From 842ee23fa4e545cf67aed94bcbe8b08e2b4613c4 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Fri, 4 Dec 2026 11:33:32 +0800 Subject: [PATCH 01/19] feat(ground-ai): add offline tank navmesh and cover baking prototype Add Stage 0 offline map geometry extraction and Recast/Detour baking tools for ground AI navigation on feat/tank-ai-nav: - Vendor upstream recastnavigation Recast and Detour sources (zlib license) under native/third_party/recastnavigation. - Define shared .wtogeo and .wtonav binary layouts in native/wto-nav/wto_nav_format.h. - Add mission-bounds.mts to collect union ground battle areas, spawns, and capture zones across mission templates. - Add Rust extractor (tools/navgen/extract) using wt-unpack and config/rendinst_dmg.blk destructionImpulse thresholds to classify hard solids, bridges, crushable objects, and tree trunks in Dagor world space. - Add multi-threaded MSVC C++ baker (tools/navgen/bake) producing 3 vehicle-width tiled Detour navmeshes, island pruning, dual-height voxel tank covers (full, hull-down, corner peek, retreat-verified), 8m tactical grids, and spawn-to-cap connectivity checks. - Add zero-dependency PNG top-down preview renderer (tools/navgen/render-preview.py). Verified: Rust release build (0 warnings), MSVC x64 baker build (0 warnings), root typecheck, and end-to-end extraction/baking/100% 3-tier connectivity and preview rendering on avg_berlin, avg_poland, and avg_hurtgen (2.61.0.58). --- .gitignore | 1 + .../Detour/Include/DetourAlloc.h | 61 + .../Detour/Include/DetourAssert.h | 56 + .../Detour/Include/DetourCommon.h | 571 +++ .../Detour/Include/DetourMath.h | 30 + .../Detour/Include/DetourNavMesh.h | 781 ++++ .../Detour/Include/DetourNavMeshBuilder.h | 149 + .../Detour/Include/DetourNavMeshQuery.h | 590 +++ .../Detour/Include/DetourNode.h | 168 + .../Detour/Include/DetourStatus.h | 65 + .../Detour/Source/DetourAlloc.cpp | 50 + .../Detour/Source/DetourAssert.cpp | 35 + .../Detour/Source/DetourCommon.cpp | 387 ++ .../Detour/Source/DetourNavMesh.cpp | 1597 +++++++ .../Detour/Source/DetourNavMeshBuilder.cpp | 802 ++++ .../Detour/Source/DetourNavMeshQuery.cpp | 3696 +++++++++++++++++ .../Detour/Source/DetourNode.cpp | 200 + .../third_party/recastnavigation/License.txt | 18 + .../recastnavigation/Recast/Include/Recast.h | 1371 ++++++ .../Recast/Include/RecastAlloc.h | 391 ++ .../Recast/Include/RecastAssert.h | 49 + .../recastnavigation/Recast/Source/Recast.cpp | 542 +++ .../Recast/Source/RecastAlloc.cpp | 51 + .../Recast/Source/RecastArea.cpp | 717 ++++ .../Recast/Source/RecastAssert.cpp | 31 + .../Recast/Source/RecastContour.cpp | 1095 +++++ .../Recast/Source/RecastFilter.cpp | 201 + .../Recast/Source/RecastLayers.cpp | 656 +++ .../Recast/Source/RecastMesh.cpp | 1541 +++++++ .../Recast/Source/RecastMeshDetail.cpp | 1476 +++++++ .../Recast/Source/RecastRasterization.cpp | 562 +++ .../Recast/Source/RecastRegion.cpp | 1820 ++++++++ native/wto-nav/wto_nav_format.h | 143 + tools/navgen/bake/bake.cpp | 1259 ++++++ tools/navgen/bake/build.ps1 | 32 + tools/navgen/extract/Cargo.lock | 534 +++ tools/navgen/extract/Cargo.toml | 16 + tools/navgen/extract/src/main.rs | 550 +++ tools/navgen/mission-bounds.mts | 278 ++ tools/navgen/render-preview.py | 252 ++ 40 files changed, 22824 insertions(+) create mode 100644 native/third_party/recastnavigation/Detour/Include/DetourAlloc.h create mode 100644 native/third_party/recastnavigation/Detour/Include/DetourAssert.h create mode 100644 native/third_party/recastnavigation/Detour/Include/DetourCommon.h create mode 100644 native/third_party/recastnavigation/Detour/Include/DetourMath.h create mode 100644 native/third_party/recastnavigation/Detour/Include/DetourNavMesh.h create mode 100644 native/third_party/recastnavigation/Detour/Include/DetourNavMeshBuilder.h create mode 100644 native/third_party/recastnavigation/Detour/Include/DetourNavMeshQuery.h create mode 100644 native/third_party/recastnavigation/Detour/Include/DetourNode.h create mode 100644 native/third_party/recastnavigation/Detour/Include/DetourStatus.h create mode 100644 native/third_party/recastnavigation/Detour/Source/DetourAlloc.cpp create mode 100644 native/third_party/recastnavigation/Detour/Source/DetourAssert.cpp create mode 100644 native/third_party/recastnavigation/Detour/Source/DetourCommon.cpp create mode 100644 native/third_party/recastnavigation/Detour/Source/DetourNavMesh.cpp create mode 100644 native/third_party/recastnavigation/Detour/Source/DetourNavMeshBuilder.cpp create mode 100644 native/third_party/recastnavigation/Detour/Source/DetourNavMeshQuery.cpp create mode 100644 native/third_party/recastnavigation/Detour/Source/DetourNode.cpp create mode 100644 native/third_party/recastnavigation/License.txt create mode 100644 native/third_party/recastnavigation/Recast/Include/Recast.h create mode 100644 native/third_party/recastnavigation/Recast/Include/RecastAlloc.h create mode 100644 native/third_party/recastnavigation/Recast/Include/RecastAssert.h create mode 100644 native/third_party/recastnavigation/Recast/Source/Recast.cpp create mode 100644 native/third_party/recastnavigation/Recast/Source/RecastAlloc.cpp create mode 100644 native/third_party/recastnavigation/Recast/Source/RecastArea.cpp create mode 100644 native/third_party/recastnavigation/Recast/Source/RecastAssert.cpp create mode 100644 native/third_party/recastnavigation/Recast/Source/RecastContour.cpp create mode 100644 native/third_party/recastnavigation/Recast/Source/RecastFilter.cpp create mode 100644 native/third_party/recastnavigation/Recast/Source/RecastLayers.cpp create mode 100644 native/third_party/recastnavigation/Recast/Source/RecastMesh.cpp create mode 100644 native/third_party/recastnavigation/Recast/Source/RecastMeshDetail.cpp create mode 100644 native/third_party/recastnavigation/Recast/Source/RecastRasterization.cpp create mode 100644 native/third_party/recastnavigation/Recast/Source/RecastRegion.cpp create mode 100644 native/wto-nav/wto_nav_format.h create mode 100644 tools/navgen/bake/bake.cpp create mode 100644 tools/navgen/bake/build.ps1 create mode 100644 tools/navgen/extract/Cargo.lock create mode 100644 tools/navgen/extract/Cargo.toml create mode 100644 tools/navgen/extract/src/main.rs create mode 100644 tools/navgen/mission-bounds.mts create mode 100644 tools/navgen/render-preview.py diff --git a/.gitignore b/.gitignore index f3c4daa..22f7385 100644 --- a/.gitignore +++ b/.gitignore @@ -18,6 +18,7 @@ aces*.exe /apps/launcher/out/ **/dist/ **/unpacked/ +tools/navgen/extract/target/ # Node node_modules/ diff --git a/native/third_party/recastnavigation/Detour/Include/DetourAlloc.h b/native/third_party/recastnavigation/Detour/Include/DetourAlloc.h new file mode 100644 index 0000000..f87b454 --- /dev/null +++ b/native/third_party/recastnavigation/Detour/Include/DetourAlloc.h @@ -0,0 +1,61 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#ifndef DETOURALLOCATOR_H +#define DETOURALLOCATOR_H + +#include + +/// Provides hint values to the memory allocator on how long the +/// memory is expected to be used. +enum dtAllocHint +{ + DT_ALLOC_PERM, ///< Memory persist after a function call. + DT_ALLOC_TEMP ///< Memory used temporarily within a function. +}; + +/// A memory allocation function. +// @param[in] size The size, in bytes of memory, to allocate. +// @param[in] rcAllocHint A hint to the allocator on how long the memory is expected to be in use. +// @return A pointer to the beginning of the allocated memory block, or null if the allocation failed. +/// @see dtAllocSetCustom +typedef void* (dtAllocFunc)(size_t size, dtAllocHint hint); + +/// A memory deallocation function. +/// @param[in] ptr A pointer to a memory block previously allocated using #dtAllocFunc. +/// @see dtAllocSetCustom +typedef void (dtFreeFunc)(void* ptr); + +/// Sets the base custom allocation functions to be used by Detour. +/// @param[in] allocFunc The memory allocation function to be used by #dtAlloc +/// @param[in] freeFunc The memory de-allocation function to be used by #dtFree +void dtAllocSetCustom(dtAllocFunc *allocFunc, dtFreeFunc *freeFunc); + +/// Allocates a memory block. +/// @param[in] size The size, in bytes of memory, to allocate. +/// @param[in] hint A hint to the allocator on how long the memory is expected to be in use. +/// @return A pointer to the beginning of the allocated memory block, or null if the allocation failed. +/// @see dtFree +void* dtAlloc(size_t size, dtAllocHint hint); + +/// Deallocates a memory block. +/// @param[in] ptr A pointer to a memory block previously allocated using #dtAlloc. +/// @see dtAlloc +void dtFree(void* ptr); + +#endif diff --git a/native/third_party/recastnavigation/Detour/Include/DetourAssert.h b/native/third_party/recastnavigation/Detour/Include/DetourAssert.h new file mode 100644 index 0000000..ea58dd9 --- /dev/null +++ b/native/third_party/recastnavigation/Detour/Include/DetourAssert.h @@ -0,0 +1,56 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#ifndef DETOURASSERT_H +#define DETOURASSERT_H + +// Note: This header file's only purpose is to include define assert. +// Feel free to change the file and include your own implementation instead. + +#ifdef RC_DISABLE_ASSERTS + +// From https://web.archive.org/web/20210117002833/http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/ +# define dtAssert(x) do { (void)sizeof(x); } while((void)(__LINE__==-1),false) + +#else + +/// An assertion failure function. +// @param[in] expression asserted expression. +// @param[in] file Filename of the failed assertion. +// @param[in] line Line number of the failed assertion. +/// @see dtAssertFailSetCustom +typedef void (dtAssertFailFunc)(const char* expression, const char* file, int line); + +/// Sets the base custom assertion failure function to be used by Detour. +/// @param[in] assertFailFunc The function to be invoked in case of failure of #dtAssert +void dtAssertFailSetCustom(dtAssertFailFunc *assertFailFunc); + +/// Gets the base custom assertion failure function to be used by Detour. +dtAssertFailFunc* dtAssertFailGetCustom(); + +# include +# define dtAssert(expression) \ + { \ + dtAssertFailFunc* failFunc = dtAssertFailGetCustom(); \ + if(failFunc == NULL) { assert(expression); } \ + else if(!(expression)) { (*failFunc)(#expression, __FILE__, __LINE__); } \ + } + +#endif + +#endif // DETOURASSERT_H diff --git a/native/third_party/recastnavigation/Detour/Include/DetourCommon.h b/native/third_party/recastnavigation/Detour/Include/DetourCommon.h new file mode 100644 index 0000000..d54bc7e --- /dev/null +++ b/native/third_party/recastnavigation/Detour/Include/DetourCommon.h @@ -0,0 +1,571 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#ifndef DETOURCOMMON_H +#define DETOURCOMMON_H + +#include "DetourMath.h" +#include + +/** +@defgroup detour Detour + +Members in this module are used to create, manipulate, and query navigation +meshes. + +@note This is a summary list of members. Use the index or search +feature to find minor members. +*/ + +/// @name General helper functions +/// @{ + +/// Used to ignore a function parameter. VS complains about unused parameters +/// and this silences the warning. +template void dtIgnoreUnused(const T&) { } + +/// Swaps the values of the two parameters. +/// @param[in,out] a Value A +/// @param[in,out] b Value B +template inline void dtSwap(T& a, T& b) { T t = a; a = b; b = t; } + +/// Returns the minimum of two values. +/// @param[in] a Value A +/// @param[in] b Value B +/// @return The minimum of the two values. +template inline T dtMin(T a, T b) { return a < b ? a : b; } + +/// Returns the maximum of two values. +/// @param[in] a Value A +/// @param[in] b Value B +/// @return The maximum of the two values. +template inline T dtMax(T a, T b) { return a > b ? a : b; } + +/// Returns the absolute value. +/// @param[in] a The value. +/// @return The absolute value of the specified value. +template inline T dtAbs(T a) { return a < 0 ? -a : a; } + +/// Returns the square of the value. +/// @param[in] a The value. +/// @return The square of the value. +template inline T dtSqr(T a) { return a*a; } + +/// Clamps the value to the specified range. +/// @param[in] v The value to clamp. +/// @param[in] mn The minimum permitted return value. +/// @param[in] mx The maximum permitted return value. +/// @return The value, clamped to the specified range. +template inline T dtClamp(T v, T mn, T mx) { return v < mn ? mn : (v > mx ? mx : v); } + +/// @} +/// @name Vector helper functions. +/// @{ + +/// Derives the cross product of two vectors. (@p v1 x @p v2) +/// @param[out] dest The cross product. [(x, y, z)] +/// @param[in] v1 A Vector [(x, y, z)] +/// @param[in] v2 A vector [(x, y, z)] +inline void dtVcross(float* dest, const float* v1, const float* v2) +{ + dest[0] = v1[1]*v2[2] - v1[2]*v2[1]; + dest[1] = v1[2]*v2[0] - v1[0]*v2[2]; + dest[2] = v1[0]*v2[1] - v1[1]*v2[0]; +} + +/// Derives the dot product of two vectors. (@p v1 . @p v2) +/// @param[in] v1 A Vector [(x, y, z)] +/// @param[in] v2 A vector [(x, y, z)] +/// @return The dot product. +inline float dtVdot(const float* v1, const float* v2) +{ + return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]; +} + +/// Performs a scaled vector addition. (@p v1 + (@p v2 * @p s)) +/// @param[out] dest The result vector. [(x, y, z)] +/// @param[in] v1 The base vector. [(x, y, z)] +/// @param[in] v2 The vector to scale and add to @p v1. [(x, y, z)] +/// @param[in] s The amount to scale @p v2 by before adding to @p v1. +inline void dtVmad(float* dest, const float* v1, const float* v2, const float s) +{ + dest[0] = v1[0]+v2[0]*s; + dest[1] = v1[1]+v2[1]*s; + dest[2] = v1[2]+v2[2]*s; +} + +/// Performs a linear interpolation between two vectors. (@p v1 toward @p v2) +/// @param[out] dest The result vector. [(x, y, x)] +/// @param[in] v1 The starting vector. +/// @param[in] v2 The destination vector. +/// @param[in] t The interpolation factor. [Limits: 0 <= value <= 1.0] +inline void dtVlerp(float* dest, const float* v1, const float* v2, const float t) +{ + dest[0] = v1[0]+(v2[0]-v1[0])*t; + dest[1] = v1[1]+(v2[1]-v1[1])*t; + dest[2] = v1[2]+(v2[2]-v1[2])*t; +} + +/// Performs a vector addition. (@p v1 + @p v2) +/// @param[out] dest The result vector. [(x, y, z)] +/// @param[in] v1 The base vector. [(x, y, z)] +/// @param[in] v2 The vector to add to @p v1. [(x, y, z)] +inline void dtVadd(float* dest, const float* v1, const float* v2) +{ + dest[0] = v1[0]+v2[0]; + dest[1] = v1[1]+v2[1]; + dest[2] = v1[2]+v2[2]; +} + +/// Performs a vector subtraction. (@p v1 - @p v2) +/// @param[out] dest The result vector. [(x, y, z)] +/// @param[in] v1 The base vector. [(x, y, z)] +/// @param[in] v2 The vector to subtract from @p v1. [(x, y, z)] +inline void dtVsub(float* dest, const float* v1, const float* v2) +{ + dest[0] = v1[0]-v2[0]; + dest[1] = v1[1]-v2[1]; + dest[2] = v1[2]-v2[2]; +} + +/// Scales the vector by the specified value. (@p v * @p t) +/// @param[out] dest The result vector. [(x, y, z)] +/// @param[in] v The vector to scale. [(x, y, z)] +/// @param[in] t The scaling factor. +inline void dtVscale(float* dest, const float* v, const float t) +{ + dest[0] = v[0]*t; + dest[1] = v[1]*t; + dest[2] = v[2]*t; +} + +/// Selects the minimum value of each element from the specified vectors. +/// @param[in,out] mn A vector. (Will be updated with the result.) [(x, y, z)] +/// @param[in] v A vector. [(x, y, z)] +inline void dtVmin(float* mn, const float* v) +{ + mn[0] = dtMin(mn[0], v[0]); + mn[1] = dtMin(mn[1], v[1]); + mn[2] = dtMin(mn[2], v[2]); +} + +/// Selects the maximum value of each element from the specified vectors. +/// @param[in,out] mx A vector. (Will be updated with the result.) [(x, y, z)] +/// @param[in] v A vector. [(x, y, z)] +inline void dtVmax(float* mx, const float* v) +{ + mx[0] = dtMax(mx[0], v[0]); + mx[1] = dtMax(mx[1], v[1]); + mx[2] = dtMax(mx[2], v[2]); +} + +/// Sets the vector elements to the specified values. +/// @param[out] dest The result vector. [(x, y, z)] +/// @param[in] x The x-value of the vector. +/// @param[in] y The y-value of the vector. +/// @param[in] z The z-value of the vector. +inline void dtVset(float* dest, const float x, const float y, const float z) +{ + dest[0] = x; dest[1] = y; dest[2] = z; +} + +/// Performs a vector copy. +/// @param[out] dest The result. [(x, y, z)] +/// @param[in] a The vector to copy. [(x, y, z)] +inline void dtVcopy(float* dest, const float* a) +{ + dest[0] = a[0]; + dest[1] = a[1]; + dest[2] = a[2]; +} + +/// Derives the scalar length of the vector. +/// @param[in] v The vector. [(x, y, z)] +/// @return The scalar length of the vector. +inline float dtVlen(const float* v) +{ + return dtMathSqrtf(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); +} + +/// Derives the square of the scalar length of the vector. (len * len) +/// @param[in] v The vector. [(x, y, z)] +/// @return The square of the scalar length of the vector. +inline float dtVlenSqr(const float* v) +{ + return v[0]*v[0] + v[1]*v[1] + v[2]*v[2]; +} + +/// Returns the distance between two points. +/// @param[in] v1 A point. [(x, y, z)] +/// @param[in] v2 A point. [(x, y, z)] +/// @return The distance between the two points. +inline float dtVdist(const float* v1, const float* v2) +{ + const float dx = v2[0] - v1[0]; + const float dy = v2[1] - v1[1]; + const float dz = v2[2] - v1[2]; + return dtMathSqrtf(dx*dx + dy*dy + dz*dz); +} + +/// Returns the square of the distance between two points. +/// @param[in] v1 A point. [(x, y, z)] +/// @param[in] v2 A point. [(x, y, z)] +/// @return The square of the distance between the two points. +inline float dtVdistSqr(const float* v1, const float* v2) +{ + const float dx = v2[0] - v1[0]; + const float dy = v2[1] - v1[1]; + const float dz = v2[2] - v1[2]; + return dx*dx + dy*dy + dz*dz; +} + +/// Derives the distance between the specified points on the xz-plane. +/// @param[in] v1 A point. [(x, y, z)] +/// @param[in] v2 A point. [(x, y, z)] +/// @return The distance between the point on the xz-plane. +/// +/// The vectors are projected onto the xz-plane, so the y-values are ignored. +inline float dtVdist2D(const float* v1, const float* v2) +{ + const float dx = v2[0] - v1[0]; + const float dz = v2[2] - v1[2]; + return dtMathSqrtf(dx*dx + dz*dz); +} + +/// Derives the square of the distance between the specified points on the xz-plane. +/// @param[in] v1 A point. [(x, y, z)] +/// @param[in] v2 A point. [(x, y, z)] +/// @return The square of the distance between the point on the xz-plane. +inline float dtVdist2DSqr(const float* v1, const float* v2) +{ + const float dx = v2[0] - v1[0]; + const float dz = v2[2] - v1[2]; + return dx*dx + dz*dz; +} + +/// Normalizes the vector. +/// @param[in,out] v The vector to normalize. [(x, y, z)] +inline void dtVnormalize(float* v) +{ + float d = 1.0f / dtMathSqrtf(dtSqr(v[0]) + dtSqr(v[1]) + dtSqr(v[2])); + v[0] *= d; + v[1] *= d; + v[2] *= d; +} + +/// Performs a 'sloppy' colocation check of the specified points. +/// @param[in] p0 A point. [(x, y, z)] +/// @param[in] p1 A point. [(x, y, z)] +/// @return True if the points are considered to be at the same location. +/// +/// Basically, this function will return true if the specified points are +/// close enough to eachother to be considered colocated. +inline bool dtVequal(const float* p0, const float* p1) +{ + static const float thr = dtSqr(1.0f/16384.0f); + const float d = dtVdistSqr(p0, p1); + return d < thr; +} + +/// Checks that the specified vector's components are all finite. +/// @param[in] v A point. [(x, y, z)] +/// @return True if all of the point's components are finite, i.e. not NaN +/// or any of the infinities. +inline bool dtVisfinite(const float* v) +{ + bool result = + dtMathIsfinite(v[0]) && + dtMathIsfinite(v[1]) && + dtMathIsfinite(v[2]); + + return result; +} + +/// Checks that the specified vector's 2D components are finite. +/// @param[in] v A point. [(x, y, z)] +inline bool dtVisfinite2D(const float* v) +{ + bool result = dtMathIsfinite(v[0]) && dtMathIsfinite(v[2]); + return result; +} + +/// Derives the dot product of two vectors on the xz-plane. (@p u . @p v) +/// @param[in] u A vector [(x, y, z)] +/// @param[in] v A vector [(x, y, z)] +/// @return The dot product on the xz-plane. +/// +/// The vectors are projected onto the xz-plane, so the y-values are ignored. +inline float dtVdot2D(const float* u, const float* v) +{ + return u[0]*v[0] + u[2]*v[2]; +} + +/// Derives the xz-plane 2D perp product of the two vectors. (uz*vx - ux*vz) +/// @param[in] u The LHV vector [(x, y, z)] +/// @param[in] v The RHV vector [(x, y, z)] +/// @return The perp dot product on the xz-plane. +/// +/// The vectors are projected onto the xz-plane, so the y-values are ignored. +inline float dtVperp2D(const float* u, const float* v) +{ + return u[2]*v[0] - u[0]*v[2]; +} + +/// @} +/// @name Computational geometry helper functions. +/// @{ + +/// Derives the signed xz-plane area of the triangle ABC, or the relationship of line AB to point C. +/// @param[in] a Vertex A. [(x, y, z)] +/// @param[in] b Vertex B. [(x, y, z)] +/// @param[in] c Vertex C. [(x, y, z)] +/// @return The signed xz-plane area of the triangle. +inline float dtTriArea2D(const float* a, const float* b, const float* c) +{ + const float abx = b[0] - a[0]; + const float abz = b[2] - a[2]; + const float acx = c[0] - a[0]; + const float acz = c[2] - a[2]; + return acx*abz - abx*acz; +} + +/// Determines if two axis-aligned bounding boxes overlap. +/// @param[in] amin Minimum bounds of box A. [(x, y, z)] +/// @param[in] amax Maximum bounds of box A. [(x, y, z)] +/// @param[in] bmin Minimum bounds of box B. [(x, y, z)] +/// @param[in] bmax Maximum bounds of box B. [(x, y, z)] +/// @return True if the two AABB's overlap. +/// @see dtOverlapBounds +inline bool dtOverlapQuantBounds(const unsigned short amin[3], const unsigned short amax[3], + const unsigned short bmin[3], const unsigned short bmax[3]) +{ + bool overlap = true; + overlap = (amin[0] > bmax[0] || amax[0] < bmin[0]) ? false : overlap; + overlap = (amin[1] > bmax[1] || amax[1] < bmin[1]) ? false : overlap; + overlap = (amin[2] > bmax[2] || amax[2] < bmin[2]) ? false : overlap; + return overlap; +} + +/// Determines if two axis-aligned bounding boxes overlap. +/// @param[in] amin Minimum bounds of box A. [(x, y, z)] +/// @param[in] amax Maximum bounds of box A. [(x, y, z)] +/// @param[in] bmin Minimum bounds of box B. [(x, y, z)] +/// @param[in] bmax Maximum bounds of box B. [(x, y, z)] +/// @return True if the two AABB's overlap. +/// @see dtOverlapQuantBounds +inline bool dtOverlapBounds(const float* amin, const float* amax, + const float* bmin, const float* bmax) +{ + bool overlap = true; + overlap = (amin[0] > bmax[0] || amax[0] < bmin[0]) ? false : overlap; + overlap = (amin[1] > bmax[1] || amax[1] < bmin[1]) ? false : overlap; + overlap = (amin[2] > bmax[2] || amax[2] < bmin[2]) ? false : overlap; + return overlap; +} + +/// Derives the closest point on a triangle from the specified reference point. +/// @param[out] closest The closest point on the triangle. +/// @param[in] p The reference point from which to test. [(x, y, z)] +/// @param[in] a Vertex A of triangle ABC. [(x, y, z)] +/// @param[in] b Vertex B of triangle ABC. [(x, y, z)] +/// @param[in] c Vertex C of triangle ABC. [(x, y, z)] +void dtClosestPtPointTriangle(float* closest, const float* p, + const float* a, const float* b, const float* c); + +/// Derives the y-axis height of the closest point on the triangle from the specified reference point. +/// @param[in] p The reference point from which to test. [(x, y, z)] +/// @param[in] a Vertex A of triangle ABC. [(x, y, z)] +/// @param[in] b Vertex B of triangle ABC. [(x, y, z)] +/// @param[in] c Vertex C of triangle ABC. [(x, y, z)] +/// @param[out] h The resulting height. +bool dtClosestHeightPointTriangle(const float* p, const float* a, const float* b, const float* c, float& h); + +bool dtIntersectSegmentPoly2D(const float* p0, const float* p1, + const float* verts, int nverts, + float& tmin, float& tmax, + int& segMin, int& segMax); + +bool dtIntersectSegSeg2D(const float* ap, const float* aq, + const float* bp, const float* bq, + float& s, float& t); + +/// Determines if the specified point is inside the convex polygon on the xz-plane. +/// @param[in] pt The point to check. [(x, y, z)] +/// @param[in] verts The polygon vertices. [(x, y, z) * @p nverts] +/// @param[in] nverts The number of vertices. [Limit: >= 3] +/// @return True if the point is inside the polygon. +bool dtPointInPolygon(const float* pt, const float* verts, const int nverts); + +bool dtDistancePtPolyEdgesSqr(const float* pt, const float* verts, const int nverts, + float* ed, float* et); + +float dtDistancePtSegSqr2D(const float* pt, const float* p, const float* q, float& t); + +/// Derives the centroid of a convex polygon. +/// @param[out] tc The centroid of the polgyon. [(x, y, z)] +/// @param[in] idx The polygon indices. [(vertIndex) * @p nidx] +/// @param[in] nidx The number of indices in the polygon. [Limit: >= 3] +/// @param[in] verts The polygon vertices. [(x, y, z) * vertCount] +void dtCalcPolyCenter(float* tc, const unsigned short* idx, int nidx, const float* verts); + +/// Determines if the two convex polygons overlap on the xz-plane. +/// @param[in] polya Polygon A vertices. [(x, y, z) * @p npolya] +/// @param[in] npolya The number of vertices in polygon A. +/// @param[in] polyb Polygon B vertices. [(x, y, z) * @p npolyb] +/// @param[in] npolyb The number of vertices in polygon B. +/// @return True if the two polygons overlap. +bool dtOverlapPolyPoly2D(const float* polya, const int npolya, + const float* polyb, const int npolyb); + +/// @} +/// @name Miscellanious functions. +/// @{ + +inline unsigned int dtNextPow2(unsigned int v) +{ + v--; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + v++; + return v; +} + +inline unsigned int dtIlog2(unsigned int v) +{ + unsigned int r; + unsigned int shift; + r = (v > 0xffff) << 4; v >>= r; + shift = (v > 0xff) << 3; v >>= shift; r |= shift; + shift = (v > 0xf) << 2; v >>= shift; r |= shift; + shift = (v > 0x3) << 1; v >>= shift; r |= shift; + r |= (v >> 1); + return r; +} + +inline int dtAlign4(int x) { return (x+3) & ~3; } + +inline int dtOppositeTile(int side) { return (side+4) & 0x7; } + +inline void dtSwapByte(unsigned char* a, unsigned char* b) +{ + unsigned char tmp = *a; + *a = *b; + *b = tmp; +} + +inline void dtSwapEndian(unsigned short* v) +{ + unsigned char* x = (unsigned char*)v; + dtSwapByte(x+0, x+1); +} + +inline void dtSwapEndian(short* v) +{ + unsigned char* x = (unsigned char*)v; + dtSwapByte(x+0, x+1); +} + +inline void dtSwapEndian(unsigned int* v) +{ + unsigned char* x = (unsigned char*)v; + dtSwapByte(x+0, x+3); dtSwapByte(x+1, x+2); +} + +inline void dtSwapEndian(int* v) +{ + unsigned char* x = (unsigned char*)v; + dtSwapByte(x+0, x+3); dtSwapByte(x+1, x+2); +} + +inline void dtSwapEndian(float* v) +{ + unsigned char* x = (unsigned char*)v; + dtSwapByte(x+0, x+3); dtSwapByte(x+1, x+2); +} + +void dtRandomPointInConvexPoly(const float* pts, const int npts, float* areas, + const float s, const float t, float* out); + +template +TypeToRetrieveAs* dtGetThenAdvanceBufferPointer(const unsigned char*& buffer, const size_t distanceToAdvance) +{ + TypeToRetrieveAs* returnPointer = reinterpret_cast(buffer); + buffer += distanceToAdvance; + return returnPointer; +} + +template +TypeToRetrieveAs* dtGetThenAdvanceBufferPointer(unsigned char*& buffer, const size_t distanceToAdvance) +{ + TypeToRetrieveAs* returnPointer = reinterpret_cast(buffer); + buffer += distanceToAdvance; + return returnPointer; +} + + +/// @} + +#endif // DETOURCOMMON_H + +/////////////////////////////////////////////////////////////////////////// + +// This section contains detailed documentation for members that don't have +// a source file. It reduces clutter in the main section of the header. + +/** + +@fn float dtTriArea2D(const float* a, const float* b, const float* c) +@par + +The vertices are projected onto the xz-plane, so the y-values are ignored. + +This is a low cost function than can be used for various purposes. Its main purpose +is for point/line relationship testing. + +In all cases: A value of zero indicates that all vertices are collinear or represent the same point. +(On the xz-plane.) + +When used for point/line relationship tests, AB usually represents a line against which +the C point is to be tested. In this case: + +A positive value indicates that point C is to the left of line AB, looking from A toward B.
+A negative value indicates that point C is to the right of lineAB, looking from A toward B. + +When used for evaluating a triangle: + +The absolute value of the return value is two times the area of the triangle when it is +projected onto the xz-plane. + +A positive return value indicates: + +
    +
  • The vertices are wrapped in the normal Detour wrap direction.
  • +
  • The triangle's 3D face normal is in the general up direction.
  • +
+ +A negative return value indicates: + +
    +
  • The vertices are reverse wrapped. (Wrapped opposite the normal Detour wrap direction.)
  • +
  • The triangle's 3D face normal is in the general down direction.
  • +
+ +*/ diff --git a/native/third_party/recastnavigation/Detour/Include/DetourMath.h b/native/third_party/recastnavigation/Detour/Include/DetourMath.h new file mode 100644 index 0000000..eec89ce --- /dev/null +++ b/native/third_party/recastnavigation/Detour/Include/DetourMath.h @@ -0,0 +1,30 @@ +/** +@defgroup detour Detour + +Members in this module are wrappers around the standard math library +*/ + +#ifndef DETOURMATH_H +#define DETOURMATH_H + +#include + +inline float dtMathFabsf(float x) { return fabsf(x); } +inline float dtMathSqrtf(float x) { return sqrtf(x); } +inline float dtMathFloorf(float x) { return floorf(x); } +inline float dtMathCeilf(float x) { return ceilf(x); } +inline float dtMathCosf(float x) { return cosf(x); } +inline float dtMathSinf(float x) { return sinf(x); } +inline float dtMathAtan2f(float y, float x) { return atan2f(y, x); } +inline bool dtMathIsfinite(float x) +{ +#ifndef RC_FAST_MATH + return isfinite(x); +#else + // Infinity and NaN are disabled when compiling with -ffast-math + (void)x; + return true; +#endif +} + +#endif diff --git a/native/third_party/recastnavigation/Detour/Include/DetourNavMesh.h b/native/third_party/recastnavigation/Detour/Include/DetourNavMesh.h new file mode 100644 index 0000000..422a334 --- /dev/null +++ b/native/third_party/recastnavigation/Detour/Include/DetourNavMesh.h @@ -0,0 +1,781 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#ifndef DETOURNAVMESH_H +#define DETOURNAVMESH_H + +#include "DetourAlloc.h" +#include "DetourStatus.h" + +// Undefine (or define in a build config) the following line to use 64bit polyref. +// Generally not needed, useful for very large worlds. +// Note: tiles build using 32bit refs are not compatible with 64bit refs! +//#define DT_POLYREF64 1 + +#ifdef DT_POLYREF64 +// TODO: figure out a multiplatform version of uint64_t +// - maybe: https://code.google.com/p/msinttypes/ +// - or: http://www.azillionmonkeys.com/qed/pstdint.h +#include +#endif + +// Note: If you want to use 64-bit refs, change the types of both dtPolyRef & dtTileRef. +// It is also recommended that you change dtHashRef() to a proper 64-bit hash. + +/// A handle to a polygon within a navigation mesh tile. +/// @ingroup detour +#ifdef DT_POLYREF64 +static const unsigned int DT_SALT_BITS = 16; +static const unsigned int DT_TILE_BITS = 28; +static const unsigned int DT_POLY_BITS = 20; +typedef uint64_t dtPolyRef; +#else +typedef unsigned int dtPolyRef; +#endif + +/// A handle to a tile within a navigation mesh. +/// @ingroup detour +#ifdef DT_POLYREF64 +typedef uint64_t dtTileRef; +#else +typedef unsigned int dtTileRef; +#endif + +/// The maximum number of vertices per navigation polygon. +/// @ingroup detour +static const int DT_VERTS_PER_POLYGON = 6; + +/// @{ +/// @name Tile Serialization Constants +/// These constants are used to detect whether a navigation tile's data +/// and state format is compatible with the current build. +/// + +/// A magic number used to detect compatibility of navigation tile data. +static const int DT_NAVMESH_MAGIC = 'D'<<24 | 'N'<<16 | 'A'<<8 | 'V'; + +/// A version number used to detect compatibility of navigation tile data. +static const int DT_NAVMESH_VERSION = 7; + +/// A magic number used to detect the compatibility of navigation tile states. +static const int DT_NAVMESH_STATE_MAGIC = 'D'<<24 | 'N'<<16 | 'M'<<8 | 'S'; + +/// A version number used to detect compatibility of navigation tile states. +static const int DT_NAVMESH_STATE_VERSION = 1; + +/// @} + +/// A flag that indicates that an entity links to an external entity. +/// (E.g. A polygon edge is a portal that links to another polygon.) +static const unsigned short DT_EXT_LINK = 0x8000; + +/// A value that indicates the entity does not link to anything. +static const unsigned int DT_NULL_LINK = 0xffffffff; + +/// A flag that indicates that an off-mesh connection can be traversed in both directions. (Is bidirectional.) +static const unsigned int DT_OFFMESH_CON_BIDIR = 1; + +/// The maximum number of user defined area ids. +/// @ingroup detour +static const int DT_MAX_AREAS = 64; + +/// Tile flags used for various functions and fields. +/// For an example, see dtNavMesh::addTile(). +enum dtTileFlags +{ + /// The navigation mesh owns the tile memory and is responsible for freeing it. + DT_TILE_FREE_DATA = 0x01 +}; + +/// Vertex flags returned by dtNavMeshQuery::findStraightPath. +enum dtStraightPathFlags +{ + DT_STRAIGHTPATH_START = 0x01, ///< The vertex is the start position in the path. + DT_STRAIGHTPATH_END = 0x02, ///< The vertex is the end position in the path. + DT_STRAIGHTPATH_OFFMESH_CONNECTION = 0x04 ///< The vertex is the start of an off-mesh connection. +}; + +/// Options for dtNavMeshQuery::findStraightPath. +enum dtStraightPathOptions +{ + DT_STRAIGHTPATH_AREA_CROSSINGS = 0x01, ///< Add a vertex at every polygon edge crossing where area changes. + DT_STRAIGHTPATH_ALL_CROSSINGS = 0x02 ///< Add a vertex at every polygon edge crossing. +}; + + +/// Options for dtNavMeshQuery::initSlicedFindPath and updateSlicedFindPath +enum dtFindPathOptions +{ + DT_FINDPATH_ANY_ANGLE = 0x02 ///< use raycasts during pathfind to "shortcut" (raycast still consider costs) +}; + +/// Options for dtNavMeshQuery::raycast +enum dtRaycastOptions +{ + DT_RAYCAST_USE_COSTS = 0x01 ///< Raycast should calculate movement cost along the ray and fill RaycastHit::cost +}; + +enum dtDetailTriEdgeFlags +{ + DT_DETAIL_EDGE_BOUNDARY = 0x01 ///< Detail triangle edge is part of the poly boundary +}; + + +/// Limit raycasting during any angle pahfinding +/// The limit is given as a multiple of the character radius +static const float DT_RAY_CAST_LIMIT_PROPORTIONS = 50.0f; + +/// Flags representing the type of a navigation mesh polygon. +enum dtPolyTypes +{ + /// The polygon is a standard convex polygon that is part of the surface of the mesh. + DT_POLYTYPE_GROUND = 0, + /// The polygon is an off-mesh connection consisting of two vertices. + DT_POLYTYPE_OFFMESH_CONNECTION = 1 +}; + + +/// Defines a polygon within a dtMeshTile object. +/// @ingroup detour +struct dtPoly +{ + /// Index to first link in linked list. (Or #DT_NULL_LINK if there is no link.) + unsigned int firstLink; + + /// The indices of the polygon's vertices. + /// The actual vertices are located in dtMeshTile::verts. + unsigned short verts[DT_VERTS_PER_POLYGON]; + + /// Packed data representing neighbor polygons references and flags for each edge. + unsigned short neis[DT_VERTS_PER_POLYGON]; + + /// The user defined polygon flags. + unsigned short flags; + + /// The number of vertices in the polygon. + unsigned char vertCount; + + /// The bit packed area id and polygon type. + /// @note Use the structure's set and get methods to access this value. + unsigned char areaAndtype; + + /// Sets the user defined area id. [Limit: < #DT_MAX_AREAS] + inline void setArea(unsigned char a) { areaAndtype = (areaAndtype & 0xc0) | (a & 0x3f); } + + /// Sets the polygon type. (See: #dtPolyTypes.) + inline void setType(unsigned char t) { areaAndtype = (areaAndtype & 0x3f) | (t << 6); } + + /// Gets the user defined area id. + inline unsigned char getArea() const { return areaAndtype & 0x3f; } + + /// Gets the polygon type. (See: #dtPolyTypes) + inline unsigned char getType() const { return areaAndtype >> 6; } +}; + +/// Defines the location of detail sub-mesh data within a dtMeshTile. +struct dtPolyDetail +{ + unsigned int vertBase; ///< The offset of the vertices in the dtMeshTile::detailVerts array. + unsigned int triBase; ///< The offset of the triangles in the dtMeshTile::detailTris array. + unsigned char vertCount; ///< The number of vertices in the sub-mesh. + unsigned char triCount; ///< The number of triangles in the sub-mesh. +}; + +/// Defines a link between polygons. +/// @note This structure is rarely if ever used by the end user. +/// @see dtMeshTile +struct dtLink +{ + dtPolyRef ref; ///< Neighbour reference. (The neighbor that is linked to.) + unsigned int next; ///< Index of the next link. + unsigned char edge; ///< Index of the polygon edge that owns this link. + unsigned char side; ///< If a boundary link, defines on which side the link is. + unsigned char bmin; ///< If a boundary link, defines the minimum sub-edge area. + unsigned char bmax; ///< If a boundary link, defines the maximum sub-edge area. +}; + +/// Bounding volume node. +/// @note This structure is rarely if ever used by the end user. +/// @see dtMeshTile +struct dtBVNode +{ + unsigned short bmin[3]; ///< Minimum bounds of the node's AABB. [(x, y, z)] + unsigned short bmax[3]; ///< Maximum bounds of the node's AABB. [(x, y, z)] + int i; ///< The node's index. (Negative for escape sequence.) +}; + +/// Defines an navigation mesh off-mesh connection within a dtMeshTile object. +/// An off-mesh connection is a user defined traversable connection made up to two vertices. +struct dtOffMeshConnection +{ + /// The endpoints of the connection. [(ax, ay, az, bx, by, bz)] + float pos[6]; + + /// The radius of the endpoints. [Limit: >= 0] + float rad; + + /// The polygon reference of the connection within the tile. + unsigned short poly; + + /// Link flags. + /// @note These are not the connection's user defined flags. Those are assigned via the + /// connection's dtPoly definition. These are link flags used for internal purposes. + unsigned char flags; + + /// End point side. + unsigned char side; + + /// The id of the offmesh connection. (User assigned when the navigation mesh is built.) + unsigned int userId; +}; + +/// Provides high level information related to a dtMeshTile object. +/// @ingroup detour +struct dtMeshHeader +{ + int magic; ///< Tile magic number. (Used to identify the data format.) + int version; ///< Tile data format version number. + int x; ///< The x-position of the tile within the dtNavMesh tile grid. (x, y, layer) + int y; ///< The y-position of the tile within the dtNavMesh tile grid. (x, y, layer) + int layer; ///< The layer of the tile within the dtNavMesh tile grid. (x, y, layer) + unsigned int userId; ///< The user defined id of the tile. + int polyCount; ///< The number of polygons in the tile. + int vertCount; ///< The number of vertices in the tile. + int maxLinkCount; ///< The number of allocated links. + int detailMeshCount; ///< The number of sub-meshes in the detail mesh. + + /// The number of unique vertices in the detail mesh. (In addition to the polygon vertices.) + int detailVertCount; + + int detailTriCount; ///< The number of triangles in the detail mesh. + int bvNodeCount; ///< The number of bounding volume nodes. (Zero if bounding volumes are disabled.) + int offMeshConCount; ///< The number of off-mesh connections. + int offMeshBase; ///< The index of the first polygon which is an off-mesh connection. + float walkableHeight; ///< The height of the agents using the tile. + float walkableRadius; ///< The radius of the agents using the tile. + float walkableClimb; ///< The maximum climb height of the agents using the tile. + float bmin[3]; ///< The minimum bounds of the tile's AABB. [(x, y, z)] + float bmax[3]; ///< The maximum bounds of the tile's AABB. [(x, y, z)] + + /// The bounding volume quantization factor. + float bvQuantFactor; +}; + +/// Defines a navigation mesh tile. +/// @ingroup detour +struct dtMeshTile +{ + unsigned int salt; ///< Counter describing modifications to the tile. + + unsigned int linksFreeList; ///< Index to the next free link. + dtMeshHeader* header; ///< The tile header. + dtPoly* polys; ///< The tile polygons. [Size: dtMeshHeader::polyCount] + float* verts; ///< The tile vertices. [(x, y, z) * dtMeshHeader::vertCount] + dtLink* links; ///< The tile links. [Size: dtMeshHeader::maxLinkCount] + dtPolyDetail* detailMeshes; ///< The tile's detail sub-meshes. [Size: dtMeshHeader::detailMeshCount] + + /// The detail mesh's unique vertices. [(x, y, z) * dtMeshHeader::detailVertCount] + float* detailVerts; + + /// The detail mesh's triangles. [(vertA, vertB, vertC, triFlags) * dtMeshHeader::detailTriCount]. + /// See dtDetailTriEdgeFlags and dtGetDetailTriEdgeFlags. + unsigned char* detailTris; + + /// The tile bounding volume nodes. [Size: dtMeshHeader::bvNodeCount] + /// (Will be null if bounding volumes are disabled.) + dtBVNode* bvTree; + + dtOffMeshConnection* offMeshCons; ///< The tile off-mesh connections. [Size: dtMeshHeader::offMeshConCount] + + unsigned char* data; ///< The tile data. (Not directly accessed under normal situations.) + int dataSize; ///< Size of the tile data. + int flags; ///< Tile flags. (See: #dtTileFlags) + dtMeshTile* next; ///< The next free tile, or the next tile in the spatial grid. +}; + +/// Get flags for edge in detail triangle. +/// @param[in] triFlags The flags for the triangle (last component of detail vertices above). +/// @param[in] edgeIndex The index of the first vertex of the edge. For instance, if 0, +/// returns flags for edge AB. +inline int dtGetDetailTriEdgeFlags(unsigned char triFlags, int edgeIndex) +{ + return (triFlags >> (edgeIndex * 2)) & 0x3; +} + +/// Configuration parameters used to define multi-tile navigation meshes. +/// The values are used to allocate space during the initialization of a navigation mesh. +/// @see dtNavMesh::init() +/// @ingroup detour +struct dtNavMeshParams +{ + float orig[3]; ///< The world space origin of the navigation mesh's tile space. [(x, y, z)] + float tileWidth; ///< The width of each tile. (Along the x-axis.) + float tileHeight; ///< The height of each tile. (Along the z-axis.) + int maxTiles; ///< The maximum number of tiles the navigation mesh can contain. This and maxPolys are used to calculate how many bits are needed to identify tiles and polygons uniquely. + int maxPolys; ///< The maximum number of polygons each tile can contain. This and maxTiles are used to calculate how many bits are needed to identify tiles and polygons uniquely. +}; + +/// A navigation mesh based on tiles of convex polygons. +/// @ingroup detour +class dtNavMesh +{ +public: + dtNavMesh(); + ~dtNavMesh(); + + /// @{ + /// @name Initialization and Tile Management + + /// Initializes the navigation mesh for tiled use. + /// @param[in] params Initialization parameters. + /// @return The status flags for the operation. + dtStatus init(const dtNavMeshParams* params); + + /// Initializes the navigation mesh for single tile use. + /// @param[in] data Data of the new tile. (See: #dtCreateNavMeshData) + /// @param[in] dataSize The data size of the new tile. + /// @param[in] flags The tile flags. (See: #dtTileFlags) + /// @return The status flags for the operation. + /// @see dtCreateNavMeshData + dtStatus init(unsigned char* data, const int dataSize, const int flags); + + /// The navigation mesh initialization params. + const dtNavMeshParams* getParams() const; + + /// Adds a tile to the navigation mesh. + /// @param[in] data Data for the new tile mesh. (See: #dtCreateNavMeshData) + /// @param[in] dataSize Data size of the new tile mesh. + /// @param[in] flags Tile flags. (See: #dtTileFlags) + /// @param[in] lastRef The desired reference for the tile. (When reloading a tile.) [opt] [Default: 0] + /// @param[out] result The tile reference. (If the tile was succesfully added.) [opt] + /// @return The status flags for the operation. + dtStatus addTile(unsigned char* data, int dataSize, int flags, dtTileRef lastRef, dtTileRef* result); + + /// Removes the specified tile from the navigation mesh. + /// @param[in] ref The reference of the tile to remove. + /// @param[out] data Data associated with deleted tile. + /// @param[out] dataSize Size of the data associated with deleted tile. + /// @return The status flags for the operation. + dtStatus removeTile(dtTileRef ref, unsigned char** data, int* dataSize); + + /// @} + + /// @{ + /// @name Query Functions + + /// Calculates the tile grid location for the specified world position. + /// @param[in] pos The world position for the query. [(x, y, z)] + /// @param[out] tx The tile's x-location. (x, y) + /// @param[out] ty The tile's y-location. (x, y) + void calcTileLoc(const float* pos, int* tx, int* ty) const; + + /// Gets the tile at the specified grid location. + /// @param[in] x The tile's x-location. (x, y, layer) + /// @param[in] y The tile's y-location. (x, y, layer) + /// @param[in] layer The tile's layer. (x, y, layer) + /// @return The tile, or null if the tile does not exist. + const dtMeshTile* getTileAt(const int x, const int y, const int layer) const; + + /// Gets all tiles at the specified grid location. (All layers.) + /// @param[in] x The tile's x-location. (x, y) + /// @param[in] y The tile's y-location. (x, y) + /// @param[out] tiles A pointer to an array of tiles that will hold the result. + /// @param[in] maxTiles The maximum tiles the tiles parameter can hold. + /// @return The number of tiles returned in the tiles array. + int getTilesAt(const int x, const int y, + dtMeshTile const** tiles, const int maxTiles) const; + + /// Gets the tile reference for the tile at specified grid location. + /// @param[in] x The tile's x-location. (x, y, layer) + /// @param[in] y The tile's y-location. (x, y, layer) + /// @param[in] layer The tile's layer. (x, y, layer) + /// @return The tile reference of the tile, or 0 if there is none. + dtTileRef getTileRefAt(int x, int y, int layer) const; + + /// Gets the tile reference for the specified tile. + /// @param[in] tile The tile. + /// @return The tile reference of the tile. + dtTileRef getTileRef(const dtMeshTile* tile) const; + + /// Gets the tile for the specified tile reference. + /// @param[in] ref The tile reference of the tile to retrieve. + /// @return The tile for the specified reference, or null if the + /// reference is invalid. + const dtMeshTile* getTileByRef(dtTileRef ref) const; + + /// The maximum number of tiles supported by the navigation mesh. + /// @return The maximum number of tiles supported by the navigation mesh. + int getMaxTiles() const; + + /// Gets the tile at the specified index. + /// @param[in] i The tile index. [Limit: 0 >= index < #getMaxTiles()] + /// @return The tile at the specified index. + const dtMeshTile* getTile(int i) const; + + /// Gets the tile and polygon for the specified polygon reference. + /// @param[in] ref The reference for the a polygon. + /// @param[out] tile The tile containing the polygon. + /// @param[out] poly The polygon. + /// @return The status flags for the operation. + dtStatus getTileAndPolyByRef(const dtPolyRef ref, const dtMeshTile** tile, const dtPoly** poly) const; + + /// Returns the tile and polygon for the specified polygon reference. + /// @param[in] ref A known valid reference for a polygon. + /// @param[out] tile The tile containing the polygon. + /// @param[out] poly The polygon. + void getTileAndPolyByRefUnsafe(const dtPolyRef ref, const dtMeshTile** tile, const dtPoly** poly) const; + + /// Checks the validity of a polygon reference. + /// @param[in] ref The polygon reference to check. + /// @return True if polygon reference is valid for the navigation mesh. + bool isValidPolyRef(dtPolyRef ref) const; + + /// Gets the polygon reference for the tile's base polygon. + /// @param[in] tile The tile. + /// @return The polygon reference for the base polygon in the specified tile. + dtPolyRef getPolyRefBase(const dtMeshTile* tile) const; + + /// Gets the endpoints for an off-mesh connection, ordered by "direction of travel". + /// @param[in] prevRef The reference of the polygon before the connection. + /// @param[in] polyRef The reference of the off-mesh connection polygon. + /// @param[out] startPos The start position of the off-mesh connection. [(x, y, z)] + /// @param[out] endPos The end position of the off-mesh connection. [(x, y, z)] + /// @return The status flags for the operation. + dtStatus getOffMeshConnectionPolyEndPoints(dtPolyRef prevRef, dtPolyRef polyRef, float* startPos, float* endPos) const; + + /// Gets the specified off-mesh connection. + /// @param[in] ref The polygon reference of the off-mesh connection. + /// @return The specified off-mesh connection, or null if the polygon reference is not valid. + const dtOffMeshConnection* getOffMeshConnectionByRef(dtPolyRef ref) const; + + /// @} + + /// @{ + /// @name State Management + /// These functions do not effect #dtTileRef or #dtPolyRef's. + + /// Sets the user defined flags for the specified polygon. + /// @param[in] ref The polygon reference. + /// @param[in] flags The new flags for the polygon. + /// @return The status flags for the operation. + dtStatus setPolyFlags(dtPolyRef ref, unsigned short flags); + + /// Gets the user defined flags for the specified polygon. + /// @param[in] ref The polygon reference. + /// @param[out] resultFlags The polygon flags. + /// @return The status flags for the operation. + dtStatus getPolyFlags(dtPolyRef ref, unsigned short* resultFlags) const; + + /// Sets the user defined area for the specified polygon. + /// @param[in] ref The polygon reference. + /// @param[in] area The new area id for the polygon. [Limit: < #DT_MAX_AREAS] + /// @return The status flags for the operation. + dtStatus setPolyArea(dtPolyRef ref, unsigned char area); + + /// Gets the user defined area for the specified polygon. + /// @param[in] ref The polygon reference. + /// @param[out] resultArea The area id for the polygon. + /// @return The status flags for the operation. + dtStatus getPolyArea(dtPolyRef ref, unsigned char* resultArea) const; + + /// Gets the size of the buffer required by #storeTileState to store the specified tile's state. + /// @param[in] tile The tile. + /// @return The size of the buffer required to store the state. + int getTileStateSize(const dtMeshTile* tile) const; + + /// Stores the non-structural state of the tile in the specified buffer. (Flags, area ids, etc.) + /// @param[in] tile The tile. + /// @param[out] data The buffer to store the tile's state in. + /// @param[in] maxDataSize The size of the data buffer. [Limit: >= #getTileStateSize] + /// @return The status flags for the operation. + dtStatus storeTileState(const dtMeshTile* tile, unsigned char* data, const int maxDataSize) const; + + /// Restores the state of the tile. + /// @param[in] tile The tile. + /// @param[in] data The new state. (Obtained from #storeTileState.) + /// @param[in] maxDataSize The size of the state within the data buffer. + /// @return The status flags for the operation. + dtStatus restoreTileState(dtMeshTile* tile, const unsigned char* data, const int maxDataSize); + + /// @} + + /// @{ + /// @name Encoding and Decoding + /// These functions are generally meant for internal use only. + + /// Derives a standard polygon reference. + /// @note This function is generally meant for internal use only. + /// @param[in] salt The tile's salt value. + /// @param[in] it The index of the tile. + /// @param[in] ip The index of the polygon within the tile. + inline dtPolyRef encodePolyId(unsigned int salt, unsigned int it, unsigned int ip) const + { +#ifdef DT_POLYREF64 + return ((dtPolyRef)salt << (DT_POLY_BITS+DT_TILE_BITS)) | ((dtPolyRef)it << DT_POLY_BITS) | (dtPolyRef)ip; +#else + return ((dtPolyRef)salt << (m_polyBits+m_tileBits)) | ((dtPolyRef)it << m_polyBits) | (dtPolyRef)ip; +#endif + } + + /// Decodes a standard polygon reference. + /// @note This function is generally meant for internal use only. + /// @param[in] ref The polygon reference to decode. + /// @param[out] salt The tile's salt value. + /// @param[out] it The index of the tile. + /// @param[out] ip The index of the polygon within the tile. + /// @see #encodePolyId + inline void decodePolyId(dtPolyRef ref, unsigned int& salt, unsigned int& it, unsigned int& ip) const + { +#ifdef DT_POLYREF64 + const dtPolyRef saltMask = ((dtPolyRef)1<> (DT_POLY_BITS+DT_TILE_BITS)) & saltMask); + it = (unsigned int)((ref >> DT_POLY_BITS) & tileMask); + ip = (unsigned int)(ref & polyMask); +#else + const dtPolyRef saltMask = ((dtPolyRef)1<> (m_polyBits+m_tileBits)) & saltMask); + it = (unsigned int)((ref >> m_polyBits) & tileMask); + ip = (unsigned int)(ref & polyMask); +#endif + } + + /// Extracts a tile's salt value from the specified polygon reference. + /// @note This function is generally meant for internal use only. + /// @param[in] ref The polygon reference. + /// @see #encodePolyId + inline unsigned int decodePolyIdSalt(dtPolyRef ref) const + { +#ifdef DT_POLYREF64 + const dtPolyRef saltMask = ((dtPolyRef)1<> (DT_POLY_BITS+DT_TILE_BITS)) & saltMask); +#else + const dtPolyRef saltMask = ((dtPolyRef)1<> (m_polyBits+m_tileBits)) & saltMask); +#endif + } + + /// Extracts the tile's index from the specified polygon reference. + /// @note This function is generally meant for internal use only. + /// @param[in] ref The polygon reference. + /// @see #encodePolyId + inline unsigned int decodePolyIdTile(dtPolyRef ref) const + { +#ifdef DT_POLYREF64 + const dtPolyRef tileMask = ((dtPolyRef)1<> DT_POLY_BITS) & tileMask); +#else + const dtPolyRef tileMask = ((dtPolyRef)1<> m_polyBits) & tileMask); +#endif + } + + /// Extracts the polygon's index (within its tile) from the specified polygon reference. + /// @note This function is generally meant for internal use only. + /// @param[in] ref The polygon reference. + /// @see #encodePolyId + inline unsigned int decodePolyIdPoly(dtPolyRef ref) const + { +#ifdef DT_POLYREF64 + const dtPolyRef polyMask = ((dtPolyRef)1<header->bvQuantFactor; +const dtBVNode* n = &tile->bvTree[i]; +if (n->i >= 0) +{ + // This is a leaf node. + float worldMinX = tile->header->bmin[0] + n->bmin[0]*cs; + float worldMinY = tile->header->bmin[0] + n->bmin[1]*cs; + // Etc... +} +@endcode + +@struct dtMeshTile +@par + +Tiles generally only exist within the context of a dtNavMesh object. + +Some tile content is optional. For example, a tile may not contain any +off-mesh connections. In this case the associated pointer will be null. + +If a detail mesh exists it will share vertices with the base polygon mesh. +Only the vertices unique to the detail mesh will be stored in #detailVerts. + +@warning Tiles returned by a dtNavMesh object are not guarenteed to be populated. +For example: The tile at a location might not have been loaded yet, or may have been removed. +In this case, pointers will be null. So if in doubt, check the polygon count in the +tile's header to determine if a tile has polygons defined. + +@var float dtOffMeshConnection::pos[6] +@par + +For a properly built navigation mesh, vertex A will always be within the bounds of the mesh. +Vertex B is not required to be within the bounds of the mesh. + +*/ diff --git a/native/third_party/recastnavigation/Detour/Include/DetourNavMeshBuilder.h b/native/third_party/recastnavigation/Detour/Include/DetourNavMeshBuilder.h new file mode 100644 index 0000000..1840ab5 --- /dev/null +++ b/native/third_party/recastnavigation/Detour/Include/DetourNavMeshBuilder.h @@ -0,0 +1,149 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#ifndef DETOURNAVMESHBUILDER_H +#define DETOURNAVMESHBUILDER_H + +#include "DetourAlloc.h" + +/// Represents the source data used to build an navigation mesh tile. +/// @ingroup detour +struct dtNavMeshCreateParams +{ + + /// @name Polygon Mesh Attributes + /// Used to create the base navigation graph. + /// See #rcPolyMesh for details related to these attributes. + /// @{ + + const unsigned short* verts; ///< The polygon mesh vertices. [(x, y, z) * #vertCount] [Unit: vx] + int vertCount; ///< The number vertices in the polygon mesh. [Limit: >= 3] + const unsigned short* polys; ///< The polygon data. [Size: #polyCount * 2 * #nvp] + const unsigned short* polyFlags; ///< The user defined flags assigned to each polygon. [Size: #polyCount] + const unsigned char* polyAreas; ///< The user defined area ids assigned to each polygon. [Size: #polyCount] + int polyCount; ///< Number of polygons in the mesh. [Limit: >= 1] + int nvp; ///< Number maximum number of vertices per polygon. [Limit: >= 3] + + /// @} + /// @name Height Detail Attributes (Optional) + /// See #rcPolyMeshDetail for details related to these attributes. + /// @{ + + const unsigned int* detailMeshes; ///< The height detail sub-mesh data. [Size: 4 * #polyCount] + const float* detailVerts; ///< The detail mesh vertices. [Size: 3 * #detailVertsCount] [Unit: wu] + int detailVertsCount; ///< The number of vertices in the detail mesh. + const unsigned char* detailTris; ///< The detail mesh triangles. [Size: 4 * #detailTriCount] + int detailTriCount; ///< The number of triangles in the detail mesh. + + /// @} + /// @name Off-Mesh Connections Attributes (Optional) + /// Used to define a custom point-to-point edge within the navigation graph, an + /// off-mesh connection is a user defined traversable connection made up to two vertices, + /// at least one of which resides within a navigation mesh polygon. + /// @{ + + /// Off-mesh connection vertices. [(ax, ay, az, bx, by, bz) * #offMeshConCount] [Unit: wu] + const float* offMeshConVerts; + /// Off-mesh connection radii. [Size: #offMeshConCount] [Unit: wu] + const float* offMeshConRad; + /// User defined flags assigned to the off-mesh connections. [Size: #offMeshConCount] + const unsigned short* offMeshConFlags; + /// User defined area ids assigned to the off-mesh connections. [Size: #offMeshConCount] + const unsigned char* offMeshConAreas; + /// The permitted travel direction of the off-mesh connections. [Size: #offMeshConCount] + /// + /// 0 = Travel only from endpoint A to endpoint B.
+ /// #DT_OFFMESH_CON_BIDIR = Bidirectional travel. + const unsigned char* offMeshConDir; + /// The user defined ids of the off-mesh connection. [Size: #offMeshConCount] + const unsigned int* offMeshConUserID; + /// The number of off-mesh connections. [Limit: >= 0] + int offMeshConCount; + + /// @} + /// @name Tile Attributes + /// @note The tile grid/layer data can be left at zero if the destination is a single tile mesh. + /// @{ + + unsigned int userId; ///< The user defined id of the tile. + int tileX; ///< The tile's x-grid location within the multi-tile destination mesh. (Along the x-axis.) + int tileY; ///< The tile's y-grid location within the multi-tile destination mesh. (Along the z-axis.) + int tileLayer; ///< The tile's layer within the layered destination mesh. [Limit: >= 0] (Along the y-axis.) + float bmin[3]; ///< The minimum bounds of the tile. [(x, y, z)] [Unit: wu] + float bmax[3]; ///< The maximum bounds of the tile. [(x, y, z)] [Unit: wu] + + /// @} + /// @name General Configuration Attributes + /// @{ + + float walkableHeight; ///< The agent height. [Unit: wu] + float walkableRadius; ///< The agent radius. [Unit: wu] + float walkableClimb; ///< The agent maximum traversable ledge. (Up/Down) [Unit: wu] + float cs; ///< The xz-plane cell size of the polygon mesh. [Limit: > 0] [Unit: wu] + float ch; ///< The y-axis cell height of the polygon mesh. [Limit: > 0] [Unit: wu] + + /// True if a bounding volume tree should be built for the tile. + /// @note The BVTree is not normally needed for layered navigation meshes. + bool buildBvTree; + + /// @} +}; + +/// Builds navigation mesh tile data from the provided tile creation data. +/// @ingroup detour +/// @param[in] params Tile creation data. +/// @param[out] outData The resulting tile data. +/// @param[out] outDataSize The size of the tile data array. +/// @return True if the tile data was successfully created. +bool dtCreateNavMeshData(dtNavMeshCreateParams* params, unsigned char** outData, int* outDataSize); + +/// Swaps the endianness of the tile data's header (#dtMeshHeader). +/// @param[in,out] data The tile data array. +/// @param[in] dataSize The size of the data array. +bool dtNavMeshHeaderSwapEndian(unsigned char* data, const int dataSize); + +/// Swaps endianness of the tile data. +/// @param[in,out] data The tile data array. +/// @param[in] dataSize The size of the data array. +bool dtNavMeshDataSwapEndian(unsigned char* data, const int dataSize); + +#endif // DETOURNAVMESHBUILDER_H + +// This section contains detailed documentation for members that don't have +// a source file. It reduces clutter in the main section of the header. + +/** + +@struct dtNavMeshCreateParams +@par + +This structure is used to marshal data between the Recast mesh generation pipeline and Detour navigation components. + +See the rcPolyMesh and rcPolyMeshDetail documentation for detailed information related to mesh structure. + +Units are usually in voxels (vx) or world units (wu). The units for voxels, grid size, and cell size +are all based on the values of #cs and #ch. + +The standard navigation mesh build process is to create tile data using dtCreateNavMeshData, then add the tile +to a navigation mesh using either the dtNavMesh single tile init() function or the dtNavMesh::addTile() +function. + +@see dtCreateNavMeshData + +*/ + diff --git a/native/third_party/recastnavigation/Detour/Include/DetourNavMeshQuery.h b/native/third_party/recastnavigation/Detour/Include/DetourNavMeshQuery.h new file mode 100644 index 0000000..dd8150c --- /dev/null +++ b/native/third_party/recastnavigation/Detour/Include/DetourNavMeshQuery.h @@ -0,0 +1,590 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#ifndef DETOURNAVMESHQUERY_H +#define DETOURNAVMESHQUERY_H + +#include "DetourNavMesh.h" +#include "DetourStatus.h" + + +// Define DT_VIRTUAL_QUERYFILTER if you wish to derive a custom filter from dtQueryFilter. +// On certain platforms indirect or virtual function call is expensive. The default +// setting is to use non-virtual functions, the actual implementations of the functions +// are declared as inline for maximum speed. + +//#define DT_VIRTUAL_QUERYFILTER 1 + +/// Defines polygon filtering and traversal costs for navigation mesh query operations. +/// @ingroup detour +class dtQueryFilter +{ + float m_areaCost[DT_MAX_AREAS]; ///< Cost per area type. (Used by default implementation.) + unsigned short m_includeFlags; ///< Flags for polygons that can be visited. (Used by default implementation.) + unsigned short m_excludeFlags; ///< Flags for polygons that should not be visited. (Used by default implementation.) + +public: + dtQueryFilter(); + +#ifdef DT_VIRTUAL_QUERYFILTER + virtual ~dtQueryFilter() { } +#endif + + /// Returns true if the polygon can be visited. (I.e. Is traversable.) + /// @param[in] ref The reference id of the polygon test. + /// @param[in] tile The tile containing the polygon. + /// @param[in] poly The polygon to test. +#ifdef DT_VIRTUAL_QUERYFILTER + virtual bool passFilter(const dtPolyRef ref, + const dtMeshTile* tile, + const dtPoly* poly) const; +#else + bool passFilter(const dtPolyRef ref, + const dtMeshTile* tile, + const dtPoly* poly) const; +#endif + + /// Returns cost to move from the beginning to the end of a line segment + /// that is fully contained within a polygon. + /// @param[in] pa The start position on the edge of the previous and current polygon. [(x, y, z)] + /// @param[in] pb The end position on the edge of the current and next polygon. [(x, y, z)] + /// @param[in] prevRef The reference id of the previous polygon. [opt] + /// @param[in] prevTile The tile containing the previous polygon. [opt] + /// @param[in] prevPoly The previous polygon. [opt] + /// @param[in] curRef The reference id of the current polygon. + /// @param[in] curTile The tile containing the current polygon. + /// @param[in] curPoly The current polygon. + /// @param[in] nextRef The refernece id of the next polygon. [opt] + /// @param[in] nextTile The tile containing the next polygon. [opt] + /// @param[in] nextPoly The next polygon. [opt] +#ifdef DT_VIRTUAL_QUERYFILTER + virtual float getCost(const float* pa, const float* pb, + const dtPolyRef prevRef, const dtMeshTile* prevTile, const dtPoly* prevPoly, + const dtPolyRef curRef, const dtMeshTile* curTile, const dtPoly* curPoly, + const dtPolyRef nextRef, const dtMeshTile* nextTile, const dtPoly* nextPoly) const; +#else + float getCost(const float* pa, const float* pb, + const dtPolyRef prevRef, const dtMeshTile* prevTile, const dtPoly* prevPoly, + const dtPolyRef curRef, const dtMeshTile* curTile, const dtPoly* curPoly, + const dtPolyRef nextRef, const dtMeshTile* nextTile, const dtPoly* nextPoly) const; +#endif + + /// @name Getters and setters for the default implementation data. + ///@{ + + /// Returns the traversal cost of the area. + /// @param[in] i The id of the area. + /// @returns The traversal cost of the area. + inline float getAreaCost(const int i) const { return m_areaCost[i]; } + + /// Sets the traversal cost of the area. + /// @param[in] i The id of the area. + /// @param[in] cost The new cost of traversing the area. + inline void setAreaCost(const int i, const float cost) { m_areaCost[i] = cost; } + + /// Returns the include flags for the filter. + /// Any polygons that include one or more of these flags will be + /// included in the operation. + inline unsigned short getIncludeFlags() const { return m_includeFlags; } + + /// Sets the include flags for the filter. + /// @param[in] flags The new flags. + inline void setIncludeFlags(const unsigned short flags) { m_includeFlags = flags; } + + /// Returns the exclude flags for the filter. + /// Any polygons that include one ore more of these flags will be + /// excluded from the operation. + inline unsigned short getExcludeFlags() const { return m_excludeFlags; } + + /// Sets the exclude flags for the filter. + /// @param[in] flags The new flags. + inline void setExcludeFlags(const unsigned short flags) { m_excludeFlags = flags; } + + ///@} + +}; + +/// Provides information about raycast hit +/// filled by dtNavMeshQuery::raycast +/// @ingroup detour +struct dtRaycastHit +{ + /// The hit parameter. (FLT_MAX if no wall hit.) + float t; + + /// hitNormal The normal of the nearest wall hit. [(x, y, z)] + float hitNormal[3]; + + /// The index of the edge on the final polygon where the wall was hit. + int hitEdgeIndex; + + /// Pointer to an array of reference ids of the visited polygons. [opt] + dtPolyRef* path; + + /// The number of visited polygons. [opt] + int pathCount; + + /// The maximum number of polygons the @p path array can hold. + int maxPath; + + /// The cost of the path until hit. + float pathCost; +}; + +/// Provides custom polygon query behavior. +/// Used by dtNavMeshQuery::queryPolygons. +/// @ingroup detour +class dtPolyQuery +{ +public: + virtual ~dtPolyQuery(); + + /// Called for each batch of unique polygons touched by the search area in dtNavMeshQuery::queryPolygons. + /// This can be called multiple times for a single query. + virtual void process(const dtMeshTile* tile, dtPoly** polys, dtPolyRef* refs, int count) = 0; +}; + +/// Provides the ability to perform pathfinding related queries against +/// a navigation mesh. +/// @ingroup detour +class dtNavMeshQuery +{ +public: + dtNavMeshQuery(); + ~dtNavMeshQuery(); + + /// Initializes the query object. + /// @param[in] nav Pointer to the dtNavMesh object to use for all queries. + /// @param[in] maxNodes Maximum number of search nodes. [Limits: 0 < value <= 65535] + /// @returns The status flags for the query. + dtStatus init(const dtNavMesh* nav, const int maxNodes); + + /// @name Standard Pathfinding Functions + /// @{ + + /// Finds a path from the start polygon to the end polygon. + /// @param[in] startRef The reference id of the start polygon. + /// @param[in] endRef The reference id of the end polygon. + /// @param[in] startPos A position within the start polygon. [(x, y, z)] + /// @param[in] endPos A position within the end polygon. [(x, y, z)] + /// @param[in] filter The polygon filter to apply to the query. + /// @param[out] path An ordered list of polygon references representing the path. (Start to end.) + /// [(polyRef) * @p pathCount] + /// @param[out] pathCount The number of polygons returned in the @p path array. + /// @param[in] maxPath The maximum number of polygons the @p path array can hold. [Limit: >= 1] + dtStatus findPath(dtPolyRef startRef, dtPolyRef endRef, + const float* startPos, const float* endPos, + const dtQueryFilter* filter, + dtPolyRef* path, int* pathCount, const int maxPath) const; + + /// Finds the straight path from the start to the end position within the polygon corridor. + /// @param[in] startPos Path start position. [(x, y, z)] + /// @param[in] endPos Path end position. [(x, y, z)] + /// @param[in] path An array of polygon references that represent the path corridor. + /// @param[in] pathSize The number of polygons in the @p path array. + /// @param[out] straightPath Points describing the straight path. [(x, y, z) * @p straightPathCount]. + /// @param[out] straightPathFlags Flags describing each point. (See: #dtStraightPathFlags) [opt] + /// @param[out] straightPathRefs The reference id of the polygon that is being entered at each point. [opt] + /// @param[out] straightPathCount The number of points in the straight path. + /// @param[in] maxStraightPath The maximum number of points the straight path arrays can hold. [Limit: > 0] + /// @param[in] options Query options. (see: #dtStraightPathOptions) + /// @returns The status flags for the query. + dtStatus findStraightPath(const float* startPos, const float* endPos, + const dtPolyRef* path, const int pathSize, + float* straightPath, unsigned char* straightPathFlags, dtPolyRef* straightPathRefs, + int* straightPathCount, const int maxStraightPath, const int options = 0) const; + + ///@} + /// @name Sliced Pathfinding Functions + /// Common use case: + /// -# Call initSlicedFindPath() to initialize the sliced path query. + /// -# Call updateSlicedFindPath() until it returns complete. + /// -# Call finalizeSlicedFindPath() to get the path. + ///@{ + + /// Initializes a sliced path query. + /// @param[in] startRef The reference id of the start polygon. + /// @param[in] endRef The reference id of the end polygon. + /// @param[in] startPos A position within the start polygon. [(x, y, z)] + /// @param[in] endPos A position within the end polygon. [(x, y, z)] + /// @param[in] filter The polygon filter to apply to the query. + /// @param[in] options query options (see: #dtFindPathOptions) + /// @returns The status flags for the query. + dtStatus initSlicedFindPath(dtPolyRef startRef, dtPolyRef endRef, + const float* startPos, const float* endPos, + const dtQueryFilter* filter, const unsigned int options = 0); + + /// Updates an in-progress sliced path query. + /// @param[in] maxIter The maximum number of iterations to perform. + /// @param[out] doneIters The actual number of iterations completed. [opt] + /// @returns The status flags for the query. + dtStatus updateSlicedFindPath(const int maxIter, int* doneIters); + + /// Finalizes and returns the results of a sliced path query. + /// @param[out] path An ordered list of polygon references representing the path. (Start to end.) + /// [(polyRef) * @p pathCount] + /// @param[out] pathCount The number of polygons returned in the @p path array. + /// @param[in] maxPath The max number of polygons the path array can hold. [Limit: >= 1] + /// @returns The status flags for the query. + dtStatus finalizeSlicedFindPath(dtPolyRef* path, int* pathCount, const int maxPath); + + /// Finalizes and returns the results of an incomplete sliced path query, returning the path to the furthest + /// polygon on the existing path that was visited during the search. + /// @param[in] existing An array of polygon references for the existing path. + /// @param[in] existingSize The number of polygon in the @p existing array. + /// @param[out] path An ordered list of polygon references representing the path. (Start to end.) + /// [(polyRef) * @p pathCount] + /// @param[out] pathCount The number of polygons returned in the @p path array. + /// @param[in] maxPath The max number of polygons the @p path array can hold. [Limit: >= 1] + /// @returns The status flags for the query. + dtStatus finalizeSlicedFindPathPartial(const dtPolyRef* existing, const int existingSize, + dtPolyRef* path, int* pathCount, const int maxPath); + + ///@} + /// @name Dijkstra Search Functions + /// @{ + + /// Finds the polygons along the navigation graph that touch the specified circle. + /// @param[in] startRef The reference id of the polygon where the search starts. + /// @param[in] centerPos The center of the search circle. [(x, y, z)] + /// @param[in] radius The radius of the search circle. + /// @param[in] filter The polygon filter to apply to the query. + /// @param[out] resultRef The reference ids of the polygons touched by the circle. [opt] + /// @param[out] resultParent The reference ids of the parent polygons for each result. + /// Zero if a result polygon has no parent. [opt] + /// @param[out] resultCost The search cost from @p centerPos to the polygon. [opt] + /// @param[out] resultCount The number of polygons found. [opt] + /// @param[in] maxResult The maximum number of polygons the result arrays can hold. + /// @returns The status flags for the query. + dtStatus findPolysAroundCircle(dtPolyRef startRef, const float* centerPos, const float radius, + const dtQueryFilter* filter, + dtPolyRef* resultRef, dtPolyRef* resultParent, float* resultCost, + int* resultCount, const int maxResult) const; + + /// Finds the polygons along the naviation graph that touch the specified convex polygon. + /// @param[in] startRef The reference id of the polygon where the search starts. + /// @param[in] verts The vertices describing the convex polygon. (CCW) + /// [(x, y, z) * @p nverts] + /// @param[in] nverts The number of vertices in the polygon. + /// @param[in] filter The polygon filter to apply to the query. + /// @param[out] resultRef The reference ids of the polygons touched by the search polygon. [opt] + /// @param[out] resultParent The reference ids of the parent polygons for each result. Zero if a + /// result polygon has no parent. [opt] + /// @param[out] resultCost The search cost from the centroid point to the polygon. [opt] + /// @param[out] resultCount The number of polygons found. + /// @param[in] maxResult The maximum number of polygons the result arrays can hold. + /// @returns The status flags for the query. + dtStatus findPolysAroundShape(dtPolyRef startRef, const float* verts, const int nverts, + const dtQueryFilter* filter, + dtPolyRef* resultRef, dtPolyRef* resultParent, float* resultCost, + int* resultCount, const int maxResult) const; + + /// Gets a path from the explored nodes in the previous search. + /// @param[in] endRef The reference id of the end polygon. + /// @param[out] path An ordered list of polygon references representing the path. (Start to end.) + /// [(polyRef) * @p pathCount] + /// @param[out] pathCount The number of polygons returned in the @p path array. + /// @param[in] maxPath The maximum number of polygons the @p path array can hold. [Limit: >= 0] + /// @returns The status flags. Returns DT_FAILURE | DT_INVALID_PARAM if any parameter is wrong, or if + /// @p endRef was not explored in the previous search. Returns DT_SUCCESS | DT_BUFFER_TOO_SMALL + /// if @p path cannot contain the entire path. In this case it is filled to capacity with a partial path. + /// Otherwise returns DT_SUCCESS. + /// @remarks The result of this function depends on the state of the query object. For that reason it should only + /// be used immediately after one of the two Dijkstra searches, findPolysAroundCircle or findPolysAroundShape. + dtStatus getPathFromDijkstraSearch(dtPolyRef endRef, dtPolyRef* path, int* pathCount, int maxPath) const; + + /// @} + /// @name Local Query Functions + ///@{ + + /// Finds the polygon nearest to the specified center point. + /// [opt] means the specified parameter can be a null pointer, in that case the output parameter will not be set. + /// + /// @param[in] center The center of the search box. [(x, y, z)] + /// @param[in] halfExtents The search distance along each axis. [(x, y, z)] + /// @param[in] filter The polygon filter to apply to the query. + /// @param[out] nearestRef The reference id of the nearest polygon. Will be set to 0 if no polygon is found. + /// @param[out] nearestPt The nearest point on the polygon. Unchanged if no polygon is found. [opt] [(x, y, z)] + /// @returns The status flags for the query. + dtStatus findNearestPoly(const float* center, const float* halfExtents, + const dtQueryFilter* filter, + dtPolyRef* nearestRef, float* nearestPt) const; + + /// Finds the polygon nearest to the specified center point. + /// [opt] means the specified parameter can be a null pointer, in that case the output parameter will not be set. + /// + /// @param[in] center The center of the search box. [(x, y, z)] + /// @param[in] halfExtents The search distance along each axis. [(x, y, z)] + /// @param[in] filter The polygon filter to apply to the query. + /// @param[out] nearestRef The reference id of the nearest polygon. Will be set to 0 if no polygon is found. + /// @param[out] nearestPt The nearest point on the polygon. Unchanged if no polygon is found. [opt] [(x, y, z)] + /// @param[out] isOverPoly Set to true if the point's X/Z coordinate lies inside the polygon, false otherwise. Unchanged if no polygon is found. [opt] + /// @returns The status flags for the query. + dtStatus findNearestPoly(const float* center, const float* halfExtents, + const dtQueryFilter* filter, + dtPolyRef* nearestRef, float* nearestPt, bool* isOverPoly) const; + + /// Finds polygons that overlap the search box. + /// @param[in] center The center of the search box. [(x, y, z)] + /// @param[in] halfExtents The search distance along each axis. [(x, y, z)] + /// @param[in] filter The polygon filter to apply to the query. + /// @param[out] polys The reference ids of the polygons that overlap the query box. + /// @param[out] polyCount The number of polygons in the search result. + /// @param[in] maxPolys The maximum number of polygons the search result can hold. + /// @returns The status flags for the query. + dtStatus queryPolygons(const float* center, const float* halfExtents, + const dtQueryFilter* filter, + dtPolyRef* polys, int* polyCount, const int maxPolys) const; + + /// Finds polygons that overlap the search box. + /// @param[in] center The center of the search box. [(x, y, z)] + /// @param[in] halfExtents The search distance along each axis. [(x, y, z)] + /// @param[in] filter The polygon filter to apply to the query. + /// @param[in] query The query. Polygons found will be batched together and passed to this query. + dtStatus queryPolygons(const float* center, const float* halfExtents, + const dtQueryFilter* filter, dtPolyQuery* query) const; + + /// Finds the non-overlapping navigation polygons in the local neighbourhood around the center position. + /// @param[in] startRef The reference id of the polygon where the search starts. + /// @param[in] centerPos The center of the query circle. [(x, y, z)] + /// @param[in] radius The radius of the query circle. + /// @param[in] filter The polygon filter to apply to the query. + /// @param[out] resultRef The reference ids of the polygons touched by the circle. + /// @param[out] resultParent The reference ids of the parent polygons for each result. + /// Zero if a result polygon has no parent. [opt] + /// @param[out] resultCount The number of polygons found. + /// @param[in] maxResult The maximum number of polygons the result arrays can hold. + /// @returns The status flags for the query. + dtStatus findLocalNeighbourhood(dtPolyRef startRef, const float* centerPos, const float radius, + const dtQueryFilter* filter, + dtPolyRef* resultRef, dtPolyRef* resultParent, + int* resultCount, const int maxResult) const; + + /// Moves from the start to the end position constrained to the navigation mesh. + /// @param[in] startRef The reference id of the start polygon. + /// @param[in] startPos A position of the mover within the start polygon. [(x, y, x)] + /// @param[in] endPos The desired end position of the mover. [(x, y, z)] + /// @param[in] filter The polygon filter to apply to the query. + /// @param[out] resultPos The result position of the mover. [(x, y, z)] + /// @param[out] visited The reference ids of the polygons visited during the move. + /// @param[out] visitedCount The number of polygons visited during the move. + /// @param[in] maxVisitedSize The maximum number of polygons the @p visited array can hold. + /// @returns The status flags for the query. + dtStatus moveAlongSurface(dtPolyRef startRef, const float* startPos, const float* endPos, + const dtQueryFilter* filter, + float* resultPos, dtPolyRef* visited, int* visitedCount, const int maxVisitedSize) const; + + /// Casts a 'walkability' ray along the surface of the navigation mesh from + /// the start position toward the end position. + /// @note A wrapper around raycast(..., RaycastHit*). Retained for backward compatibility. + /// @param[in] startRef The reference id of the start polygon. + /// @param[in] startPos A position within the start polygon representing + /// the start of the ray. [(x, y, z)] + /// @param[in] endPos The position to cast the ray toward. [(x, y, z)] + /// @param[in] filter The polygon filter to apply to the query. + /// @param[out] t The hit parameter. (FLT_MAX if no wall hit.) + /// @param[out] hitNormal The normal of the nearest wall hit. [(x, y, z)] + /// @param[out] path The reference ids of the visited polygons. [opt] + /// @param[out] pathCount The number of visited polygons. [opt] + /// @param[in] maxPath The maximum number of polygons the @p path array can hold. + /// @returns The status flags for the query. + dtStatus raycast(dtPolyRef startRef, const float* startPos, const float* endPos, + const dtQueryFilter* filter, + float* t, float* hitNormal, dtPolyRef* path, int* pathCount, const int maxPath) const; + + /// Casts a 'walkability' ray along the surface of the navigation mesh from + /// the start position toward the end position. + /// @param[in] startRef The reference id of the start polygon. + /// @param[in] startPos A position within the start polygon representing + /// the start of the ray. [(x, y, z)] + /// @param[in] endPos The position to cast the ray toward. [(x, y, z)] + /// @param[in] filter The polygon filter to apply to the query. + /// @param[in] options govern how the raycast behaves. See dtRaycastOptions + /// @param[out] hit Pointer to a raycast hit structure which will be filled by the results. + /// @param[in] prevRef parent of start ref. Used during for cost calculation [opt] + /// @returns The status flags for the query. + dtStatus raycast(dtPolyRef startRef, const float* startPos, const float* endPos, + const dtQueryFilter* filter, const unsigned int options, + dtRaycastHit* hit, dtPolyRef prevRef = 0) const; + + + /// Finds the distance from the specified position to the nearest polygon wall. + /// @param[in] startRef The reference id of the polygon containing @p centerPos. + /// @param[in] centerPos The center of the search circle. [(x, y, z)] + /// @param[in] maxRadius The radius of the search circle. + /// @param[in] filter The polygon filter to apply to the query. + /// @param[out] hitDist The distance to the nearest wall from @p centerPos. + /// @param[out] hitPos The nearest position on the wall that was hit. [(x, y, z)] + /// @param[out] hitNormal The normalized ray formed from the wall point to the + /// source point. [(x, y, z)] + /// @returns The status flags for the query. + dtStatus findDistanceToWall(dtPolyRef startRef, const float* centerPos, const float maxRadius, + const dtQueryFilter* filter, + float* hitDist, float* hitPos, float* hitNormal) const; + + /// Returns the segments for the specified polygon, optionally including portals. + /// @param[in] ref The reference id of the polygon. + /// @param[in] filter The polygon filter to apply to the query. + /// @param[out] segmentVerts The segments. [(ax, ay, az, bx, by, bz) * segmentCount] + /// @param[out] segmentRefs The reference ids of each segment's neighbor polygon. + /// Or zero if the segment is a wall. [opt] [(parentRef) * @p segmentCount] + /// @param[out] segmentCount The number of segments returned. + /// @param[in] maxSegments The maximum number of segments the result arrays can hold. + /// @returns The status flags for the query. + dtStatus getPolyWallSegments(dtPolyRef ref, const dtQueryFilter* filter, + float* segmentVerts, dtPolyRef* segmentRefs, int* segmentCount, + const int maxSegments) const; + + /// Returns random location on navmesh. + /// Polygons are chosen weighted by area. The search runs in linear related to number of polygon. + /// @param[in] filter The polygon filter to apply to the query. + /// @param[in] frand Function returning a random number [0..1). + /// @param[out] randomRef The reference id of the random location. + /// @param[out] randomPt The random location. + /// @returns The status flags for the query. + dtStatus findRandomPoint(const dtQueryFilter* filter, float (*frand)(), + dtPolyRef* randomRef, float* randomPt) const; + + /// Returns random location on navmesh within the reach of specified location. + /// Polygons are chosen weighted by area. The search runs in linear related to number of polygon. + /// The location is not exactly constrained by the circle, but it limits the visited polygons. + /// @param[in] startRef The reference id of the polygon where the search starts. + /// @param[in] centerPos The center of the search circle. [(x, y, z)] + /// @param[in] maxRadius The radius of the search circle. [Units: wu] + /// @param[in] filter The polygon filter to apply to the query. + /// @param[in] frand Function returning a random number [0..1). + /// @param[out] randomRef The reference id of the random location. + /// @param[out] randomPt The random location. [(x, y, z)] + /// @returns The status flags for the query. + dtStatus findRandomPointAroundCircle(dtPolyRef startRef, const float* centerPos, const float maxRadius, + const dtQueryFilter* filter, float (*frand)(), + dtPolyRef* randomRef, float* randomPt) const; + + /// Finds the closest point on the specified polygon. + /// @param[in] ref The reference id of the polygon. + /// @param[in] pos The position to check. [(x, y, z)] + /// @param[out] closest The closest point on the polygon. [(x, y, z)] + /// @param[out] posOverPoly True of the position is over the polygon. + /// @returns The status flags for the query. + dtStatus closestPointOnPoly(dtPolyRef ref, const float* pos, float* closest, bool* posOverPoly) const; + + /// Returns a point on the boundary closest to the source point if the source point is outside the + /// polygon's xz-bounds. + /// @param[in] ref The reference id to the polygon. + /// @param[in] pos The position to check. [(x, y, z)] + /// @param[out] closest The closest point. [(x, y, z)] + /// @returns The status flags for the query. + dtStatus closestPointOnPolyBoundary(dtPolyRef ref, const float* pos, float* closest) const; + + /// Gets the height of the polygon at the provided position using the height detail. (Most accurate.) + /// @param[in] ref The reference id of the polygon. + /// @param[in] pos A position within the xz-bounds of the polygon. [(x, y, z)] + /// @param[out] height The height at the surface of the polygon. + /// @returns The status flags for the query. + dtStatus getPolyHeight(dtPolyRef ref, const float* pos, float* height) const; + + /// @} + /// @name Miscellaneous Functions + /// @{ + + /// Returns true if the polygon reference is valid and passes the filter restrictions. + /// @param[in] ref The polygon reference to check. + /// @param[in] filter The filter to apply. + bool isValidPolyRef(dtPolyRef ref, const dtQueryFilter* filter) const; + + /// Returns true if the polygon reference is in the closed list. + /// @param[in] ref The reference id of the polygon to check. + /// @returns True if the polygon is in closed list. + bool isInClosedList(dtPolyRef ref) const; + + /// Gets the node pool. + /// @returns The node pool. + class dtNodePool* getNodePool() const { return m_nodePool; } + + /// Gets the navigation mesh the query object is using. + /// @return The navigation mesh the query object is using. + const dtNavMesh* getAttachedNavMesh() const { return m_nav; } + + /// @} + +private: + // Explicitly disabled copy constructor and copy assignment operator + dtNavMeshQuery(const dtNavMeshQuery&); + dtNavMeshQuery& operator=(const dtNavMeshQuery&); + + /// Queries polygons within a tile. + void queryPolygonsInTile(const dtMeshTile* tile, const float* qmin, const float* qmax, + const dtQueryFilter* filter, dtPolyQuery* query) const; + + /// Returns portal points between two polygons. + dtStatus getPortalPoints(dtPolyRef from, dtPolyRef to, float* left, float* right, + unsigned char& fromType, unsigned char& toType) const; + dtStatus getPortalPoints(dtPolyRef from, const dtPoly* fromPoly, const dtMeshTile* fromTile, + dtPolyRef to, const dtPoly* toPoly, const dtMeshTile* toTile, + float* left, float* right) const; + + /// Returns edge mid point between two polygons. + dtStatus getEdgeMidPoint(dtPolyRef from, dtPolyRef to, float* mid) const; + dtStatus getEdgeMidPoint(dtPolyRef from, const dtPoly* fromPoly, const dtMeshTile* fromTile, + dtPolyRef to, const dtPoly* toPoly, const dtMeshTile* toTile, + float* mid) const; + + // Appends vertex to a straight path + dtStatus appendVertex(const float* pos, const unsigned char flags, const dtPolyRef ref, + float* straightPath, unsigned char* straightPathFlags, dtPolyRef* straightPathRefs, + int* straightPathCount, const int maxStraightPath) const; + + // Appends intermediate portal points to a straight path. + dtStatus appendPortals(const int startIdx, const int endIdx, const float* endPos, const dtPolyRef* path, + float* straightPath, unsigned char* straightPathFlags, dtPolyRef* straightPathRefs, + int* straightPathCount, const int maxStraightPath, const int options) const; + + // Gets the path leading to the specified end node. + dtStatus getPathToNode(struct dtNode* endNode, dtPolyRef* path, int* pathCount, int maxPath) const; + + const dtNavMesh* m_nav; ///< Pointer to navmesh data. + + struct dtQueryData + { + dtStatus status; + struct dtNode* lastBestNode; + float lastBestNodeCost; + dtPolyRef startRef, endRef; + float startPos[3], endPos[3]; + const dtQueryFilter* filter; + unsigned int options; + float raycastLimitSqr; + }; + dtQueryData m_query; ///< Sliced query state. + + class dtNodePool* m_tinyNodePool; ///< Pointer to small node pool. + class dtNodePool* m_nodePool; ///< Pointer to node pool. + class dtNodeQueue* m_openList; ///< Pointer to open list queue. +}; + +/// Allocates a query object using the Detour allocator. +/// @return An allocated query object, or null on failure. +/// @ingroup detour +dtNavMeshQuery* dtAllocNavMeshQuery(); + +/// Frees the specified query object using the Detour allocator. +/// @param[in] query A query object allocated using #dtAllocNavMeshQuery +/// @ingroup detour +void dtFreeNavMeshQuery(dtNavMeshQuery* query); + +#endif // DETOURNAVMESHQUERY_H diff --git a/native/third_party/recastnavigation/Detour/Include/DetourNode.h b/native/third_party/recastnavigation/Detour/Include/DetourNode.h new file mode 100644 index 0000000..8918d46 --- /dev/null +++ b/native/third_party/recastnavigation/Detour/Include/DetourNode.h @@ -0,0 +1,168 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#ifndef DETOURNODE_H +#define DETOURNODE_H + +#include "DetourNavMesh.h" + +enum dtNodeFlags +{ + DT_NODE_OPEN = 0x01, + DT_NODE_CLOSED = 0x02, + DT_NODE_PARENT_DETACHED = 0x04 // parent of the node is not adjacent. Found using raycast. +}; + +typedef unsigned short dtNodeIndex; +static const dtNodeIndex DT_NULL_IDX = (dtNodeIndex)~0; + +static const int DT_NODE_PARENT_BITS = 24; +static const int DT_NODE_STATE_BITS = 2; +struct dtNode +{ + float pos[3]; ///< Position of the node. + float cost; ///< Cost from previous node to current node. + float total; ///< Cost up to the node. + unsigned int pidx : DT_NODE_PARENT_BITS; ///< Index to parent node. + unsigned int state : DT_NODE_STATE_BITS; ///< extra state information. A polyRef can have multiple nodes with different extra info. see DT_MAX_STATES_PER_NODE + unsigned int flags : 3; ///< Node flags. A combination of dtNodeFlags. + dtPolyRef id; ///< Polygon ref the node corresponds to. +}; + +static const int DT_MAX_STATES_PER_NODE = 1 << DT_NODE_STATE_BITS; // number of extra states per node. See dtNode::state + +class dtNodePool +{ +public: + dtNodePool(int maxNodes, int hashSize); + ~dtNodePool(); + void clear(); + + // Get a dtNode by ref and extra state information. If there is none then - allocate + // There can be more than one node for the same polyRef but with different extra state information + dtNode* getNode(dtPolyRef id, unsigned char state=0); + dtNode* findNode(dtPolyRef id, unsigned char state); + unsigned int findNodes(dtPolyRef id, dtNode** nodes, const int maxNodes); + + inline unsigned int getNodeIdx(const dtNode* node) const + { + if (!node) return 0; + return (unsigned int)(node - m_nodes) + 1; + } + + inline dtNode* getNodeAtIdx(unsigned int idx) + { + if (!idx) return 0; + return &m_nodes[idx - 1]; + } + + inline const dtNode* getNodeAtIdx(unsigned int idx) const + { + if (!idx) return 0; + return &m_nodes[idx - 1]; + } + + inline int getMemUsed() const + { + return sizeof(*this) + + sizeof(dtNode)*m_maxNodes + + sizeof(dtNodeIndex)*m_maxNodes + + sizeof(dtNodeIndex)*m_hashSize; + } + + inline int getMaxNodes() const { return m_maxNodes; } + + inline int getHashSize() const { return m_hashSize; } + inline dtNodeIndex getFirst(int bucket) const { return m_first[bucket]; } + inline dtNodeIndex getNext(int i) const { return m_next[i]; } + inline int getNodeCount() const { return m_nodeCount; } + +private: + // Explicitly disabled copy constructor and copy assignment operator. + dtNodePool(const dtNodePool&); + dtNodePool& operator=(const dtNodePool&); + + dtNode* m_nodes; + dtNodeIndex* m_first; + dtNodeIndex* m_next; + const int m_maxNodes; + const int m_hashSize; + int m_nodeCount; +}; + +class dtNodeQueue +{ +public: + dtNodeQueue(int n); + ~dtNodeQueue(); + + inline void clear() { m_size = 0; } + + inline dtNode* top() { return m_heap[0]; } + + inline dtNode* pop() + { + dtNode* result = m_heap[0]; + m_size--; + trickleDown(0, m_heap[m_size]); + return result; + } + + inline void push(dtNode* node) + { + m_size++; + bubbleUp(m_size-1, node); + } + + inline void modify(dtNode* node) + { + for (int i = 0; i < m_size; ++i) + { + if (m_heap[i] == node) + { + bubbleUp(i, node); + return; + } + } + } + + inline bool empty() const { return m_size == 0; } + + inline int getMemUsed() const + { + return sizeof(*this) + + sizeof(dtNode*) * (m_capacity + 1); + } + + inline int getCapacity() const { return m_capacity; } + +private: + // Explicitly disabled copy constructor and copy assignment operator. + dtNodeQueue(const dtNodeQueue&); + dtNodeQueue& operator=(const dtNodeQueue&); + + void bubbleUp(int i, dtNode* node); + void trickleDown(int i, dtNode* node); + + dtNode** m_heap; + const int m_capacity; + int m_size; +}; + + +#endif // DETOURNODE_H diff --git a/native/third_party/recastnavigation/Detour/Include/DetourStatus.h b/native/third_party/recastnavigation/Detour/Include/DetourStatus.h new file mode 100644 index 0000000..8e1bb44 --- /dev/null +++ b/native/third_party/recastnavigation/Detour/Include/DetourStatus.h @@ -0,0 +1,65 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#ifndef DETOURSTATUS_H +#define DETOURSTATUS_H + +typedef unsigned int dtStatus; + +// High level status. +static const unsigned int DT_FAILURE = 1u << 31; // Operation failed. +static const unsigned int DT_SUCCESS = 1u << 30; // Operation succeed. +static const unsigned int DT_IN_PROGRESS = 1u << 29; // Operation still in progress. + +// Detail information for status. +static const unsigned int DT_STATUS_DETAIL_MASK = 0x0ffffff; +static const unsigned int DT_WRONG_MAGIC = 1 << 0; // Input data is not recognized. +static const unsigned int DT_WRONG_VERSION = 1 << 1; // Input data is in wrong version. +static const unsigned int DT_OUT_OF_MEMORY = 1 << 2; // Operation ran out of memory. +static const unsigned int DT_INVALID_PARAM = 1 << 3; // An input parameter was invalid. +static const unsigned int DT_BUFFER_TOO_SMALL = 1 << 4; // Result buffer for the query was too small to store all results. +static const unsigned int DT_OUT_OF_NODES = 1 << 5; // Query ran out of nodes during search. +static const unsigned int DT_PARTIAL_RESULT = 1 << 6; // Query did not reach the end location, returning best guess. +static const unsigned int DT_ALREADY_OCCUPIED = 1 << 7; // A tile has already been assigned to the given x,y coordinate + + +// Returns true of status is success. +inline bool dtStatusSucceed(dtStatus status) +{ + return (status & DT_SUCCESS) != 0; +} + +// Returns true of status is failure. +inline bool dtStatusFailed(dtStatus status) +{ + return (status & DT_FAILURE) != 0; +} + +// Returns true of status is in progress. +inline bool dtStatusInProgress(dtStatus status) +{ + return (status & DT_IN_PROGRESS) != 0; +} + +// Returns true if specific detail is set. +inline bool dtStatusDetail(dtStatus status, unsigned int detail) +{ + return (status & detail) != 0; +} + +#endif // DETOURSTATUS_H diff --git a/native/third_party/recastnavigation/Detour/Source/DetourAlloc.cpp b/native/third_party/recastnavigation/Detour/Source/DetourAlloc.cpp new file mode 100644 index 0000000..d9ad1fc --- /dev/null +++ b/native/third_party/recastnavigation/Detour/Source/DetourAlloc.cpp @@ -0,0 +1,50 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#include +#include "DetourAlloc.h" + +static void *dtAllocDefault(size_t size, dtAllocHint) +{ + return malloc(size); +} + +static void dtFreeDefault(void *ptr) +{ + free(ptr); +} + +static dtAllocFunc* sAllocFunc = dtAllocDefault; +static dtFreeFunc* sFreeFunc = dtFreeDefault; + +void dtAllocSetCustom(dtAllocFunc *allocFunc, dtFreeFunc *freeFunc) +{ + sAllocFunc = allocFunc ? allocFunc : dtAllocDefault; + sFreeFunc = freeFunc ? freeFunc : dtFreeDefault; +} + +void* dtAlloc(size_t size, dtAllocHint hint) +{ + return sAllocFunc(size, hint); +} + +void dtFree(void* ptr) +{ + if (ptr) + sFreeFunc(ptr); +} diff --git a/native/third_party/recastnavigation/Detour/Source/DetourAssert.cpp b/native/third_party/recastnavigation/Detour/Source/DetourAssert.cpp new file mode 100644 index 0000000..a9727a3 --- /dev/null +++ b/native/third_party/recastnavigation/Detour/Source/DetourAssert.cpp @@ -0,0 +1,35 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#include "DetourAssert.h" + +#ifndef RC_DISABLE_ASSERTS + +static dtAssertFailFunc* sAssertFailFunc = 0; + +void dtAssertFailSetCustom(dtAssertFailFunc *assertFailFunc) +{ + sAssertFailFunc = assertFailFunc; +} + +dtAssertFailFunc* dtAssertFailGetCustom() +{ + return sAssertFailFunc; +} + +#endif diff --git a/native/third_party/recastnavigation/Detour/Source/DetourCommon.cpp b/native/third_party/recastnavigation/Detour/Source/DetourCommon.cpp new file mode 100644 index 0000000..b845782 --- /dev/null +++ b/native/third_party/recastnavigation/Detour/Source/DetourCommon.cpp @@ -0,0 +1,387 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#include "DetourCommon.h" +#include "DetourMath.h" + +////////////////////////////////////////////////////////////////////////////////////////// + +void dtClosestPtPointTriangle(float* closest, const float* p, + const float* a, const float* b, const float* c) +{ + // Check if P in vertex region outside A + float ab[3], ac[3], ap[3]; + dtVsub(ab, b, a); + dtVsub(ac, c, a); + dtVsub(ap, p, a); + float d1 = dtVdot(ab, ap); + float d2 = dtVdot(ac, ap); + if (d1 <= 0.0f && d2 <= 0.0f) + { + // barycentric coordinates (1,0,0) + dtVcopy(closest, a); + return; + } + + // Check if P in vertex region outside B + float bp[3]; + dtVsub(bp, p, b); + float d3 = dtVdot(ab, bp); + float d4 = dtVdot(ac, bp); + if (d3 >= 0.0f && d4 <= d3) + { + // barycentric coordinates (0,1,0) + dtVcopy(closest, b); + return; + } + + // Check if P in edge region of AB, if so return projection of P onto AB + float vc = d1*d4 - d3*d2; + if (vc <= 0.0f && d1 >= 0.0f && d3 <= 0.0f) + { + // barycentric coordinates (1-v,v,0) + float v = d1 / (d1 - d3); + closest[0] = a[0] + v * ab[0]; + closest[1] = a[1] + v * ab[1]; + closest[2] = a[2] + v * ab[2]; + return; + } + + // Check if P in vertex region outside C + float cp[3]; + dtVsub(cp, p, c); + float d5 = dtVdot(ab, cp); + float d6 = dtVdot(ac, cp); + if (d6 >= 0.0f && d5 <= d6) + { + // barycentric coordinates (0,0,1) + dtVcopy(closest, c); + return; + } + + // Check if P in edge region of AC, if so return projection of P onto AC + float vb = d5*d2 - d1*d6; + if (vb <= 0.0f && d2 >= 0.0f && d6 <= 0.0f) + { + // barycentric coordinates (1-w,0,w) + float w = d2 / (d2 - d6); + closest[0] = a[0] + w * ac[0]; + closest[1] = a[1] + w * ac[1]; + closest[2] = a[2] + w * ac[2]; + return; + } + + // Check if P in edge region of BC, if so return projection of P onto BC + float va = d3*d6 - d5*d4; + if (va <= 0.0f && (d4 - d3) >= 0.0f && (d5 - d6) >= 0.0f) + { + // barycentric coordinates (0,1-w,w) + float w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); + closest[0] = b[0] + w * (c[0] - b[0]); + closest[1] = b[1] + w * (c[1] - b[1]); + closest[2] = b[2] + w * (c[2] - b[2]); + return; + } + + // P inside face region. Compute Q through its barycentric coordinates (u,v,w) + float denom = 1.0f / (va + vb + vc); + float v = vb * denom; + float w = vc * denom; + closest[0] = a[0] + ab[0] * v + ac[0] * w; + closest[1] = a[1] + ab[1] * v + ac[1] * w; + closest[2] = a[2] + ab[2] * v + ac[2] * w; +} + +bool dtIntersectSegmentPoly2D(const float* p0, const float* p1, + const float* verts, int nverts, + float& tmin, float& tmax, + int& segMin, int& segMax) +{ + static const float EPS = 0.000001f; + + tmin = 0; + tmax = 1; + segMin = -1; + segMax = -1; + + float dir[3]; + dtVsub(dir, p1, p0); + + for (int i = 0, j = nverts-1; i < nverts; j=i++) + { + float edge[3], diff[3]; + dtVsub(edge, &verts[i*3], &verts[j*3]); + dtVsub(diff, p0, &verts[j*3]); + const float n = dtVperp2D(edge, diff); + const float d = dtVperp2D(dir, edge); + if (fabsf(d) < EPS) + { + // S is nearly parallel to this edge + if (n < 0) + return false; + else + continue; + } + const float t = n / d; + if (d < 0) + { + // segment S is entering across this edge + if (t > tmin) + { + tmin = t; + segMin = j; + // S enters after leaving polygon + if (tmin > tmax) + return false; + } + } + else + { + // segment S is leaving across this edge + if (t < tmax) + { + tmax = t; + segMax = j; + // S leaves before entering polygon + if (tmax < tmin) + return false; + } + } + } + + return true; +} + +float dtDistancePtSegSqr2D(const float* pt, const float* p, const float* q, float& t) +{ + float pqx = q[0] - p[0]; + float pqz = q[2] - p[2]; + float dx = pt[0] - p[0]; + float dz = pt[2] - p[2]; + float d = pqx*pqx + pqz*pqz; + t = pqx*dx + pqz*dz; + if (d > 0) t /= d; + if (t < 0) t = 0; + else if (t > 1) t = 1; + dx = p[0] + t*pqx - pt[0]; + dz = p[2] + t*pqz - pt[2]; + return dx*dx + dz*dz; +} + +void dtCalcPolyCenter(float* tc, const unsigned short* idx, int nidx, const float* verts) +{ + tc[0] = 0.0f; + tc[1] = 0.0f; + tc[2] = 0.0f; + for (int j = 0; j < nidx; ++j) + { + const float* v = &verts[idx[j]*3]; + tc[0] += v[0]; + tc[1] += v[1]; + tc[2] += v[2]; + } + const float s = 1.0f / nidx; + tc[0] *= s; + tc[1] *= s; + tc[2] *= s; +} + +bool dtClosestHeightPointTriangle(const float* p, const float* a, const float* b, const float* c, float& h) +{ + const float EPS = 1e-6f; + float v0[3], v1[3], v2[3]; + + dtVsub(v0, c, a); + dtVsub(v1, b, a); + dtVsub(v2, p, a); + + // Compute scaled barycentric coordinates + float denom = v0[0] * v1[2] - v0[2] * v1[0]; + if (fabsf(denom) < EPS) + return false; + + float u = v1[2] * v2[0] - v1[0] * v2[2]; + float v = v0[0] * v2[2] - v0[2] * v2[0]; + + if (denom < 0) { + denom = -denom; + u = -u; + v = -v; + } + + // If point lies inside the triangle, return interpolated ycoord. + if (u >= 0.0f && v >= 0.0f && (u + v) <= denom) { + h = a[1] + (v0[1] * u + v1[1] * v) / denom; + return true; + } + return false; +} + +/// @par +/// +/// All points are projected onto the xz-plane, so the y-values are ignored. +bool dtPointInPolygon(const float* pt, const float* verts, const int nverts) +{ + // TODO: Replace pnpoly with triArea2D tests? + int i, j; + bool c = false; + for (i = 0, j = nverts-1; i < nverts; j = i++) + { + const float* vi = &verts[i*3]; + const float* vj = &verts[j*3]; + if (((vi[2] > pt[2]) != (vj[2] > pt[2])) && + (pt[0] < (vj[0]-vi[0]) * (pt[2]-vi[2]) / (vj[2]-vi[2]) + vi[0]) ) + c = !c; + } + return c; +} + +bool dtDistancePtPolyEdgesSqr(const float* pt, const float* verts, const int nverts, + float* ed, float* et) +{ + // TODO: Replace pnpoly with triArea2D tests? + int i, j; + bool c = false; + for (i = 0, j = nverts-1; i < nverts; j = i++) + { + const float* vi = &verts[i*3]; + const float* vj = &verts[j*3]; + if (((vi[2] > pt[2]) != (vj[2] > pt[2])) && + (pt[0] < (vj[0]-vi[0]) * (pt[2]-vi[2]) / (vj[2]-vi[2]) + vi[0]) ) + c = !c; + ed[j] = dtDistancePtSegSqr2D(pt, vj, vi, et[j]); + } + return c; +} + +static void projectPoly(const float* axis, const float* poly, const int npoly, + float& rmin, float& rmax) +{ + rmin = rmax = dtVdot2D(axis, &poly[0]); + for (int i = 1; i < npoly; ++i) + { + const float d = dtVdot2D(axis, &poly[i*3]); + rmin = dtMin(rmin, d); + rmax = dtMax(rmax, d); + } +} + +inline bool overlapRange(const float amin, const float amax, + const float bmin, const float bmax, + const float eps) +{ + return ((amin+eps) > bmax || (amax-eps) < bmin) ? false : true; +} + +/// @par +/// +/// All vertices are projected onto the xz-plane, so the y-values are ignored. +bool dtOverlapPolyPoly2D(const float* polya, const int npolya, + const float* polyb, const int npolyb) +{ + const float eps = 1e-4f; + + for (int i = 0, j = npolya-1; i < npolya; j=i++) + { + const float* va = &polya[j*3]; + const float* vb = &polya[i*3]; + const float n[3] = { vb[2]-va[2], 0, -(vb[0]-va[0]) }; + float amin,amax,bmin,bmax; + projectPoly(n, polya, npolya, amin,amax); + projectPoly(n, polyb, npolyb, bmin,bmax); + if (!overlapRange(amin,amax, bmin,bmax, eps)) + { + // Found separating axis + return false; + } + } + for (int i = 0, j = npolyb-1; i < npolyb; j=i++) + { + const float* va = &polyb[j*3]; + const float* vb = &polyb[i*3]; + const float n[3] = { vb[2]-va[2], 0, -(vb[0]-va[0]) }; + float amin,amax,bmin,bmax; + projectPoly(n, polya, npolya, amin,amax); + projectPoly(n, polyb, npolyb, bmin,bmax); + if (!overlapRange(amin,amax, bmin,bmax, eps)) + { + // Found separating axis + return false; + } + } + return true; +} + +// Returns a random point in a convex polygon. +// Adapted from Graphics Gems article. +void dtRandomPointInConvexPoly(const float* pts, const int npts, float* areas, + const float s, const float t, float* out) +{ + // Calc triangle araes + float areasum = 0.0f; + for (int i = 2; i < npts; i++) { + areas[i] = dtTriArea2D(&pts[0], &pts[(i-1)*3], &pts[i*3]); + areasum += dtMax(0.001f, areas[i]); + } + // Find sub triangle weighted by area. + const float thr = s*areasum; + float acc = 0.0f; + float u = 1.0f; + int tri = npts - 1; + for (int i = 2; i < npts; i++) { + const float dacc = areas[i]; + if (thr >= acc && thr < (acc+dacc)) + { + u = (thr - acc) / dacc; + tri = i; + break; + } + acc += dacc; + } + + float v = dtMathSqrtf(t); + + const float a = 1 - v; + const float b = (1 - u) * v; + const float c = u * v; + const float* pa = &pts[0]; + const float* pb = &pts[(tri-1)*3]; + const float* pc = &pts[tri*3]; + + out[0] = a*pa[0] + b*pb[0] + c*pc[0]; + out[1] = a*pa[1] + b*pb[1] + c*pc[1]; + out[2] = a*pa[2] + b*pb[2] + c*pc[2]; +} + +inline float vperpXZ(const float* a, const float* b) { return a[0]*b[2] - a[2]*b[0]; } + +bool dtIntersectSegSeg2D(const float* ap, const float* aq, + const float* bp, const float* bq, + float& s, float& t) +{ + float u[3], v[3], w[3]; + dtVsub(u,aq,ap); + dtVsub(v,bq,bp); + dtVsub(w,ap,bp); + float d = vperpXZ(u,v); + if (fabsf(d) < 1e-6f) return false; + s = vperpXZ(v,w) / d; + t = vperpXZ(u,w) / d; + return true; +} + diff --git a/native/third_party/recastnavigation/Detour/Source/DetourNavMesh.cpp b/native/third_party/recastnavigation/Detour/Source/DetourNavMesh.cpp new file mode 100644 index 0000000..ee868f2 --- /dev/null +++ b/native/third_party/recastnavigation/Detour/Source/DetourNavMesh.cpp @@ -0,0 +1,1597 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#include +#include +#include +#include "DetourNavMesh.h" +#include "DetourNode.h" +#include "DetourCommon.h" +#include "DetourMath.h" +#include "DetourAlloc.h" +#include "DetourAssert.h" +#include + + +inline bool overlapSlabs(const float* amin, const float* amax, + const float* bmin, const float* bmax, + const float px, const float py) +{ + // Check for horizontal overlap. + // The segment is shrunken a little so that slabs which touch + // at end points are not connected. + const float minx = dtMax(amin[0]+px,bmin[0]+px); + const float maxx = dtMin(amax[0]-px,bmax[0]-px); + if (minx > maxx) + return false; + + // Check vertical overlap. + const float ad = (amax[1]-amin[1]) / (amax[0]-amin[0]); + const float ak = amin[1] - ad*amin[0]; + const float bd = (bmax[1]-bmin[1]) / (bmax[0]-bmin[0]); + const float bk = bmin[1] - bd*bmin[0]; + const float aminy = ad*minx + ak; + const float amaxy = ad*maxx + ak; + const float bminy = bd*minx + bk; + const float bmaxy = bd*maxx + bk; + const float dmin = bminy - aminy; + const float dmax = bmaxy - amaxy; + + // Crossing segments always overlap. + if (dmin*dmax < 0) + return true; + + // Check for overlap at endpoints. + const float thr = dtSqr(py*2); + if (dmin*dmin <= thr || dmax*dmax <= thr) + return true; + + return false; +} + +static float getSlabCoord(const float* va, const int side) +{ + if (side == 0 || side == 4) + return va[0]; + else if (side == 2 || side == 6) + return va[2]; + return 0; +} + +static void calcSlabEndPoints(const float* va, const float* vb, float* bmin, float* bmax, const int side) +{ + if (side == 0 || side == 4) + { + if (va[2] < vb[2]) + { + bmin[0] = va[2]; + bmin[1] = va[1]; + bmax[0] = vb[2]; + bmax[1] = vb[1]; + } + else + { + bmin[0] = vb[2]; + bmin[1] = vb[1]; + bmax[0] = va[2]; + bmax[1] = va[1]; + } + } + else if (side == 2 || side == 6) + { + if (va[0] < vb[0]) + { + bmin[0] = va[0]; + bmin[1] = va[1]; + bmax[0] = vb[0]; + bmax[1] = vb[1]; + } + else + { + bmin[0] = vb[0]; + bmin[1] = vb[1]; + bmax[0] = va[0]; + bmax[1] = va[1]; + } + } +} + +inline int computeTileHash(int x, int y, const int mask) +{ + const unsigned int h1 = 0x8da6b343; // Large multiplicative constants; + const unsigned int h2 = 0xd8163841; // here arbitrarily chosen primes + unsigned int n = h1 * x + h2 * y; + return (int)(n & mask); +} + +inline unsigned int allocLink(dtMeshTile* tile) +{ + if (tile->linksFreeList == DT_NULL_LINK) + return DT_NULL_LINK; + unsigned int link = tile->linksFreeList; + tile->linksFreeList = tile->links[link].next; + return link; +} + +inline void freeLink(dtMeshTile* tile, unsigned int link) +{ + tile->links[link].next = tile->linksFreeList; + tile->linksFreeList = link; +} + + +dtNavMesh* dtAllocNavMesh() +{ + void* mem = dtAlloc(sizeof(dtNavMesh), DT_ALLOC_PERM); + if (!mem) return 0; + return new(mem) dtNavMesh; +} + +/// @par +/// +/// This function will only free the memory for tiles with the #DT_TILE_FREE_DATA +/// flag set. +void dtFreeNavMesh(dtNavMesh* navmesh) +{ + if (!navmesh) return; + navmesh->~dtNavMesh(); + dtFree(navmesh); +} + +////////////////////////////////////////////////////////////////////////////////////////// + +/** +@class dtNavMesh + +The navigation mesh consists of one or more tiles defining three primary types of structural data: + +A polygon mesh which defines most of the navigation graph. (See rcPolyMesh for its structure.) +A detail mesh used for determining surface height on the polygon mesh. (See rcPolyMeshDetail for its structure.) +Off-mesh connections, which define custom point-to-point edges within the navigation graph. + +The general build process is as follows: + +-# Create rcPolyMesh and rcPolyMeshDetail data using the Recast build pipeline. +-# Optionally, create off-mesh connection data. +-# Combine the source data into a dtNavMeshCreateParams structure. +-# Create a tile data array using dtCreateNavMeshData(). +-# Allocate at dtNavMesh object and initialize it. (For single tile navigation meshes, + the tile data is loaded during this step.) +-# For multi-tile navigation meshes, load the tile data using dtNavMesh::addTile(). + +Notes: + +- This class is usually used in conjunction with the dtNavMeshQuery class for pathfinding. +- Technically, all navigation meshes are tiled. A 'solo' mesh is simply a navigation mesh initialized + to have only a single tile. +- This class does not implement any asynchronous methods. So the ::dtStatus result of all methods will + always contain either a success or failure flag. + +@see dtNavMeshQuery, dtCreateNavMeshData, dtNavMeshCreateParams, #dtAllocNavMesh, #dtFreeNavMesh +*/ + +dtNavMesh::dtNavMesh() : + m_tileWidth(0), + m_tileHeight(0), + m_maxTiles(0), + m_tileLutSize(0), + m_tileLutMask(0), + m_posLookup(0), + m_nextFree(0), + m_tiles(0) +{ +#ifndef DT_POLYREF64 + m_saltBits = 0; + m_tileBits = 0; + m_polyBits = 0; +#endif + memset(&m_params, 0, sizeof(dtNavMeshParams)); + m_orig[0] = 0; + m_orig[1] = 0; + m_orig[2] = 0; +} + +dtNavMesh::~dtNavMesh() +{ + for (int i = 0; i < m_maxTiles; ++i) + { + if (m_tiles[i].flags & DT_TILE_FREE_DATA) + { + dtFree(m_tiles[i].data); + m_tiles[i].data = 0; + m_tiles[i].dataSize = 0; + } + } + dtFree(m_posLookup); + dtFree(m_tiles); +} + +dtStatus dtNavMesh::init(const dtNavMeshParams* params) +{ + memcpy(&m_params, params, sizeof(dtNavMeshParams)); + dtVcopy(m_orig, params->orig); + m_tileWidth = params->tileWidth; + m_tileHeight = params->tileHeight; + + // Init tiles + m_maxTiles = params->maxTiles; + m_tileLutSize = dtNextPow2(params->maxTiles/4); + if (!m_tileLutSize) m_tileLutSize = 1; + m_tileLutMask = m_tileLutSize-1; + + m_tiles = (dtMeshTile*)dtAlloc(sizeof(dtMeshTile)*m_maxTiles, DT_ALLOC_PERM); + if (!m_tiles) + return DT_FAILURE | DT_OUT_OF_MEMORY; + m_posLookup = (dtMeshTile**)dtAlloc(sizeof(dtMeshTile*)*m_tileLutSize, DT_ALLOC_PERM); + if (!m_posLookup) + return DT_FAILURE | DT_OUT_OF_MEMORY; + memset(m_tiles, 0, sizeof(dtMeshTile)*m_maxTiles); + memset(m_posLookup, 0, sizeof(dtMeshTile*)*m_tileLutSize); + m_nextFree = 0; + for (int i = m_maxTiles-1; i >= 0; --i) + { + m_tiles[i].salt = 1; + m_tiles[i].next = m_nextFree; + m_nextFree = &m_tiles[i]; + } + + // Init ID generator values. +#ifndef DT_POLYREF64 + m_tileBits = dtIlog2(dtNextPow2((unsigned int)params->maxTiles)); + m_polyBits = dtIlog2(dtNextPow2((unsigned int)params->maxPolys)); + + // Ensure that the bits of poly ref do not overflow. + dtAssert(m_tileBits + m_polyBits <= 31); + + // Only allow 31 salt bits, since the salt mask is calculated using 32bit uint and it will overflow. + m_saltBits = dtMin((unsigned int)31, 32 - m_tileBits - m_polyBits); + + if (m_saltBits < 10) + return DT_FAILURE | DT_INVALID_PARAM; +#endif + + return DT_SUCCESS; +} + +dtStatus dtNavMesh::init(unsigned char* data, const int dataSize, const int flags) +{ + // Make sure the data is in right format. + dtMeshHeader* header = (dtMeshHeader*)data; + if (header->magic != DT_NAVMESH_MAGIC) + return DT_FAILURE | DT_WRONG_MAGIC; + if (header->version != DT_NAVMESH_VERSION) + return DT_FAILURE | DT_WRONG_VERSION; + + dtNavMeshParams params; + dtVcopy(params.orig, header->bmin); + params.tileWidth = header->bmax[0] - header->bmin[0]; + params.tileHeight = header->bmax[2] - header->bmin[2]; + params.maxTiles = 1; + params.maxPolys = header->polyCount; + + dtStatus status = init(¶ms); + if (dtStatusFailed(status)) + return status; + + return addTile(data, dataSize, flags, 0, 0); +} + +/// @par +/// +/// @note The parameters are created automatically when the single tile +/// initialization is performed. +const dtNavMeshParams* dtNavMesh::getParams() const +{ + return &m_params; +} + +////////////////////////////////////////////////////////////////////////////////////////// +int dtNavMesh::findConnectingPolys(const float* va, const float* vb, + const dtMeshTile* tile, int side, + dtPolyRef* con, float* conarea, int maxcon) const +{ + if (!tile) return 0; + + float amin[2], amax[2]; + calcSlabEndPoints(va, vb, amin, amax, side); + const float apos = getSlabCoord(va, side); + + // Remove links pointing to 'side' and compact the links array. + float bmin[2], bmax[2]; + unsigned short m = DT_EXT_LINK | (unsigned short)side; + int n = 0; + + dtPolyRef base = getPolyRefBase(tile); + + for (int i = 0; i < tile->header->polyCount; ++i) + { + dtPoly* poly = &tile->polys[i]; + const int nv = poly->vertCount; + for (int j = 0; j < nv; ++j) + { + // Skip edges which do not point to the right side. + if (poly->neis[j] != m) continue; + + const float* vc = &tile->verts[poly->verts[j]*3]; + const float* vd = &tile->verts[poly->verts[(j+1) % nv]*3]; + const float bpos = getSlabCoord(vc, side); + + // Segments are not close enough. + if (dtAbs(apos-bpos) > 0.01f) + continue; + + // Check if the segments touch. + calcSlabEndPoints(vc, vd, bmin, bmax, side); + + if (!overlapSlabs(amin,amax, bmin,bmax, 0.01f, tile->header->walkableClimb)) continue; + + // Add return value. + if (n < maxcon) + { + conarea[n*2+0] = dtMax(amin[0], bmin[0]); + conarea[n*2+1] = dtMin(amax[0], bmax[0]); + con[n] = base | (dtPolyRef)i; + n++; + } + break; + } + } + return n; +} + +void dtNavMesh::unconnectLinks(dtMeshTile* tile, dtMeshTile* target) +{ + if (!tile || !target) return; + + const unsigned int targetNum = decodePolyIdTile(getTileRef(target)); + + for (int i = 0; i < tile->header->polyCount; ++i) + { + dtPoly* poly = &tile->polys[i]; + unsigned int j = poly->firstLink; + unsigned int pj = DT_NULL_LINK; + while (j != DT_NULL_LINK) + { + if (decodePolyIdTile(tile->links[j].ref) == targetNum) + { + // Remove link. + unsigned int nj = tile->links[j].next; + if (pj == DT_NULL_LINK) + poly->firstLink = nj; + else + tile->links[pj].next = nj; + freeLink(tile, j); + j = nj; + } + else + { + // Advance + pj = j; + j = tile->links[j].next; + } + } + } +} + +void dtNavMesh::connectExtLinks(dtMeshTile* tile, dtMeshTile* target, int side) +{ + if (!tile) return; + + // Connect border links. + for (int i = 0; i < tile->header->polyCount; ++i) + { + dtPoly* poly = &tile->polys[i]; + + // Create new links. +// unsigned short m = DT_EXT_LINK | (unsigned short)side; + + const int nv = poly->vertCount; + for (int j = 0; j < nv; ++j) + { + // Skip non-portal edges. + if ((poly->neis[j] & DT_EXT_LINK) == 0) + continue; + + const int dir = (int)(poly->neis[j] & 0xff); + if (side != -1 && dir != side) + continue; + + // Create new links + const float* va = &tile->verts[poly->verts[j]*3]; + const float* vb = &tile->verts[poly->verts[(j+1) % nv]*3]; + dtPolyRef nei[4]; + float neia[4*2]; + int nnei = findConnectingPolys(va,vb, target, dtOppositeTile(dir), nei,neia,4); + for (int k = 0; k < nnei; ++k) + { + unsigned int idx = allocLink(tile); + if (idx != DT_NULL_LINK) + { + dtLink* link = &tile->links[idx]; + link->ref = nei[k]; + link->edge = (unsigned char)j; + link->side = (unsigned char)dir; + + link->next = poly->firstLink; + poly->firstLink = idx; + + // Compress portal limits to a byte value. + if (dir == 0 || dir == 4) + { + float tmin = (neia[k*2+0]-va[2]) / (vb[2]-va[2]); + float tmax = (neia[k*2+1]-va[2]) / (vb[2]-va[2]); + if (tmin > tmax) + dtSwap(tmin,tmax); + link->bmin = (unsigned char)roundf(dtClamp(tmin, 0.0f, 1.0f)*255.0f); + link->bmax = (unsigned char)roundf(dtClamp(tmax, 0.0f, 1.0f)*255.0f); + } + else if (dir == 2 || dir == 6) + { + float tmin = (neia[k*2+0]-va[0]) / (vb[0]-va[0]); + float tmax = (neia[k*2+1]-va[0]) / (vb[0]-va[0]); + if (tmin > tmax) + dtSwap(tmin,tmax); + link->bmin = (unsigned char)roundf(dtClamp(tmin, 0.0f, 1.0f)*255.0f); + link->bmax = (unsigned char)roundf(dtClamp(tmax, 0.0f, 1.0f)*255.0f); + } + } + } + } + } +} + +void dtNavMesh::connectExtOffMeshLinks(dtMeshTile* tile, dtMeshTile* target, int side) +{ + if (!tile) return; + + // Connect off-mesh links. + // We are interested on links which land from target tile to this tile. + const unsigned char oppositeSide = (side == -1) ? 0xff : (unsigned char)dtOppositeTile(side); + + for (int i = 0; i < target->header->offMeshConCount; ++i) + { + dtOffMeshConnection* targetCon = &target->offMeshCons[i]; + if (targetCon->side != oppositeSide) + continue; + + dtPoly* targetPoly = &target->polys[targetCon->poly]; + // Skip off-mesh connections which start location could not be connected at all. + if (targetPoly->firstLink == DT_NULL_LINK) + continue; + + const float halfExtents[3] = { targetCon->rad, target->header->walkableClimb, targetCon->rad }; + + // Find polygon to connect to. + const float* p = &targetCon->pos[3]; + float nearestPt[3]; + dtPolyRef ref = findNearestPolyInTile(tile, p, halfExtents, nearestPt); + if (!ref) + continue; + // findNearestPoly may return too optimistic results, further check to make sure. + if (dtSqr(nearestPt[0]-p[0])+dtSqr(nearestPt[2]-p[2]) > dtSqr(targetCon->rad)) + continue; + // Make sure the location is on current mesh. + float* v = &target->verts[targetPoly->verts[1]*3]; + dtVcopy(v, nearestPt); + + // Link off-mesh connection to target poly. + unsigned int idx = allocLink(target); + if (idx != DT_NULL_LINK) + { + dtLink* link = &target->links[idx]; + link->ref = ref; + link->edge = (unsigned char)1; + link->side = oppositeSide; + link->bmin = link->bmax = 0; + // Add to linked list. + link->next = targetPoly->firstLink; + targetPoly->firstLink = idx; + } + + // Link target poly to off-mesh connection. + if (targetCon->flags & DT_OFFMESH_CON_BIDIR) + { + unsigned int tidx = allocLink(tile); + if (tidx != DT_NULL_LINK) + { + const unsigned short landPolyIdx = (unsigned short)decodePolyIdPoly(ref); + dtPoly* landPoly = &tile->polys[landPolyIdx]; + dtLink* link = &tile->links[tidx]; + link->ref = getPolyRefBase(target) | (dtPolyRef)(targetCon->poly); + link->edge = 0xff; + link->side = (unsigned char)(side == -1 ? 0xff : side); + link->bmin = link->bmax = 0; + // Add to linked list. + link->next = landPoly->firstLink; + landPoly->firstLink = tidx; + } + } + } + +} + +void dtNavMesh::connectIntLinks(dtMeshTile* tile) +{ + if (!tile) return; + + dtPolyRef base = getPolyRefBase(tile); + + for (int i = 0; i < tile->header->polyCount; ++i) + { + dtPoly* poly = &tile->polys[i]; + poly->firstLink = DT_NULL_LINK; + + if (poly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION) + continue; + + // Build edge links backwards so that the links will be + // in the linked list from lowest index to highest. + for (int j = poly->vertCount-1; j >= 0; --j) + { + // Skip hard and non-internal edges. + if (poly->neis[j] == 0 || (poly->neis[j] & DT_EXT_LINK)) continue; + + unsigned int idx = allocLink(tile); + if (idx != DT_NULL_LINK) + { + dtLink* link = &tile->links[idx]; + link->ref = base | (dtPolyRef)(poly->neis[j]-1); + link->edge = (unsigned char)j; + link->side = 0xff; + link->bmin = link->bmax = 0; + // Add to linked list. + link->next = poly->firstLink; + poly->firstLink = idx; + } + } + } +} + +void dtNavMesh::baseOffMeshLinks(dtMeshTile* tile) +{ + if (!tile) return; + + dtPolyRef base = getPolyRefBase(tile); + + // Base off-mesh connection start points. + for (int i = 0; i < tile->header->offMeshConCount; ++i) + { + dtOffMeshConnection* con = &tile->offMeshCons[i]; + dtPoly* poly = &tile->polys[con->poly]; + + const float halfExtents[3] = { con->rad, tile->header->walkableClimb, con->rad }; + + // Find polygon to connect to. + const float* p = &con->pos[0]; // First vertex + float nearestPt[3]; + dtPolyRef ref = findNearestPolyInTile(tile, p, halfExtents, nearestPt); + if (!ref) continue; + // findNearestPoly may return too optimistic results, further check to make sure. + if (dtSqr(nearestPt[0]-p[0])+dtSqr(nearestPt[2]-p[2]) > dtSqr(con->rad)) + continue; + // Make sure the location is on current mesh. + float* v = &tile->verts[poly->verts[0]*3]; + dtVcopy(v, nearestPt); + + // Link off-mesh connection to target poly. + unsigned int idx = allocLink(tile); + if (idx != DT_NULL_LINK) + { + dtLink* link = &tile->links[idx]; + link->ref = ref; + link->edge = (unsigned char)0; + link->side = 0xff; + link->bmin = link->bmax = 0; + // Add to linked list. + link->next = poly->firstLink; + poly->firstLink = idx; + } + + // Start end-point is always connect back to off-mesh connection. + unsigned int tidx = allocLink(tile); + if (tidx != DT_NULL_LINK) + { + const unsigned short landPolyIdx = (unsigned short)decodePolyIdPoly(ref); + dtPoly* landPoly = &tile->polys[landPolyIdx]; + dtLink* link = &tile->links[tidx]; + link->ref = base | (dtPolyRef)(con->poly); + link->edge = 0xff; + link->side = 0xff; + link->bmin = link->bmax = 0; + // Add to linked list. + link->next = landPoly->firstLink; + landPoly->firstLink = tidx; + } + } +} + +namespace +{ +void closestPointOnDetailEdges(const dtMeshTile* tile, const dtPoly* poly, const float* pos, float* closest, bool onlyBoundary) +{ + const unsigned int ip = (unsigned int)(poly - tile->polys); + const dtPolyDetail* pd = &tile->detailMeshes[ip]; + + float dmin = FLT_MAX; + float tmin = 0; + const float* pmin = 0; + const float* pmax = 0; + + for (int i = 0; i < pd->triCount; i++) + { + const unsigned char* tris = &tile->detailTris[(pd->triBase + i) * 4]; + const int ANY_BOUNDARY_EDGE = + (DT_DETAIL_EDGE_BOUNDARY << 0) | (DT_DETAIL_EDGE_BOUNDARY << 2) | (DT_DETAIL_EDGE_BOUNDARY << 4); + if (onlyBoundary && (tris[3] & ANY_BOUNDARY_EDGE) == 0) + { + continue; + } + + const float* v[3]; + for (int j = 0; j < 3; ++j) + { + if (tris[j] < poly->vertCount) + { + v[j] = &tile->verts[poly->verts[tris[j]] * 3]; + } + else + { + v[j] = &tile->detailVerts[(pd->vertBase + (tris[j] - poly->vertCount)) * 3]; + } + } + + for (int k = 0, j = 2; k < 3; j = k++) + { + if ((dtGetDetailTriEdgeFlags(tris[3], j) & DT_DETAIL_EDGE_BOUNDARY) == 0 && (onlyBoundary || tris[j] < tris[k])) + { + // Only looking at boundary edges and this is internal, or + // this is an inner edge that we will see again or have already seen. + continue; + } + + float t; + float d = dtDistancePtSegSqr2D(pos, v[j], v[k], t); + if (d < dmin) + { + dmin = d; + tmin = t; + pmin = v[j]; + pmax = v[k]; + } + } + } + + dtVlerp(closest, pmin, pmax, tmin); +} +} + +bool dtNavMesh::getPolyHeight(const dtMeshTile* tile, const dtPoly* poly, const float* pos, float* height) const +{ + // Off-mesh connections do not have detail polys and getting height + // over them does not make sense. + if (poly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION) + return false; + + const unsigned int ip = (unsigned int)(poly - tile->polys); + const dtPolyDetail* pd = &tile->detailMeshes[ip]; + + float verts[DT_VERTS_PER_POLYGON*3]; + const int nv = poly->vertCount; + for (int i = 0; i < nv; ++i) + dtVcopy(&verts[i*3], &tile->verts[poly->verts[i]*3]); + + if (!dtPointInPolygon(pos, verts, nv)) + return false; + + if (!height) + return true; + + // Find height at the location. + for (int j = 0; j < pd->triCount; ++j) + { + const unsigned char* t = &tile->detailTris[(pd->triBase+j)*4]; + const float* v[3]; + for (int k = 0; k < 3; ++k) + { + if (t[k] < poly->vertCount) + v[k] = &tile->verts[poly->verts[t[k]]*3]; + else + v[k] = &tile->detailVerts[(pd->vertBase+(t[k]-poly->vertCount))*3]; + } + float h; + if (dtClosestHeightPointTriangle(pos, v[0], v[1], v[2], h)) + { + *height = h; + return true; + } + } + + // If all triangle checks failed above (can happen with degenerate triangles + // or larger floating point values) the point is on an edge, so just select + // closest. This should almost never happen so the extra iteration here is + // ok. + float closest[3]; + closestPointOnDetailEdges(tile, poly, pos, closest, false); + *height = closest[1]; + return true; +} + +void dtNavMesh::closestPointOnPoly(dtPolyRef ref, const float* pos, float* closest, bool* posOverPoly) const +{ + const dtMeshTile* tile = 0; + const dtPoly* poly = 0; + getTileAndPolyByRefUnsafe(ref, &tile, &poly); + + dtVcopy(closest, pos); + if (getPolyHeight(tile, poly, pos, &closest[1])) + { + if (posOverPoly) + *posOverPoly = true; + return; + } + + if (posOverPoly) + *posOverPoly = false; + + // Off-mesh connections don't have detail polygons. + if (poly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION) + { + const float* v0 = &tile->verts[poly->verts[0]*3]; + const float* v1 = &tile->verts[poly->verts[1]*3]; + float t; + dtDistancePtSegSqr2D(pos, v0, v1, t); + dtVlerp(closest, v0, v1, t); + return; + } + + // Outside poly that is not an offmesh connection. + closestPointOnDetailEdges(tile, poly, pos, closest, true); +} + +dtPolyRef dtNavMesh::findNearestPolyInTile(const dtMeshTile* tile, + const float* center, const float* halfExtents, + float* nearestPt) const +{ + float bmin[3], bmax[3]; + dtVsub(bmin, center, halfExtents); + dtVadd(bmax, center, halfExtents); + + // Get nearby polygons from proximity grid. + dtPolyRef polys[128]; + int polyCount = queryPolygonsInTile(tile, bmin, bmax, polys, 128); + + // Find nearest polygon amongst the nearby polygons. + dtPolyRef nearest = 0; + float nearestDistanceSqr = FLT_MAX; + for (int i = 0; i < polyCount; ++i) + { + dtPolyRef ref = polys[i]; + float closestPtPoly[3]; + float diff[3]; + bool posOverPoly = false; + float d; + closestPointOnPoly(ref, center, closestPtPoly, &posOverPoly); + + // If a point is directly over a polygon and closer than + // climb height, favor that instead of straight line nearest point. + dtVsub(diff, center, closestPtPoly); + if (posOverPoly) + { + d = dtAbs(diff[1]) - tile->header->walkableClimb; + d = d > 0 ? d*d : 0; + } + else + { + d = dtVlenSqr(diff); + } + + if (d < nearestDistanceSqr) + { + dtVcopy(nearestPt, closestPtPoly); + nearestDistanceSqr = d; + nearest = ref; + } + } + + return nearest; +} + +int dtNavMesh::queryPolygonsInTile(const dtMeshTile* tile, const float* qmin, const float* qmax, + dtPolyRef* polys, const int maxPolys) const +{ + if (tile->bvTree) + { + const dtBVNode* node = &tile->bvTree[0]; + const dtBVNode* end = &tile->bvTree[tile->header->bvNodeCount]; + const float* tbmin = tile->header->bmin; + const float* tbmax = tile->header->bmax; + const float qfac = tile->header->bvQuantFactor; + + // Calculate quantized box + unsigned short bmin[3], bmax[3]; + // dtClamp query box to world box. + float minx = dtClamp(qmin[0], tbmin[0], tbmax[0]) - tbmin[0]; + float miny = dtClamp(qmin[1], tbmin[1], tbmax[1]) - tbmin[1]; + float minz = dtClamp(qmin[2], tbmin[2], tbmax[2]) - tbmin[2]; + float maxx = dtClamp(qmax[0], tbmin[0], tbmax[0]) - tbmin[0]; + float maxy = dtClamp(qmax[1], tbmin[1], tbmax[1]) - tbmin[1]; + float maxz = dtClamp(qmax[2], tbmin[2], tbmax[2]) - tbmin[2]; + // Quantize + bmin[0] = (unsigned short)(qfac * minx) & 0xfffe; + bmin[1] = (unsigned short)(qfac * miny) & 0xfffe; + bmin[2] = (unsigned short)(qfac * minz) & 0xfffe; + bmax[0] = (unsigned short)(qfac * maxx + 1) | 1; + bmax[1] = (unsigned short)(qfac * maxy + 1) | 1; + bmax[2] = (unsigned short)(qfac * maxz + 1) | 1; + + // Traverse tree + dtPolyRef base = getPolyRefBase(tile); + int n = 0; + while (node < end) + { + const bool overlap = dtOverlapQuantBounds(bmin, bmax, node->bmin, node->bmax); + const bool isLeafNode = node->i >= 0; + + if (isLeafNode && overlap) + { + if (n < maxPolys) + polys[n++] = base | (dtPolyRef)node->i; + } + + if (overlap || isLeafNode) + node++; + else + { + const int escapeIndex = -node->i; + node += escapeIndex; + } + } + + return n; + } + else + { + float bmin[3], bmax[3]; + int n = 0; + dtPolyRef base = getPolyRefBase(tile); + for (int i = 0; i < tile->header->polyCount; ++i) + { + dtPoly* p = &tile->polys[i]; + // Do not return off-mesh connection polygons. + if (p->getType() == DT_POLYTYPE_OFFMESH_CONNECTION) + continue; + // Calc polygon bounds. + const float* v = &tile->verts[p->verts[0]*3]; + dtVcopy(bmin, v); + dtVcopy(bmax, v); + for (int j = 1; j < p->vertCount; ++j) + { + v = &tile->verts[p->verts[j]*3]; + dtVmin(bmin, v); + dtVmax(bmax, v); + } + if (dtOverlapBounds(qmin,qmax, bmin,bmax)) + { + if (n < maxPolys) + polys[n++] = base | (dtPolyRef)i; + } + } + return n; + } +} + +/// @par +/// +/// The add operation will fail if the data is in the wrong format, the allocated tile +/// space is full, or there is a tile already at the specified reference. +/// +/// The lastRef parameter is used to restore a tile with the same tile +/// reference it had previously used. In this case the #dtPolyRef's for the +/// tile will be restored to the same values they were before the tile was +/// removed. +/// +/// The nav mesh assumes exclusive access to the data passed and will make +/// changes to the dynamic portion of the data. For that reason the data +/// should not be reused in other nav meshes until the tile has been successfully +/// removed from this nav mesh. +/// +/// @see dtCreateNavMeshData, #removeTile +dtStatus dtNavMesh::addTile(unsigned char* data, int dataSize, int flags, + dtTileRef lastRef, dtTileRef* result) +{ + // Make sure the data is in right format. + dtMeshHeader* header = (dtMeshHeader*)data; + if (header->magic != DT_NAVMESH_MAGIC) + return DT_FAILURE | DT_WRONG_MAGIC; + if (header->version != DT_NAVMESH_VERSION) + return DT_FAILURE | DT_WRONG_VERSION; + +#ifndef DT_POLYREF64 + // Do not allow adding more polygons than specified in the NavMesh's maxPolys constraint. + // Otherwise, the poly ID cannot be represented with the given number of bits. + if (m_polyBits < dtIlog2(dtNextPow2((unsigned int)header->polyCount))) + return DT_FAILURE | DT_INVALID_PARAM; +#endif + + // Make sure the location is free. + if (getTileAt(header->x, header->y, header->layer)) + return DT_FAILURE | DT_ALREADY_OCCUPIED; + + // Allocate a tile. + dtMeshTile* tile = 0; + if (!lastRef) + { + if (m_nextFree) + { + tile = m_nextFree; + m_nextFree = tile->next; + tile->next = 0; + } + } + else + { + // Try to relocate the tile to specific index with same salt. + int tileIndex = (int)decodePolyIdTile((dtPolyRef)lastRef); + if (tileIndex >= m_maxTiles) + return DT_FAILURE | DT_OUT_OF_MEMORY; + // Try to find the specific tile id from the free list. + dtMeshTile* target = &m_tiles[tileIndex]; + dtMeshTile* prev = 0; + tile = m_nextFree; + while (tile && tile != target) + { + prev = tile; + tile = tile->next; + } + // Could not find the correct location. + if (tile != target) + return DT_FAILURE | DT_OUT_OF_MEMORY; + // Remove from freelist + if (!prev) + m_nextFree = tile->next; + else + prev->next = tile->next; + + // Restore salt. + tile->salt = decodePolyIdSalt((dtPolyRef)lastRef); + } + + // Make sure we could allocate a tile. + if (!tile) + return DT_FAILURE | DT_OUT_OF_MEMORY; + + // Insert tile into the position lut. + int h = computeTileHash(header->x, header->y, m_tileLutMask); + tile->next = m_posLookup[h]; + m_posLookup[h] = tile; + + // Patch header pointers. + const int headerSize = dtAlign4(sizeof(dtMeshHeader)); + const int vertsSize = dtAlign4(sizeof(float)*3*header->vertCount); + const int polysSize = dtAlign4(sizeof(dtPoly)*header->polyCount); + const int linksSize = dtAlign4(sizeof(dtLink)*(header->maxLinkCount)); + const int detailMeshesSize = dtAlign4(sizeof(dtPolyDetail)*header->detailMeshCount); + const int detailVertsSize = dtAlign4(sizeof(float)*3*header->detailVertCount); + const int detailTrisSize = dtAlign4(sizeof(unsigned char)*4*header->detailTriCount); + const int bvtreeSize = dtAlign4(sizeof(dtBVNode)*header->bvNodeCount); + const int offMeshLinksSize = dtAlign4(sizeof(dtOffMeshConnection)*header->offMeshConCount); + + unsigned char* d = data + headerSize; + tile->verts = dtGetThenAdvanceBufferPointer(d, vertsSize); + tile->polys = dtGetThenAdvanceBufferPointer(d, polysSize); + tile->links = dtGetThenAdvanceBufferPointer(d, linksSize); + tile->detailMeshes = dtGetThenAdvanceBufferPointer(d, detailMeshesSize); + tile->detailVerts = dtGetThenAdvanceBufferPointer(d, detailVertsSize); + tile->detailTris = dtGetThenAdvanceBufferPointer(d, detailTrisSize); + tile->bvTree = dtGetThenAdvanceBufferPointer(d, bvtreeSize); + tile->offMeshCons = dtGetThenAdvanceBufferPointer(d, offMeshLinksSize); + + // If there are no items in the bvtree, reset the tree pointer. + if (!bvtreeSize) + tile->bvTree = 0; + + // Build links freelist + tile->linksFreeList = 0; + tile->links[header->maxLinkCount-1].next = DT_NULL_LINK; + for (int i = 0; i < header->maxLinkCount-1; ++i) + tile->links[i].next = i+1; + + // Init tile. + tile->header = header; + tile->data = data; + tile->dataSize = dataSize; + tile->flags = flags; + + connectIntLinks(tile); + + // Base off-mesh connections to their starting polygons and connect connections inside the tile. + baseOffMeshLinks(tile); + connectExtOffMeshLinks(tile, tile, -1); + + // Create connections with neighbour tiles. + static const int MAX_NEIS = 32; + dtMeshTile* neis[MAX_NEIS]; + int nneis; + + // Connect with layers in current tile. + nneis = getTilesAt(header->x, header->y, neis, MAX_NEIS); + for (int j = 0; j < nneis; ++j) + { + if (neis[j] == tile) + continue; + + connectExtLinks(tile, neis[j], -1); + connectExtLinks(neis[j], tile, -1); + connectExtOffMeshLinks(tile, neis[j], -1); + connectExtOffMeshLinks(neis[j], tile, -1); + } + + // Connect with neighbour tiles. + for (int i = 0; i < 8; ++i) + { + nneis = getNeighbourTilesAt(header->x, header->y, i, neis, MAX_NEIS); + for (int j = 0; j < nneis; ++j) + { + connectExtLinks(tile, neis[j], i); + connectExtLinks(neis[j], tile, dtOppositeTile(i)); + connectExtOffMeshLinks(tile, neis[j], i); + connectExtOffMeshLinks(neis[j], tile, dtOppositeTile(i)); + } + } + + if (result) + *result = getTileRef(tile); + + return DT_SUCCESS; +} + +const dtMeshTile* dtNavMesh::getTileAt(const int x, const int y, const int layer) const +{ + // Find tile based on hash. + int h = computeTileHash(x,y,m_tileLutMask); + dtMeshTile* tile = m_posLookup[h]; + while (tile) + { + if (tile->header && + tile->header->x == x && + tile->header->y == y && + tile->header->layer == layer) + { + return tile; + } + tile = tile->next; + } + return 0; +} + +int dtNavMesh::getNeighbourTilesAt(const int x, const int y, const int side, dtMeshTile** tiles, const int maxTiles) const +{ + int nx = x, ny = y; + switch (side) + { + case 0: nx++; break; + case 1: nx++; ny++; break; + case 2: ny++; break; + case 3: nx--; ny++; break; + case 4: nx--; break; + case 5: nx--; ny--; break; + case 6: ny--; break; + case 7: nx++; ny--; break; + }; + + return getTilesAt(nx, ny, tiles, maxTiles); +} + +int dtNavMesh::getTilesAt(const int x, const int y, dtMeshTile** tiles, const int maxTiles) const +{ + int n = 0; + + // Find tile based on hash. + int h = computeTileHash(x,y,m_tileLutMask); + dtMeshTile* tile = m_posLookup[h]; + while (tile) + { + if (tile->header && + tile->header->x == x && + tile->header->y == y) + { + if (n < maxTiles) + tiles[n++] = tile; + } + tile = tile->next; + } + + return n; +} + +/// @par +/// +/// This function will not fail if the tiles array is too small to hold the +/// entire result set. It will simply fill the array to capacity. +int dtNavMesh::getTilesAt(const int x, const int y, dtMeshTile const** tiles, const int maxTiles) const +{ + int n = 0; + + // Find tile based on hash. + int h = computeTileHash(x,y,m_tileLutMask); + dtMeshTile* tile = m_posLookup[h]; + while (tile) + { + if (tile->header && + tile->header->x == x && + tile->header->y == y) + { + if (n < maxTiles) + tiles[n++] = tile; + } + tile = tile->next; + } + + return n; +} + + +dtTileRef dtNavMesh::getTileRefAt(const int x, const int y, const int layer) const +{ + // Find tile based on hash. + int h = computeTileHash(x,y,m_tileLutMask); + dtMeshTile* tile = m_posLookup[h]; + while (tile) + { + if (tile->header && + tile->header->x == x && + tile->header->y == y && + tile->header->layer == layer) + { + return getTileRef(tile); + } + tile = tile->next; + } + return 0; +} + +const dtMeshTile* dtNavMesh::getTileByRef(dtTileRef ref) const +{ + if (!ref) + return 0; + unsigned int tileIndex = decodePolyIdTile((dtPolyRef)ref); + unsigned int tileSalt = decodePolyIdSalt((dtPolyRef)ref); + if ((int)tileIndex >= m_maxTiles) + return 0; + const dtMeshTile* tile = &m_tiles[tileIndex]; + if (tile->salt != tileSalt) + return 0; + return tile; +} + +int dtNavMesh::getMaxTiles() const +{ + return m_maxTiles; +} + +dtMeshTile* dtNavMesh::getTile(int i) +{ + return &m_tiles[i]; +} + +const dtMeshTile* dtNavMesh::getTile(int i) const +{ + return &m_tiles[i]; +} + +void dtNavMesh::calcTileLoc(const float* pos, int* tx, int* ty) const +{ + *tx = (int)floorf((pos[0]-m_orig[0]) / m_tileWidth); + *ty = (int)floorf((pos[2]-m_orig[2]) / m_tileHeight); +} + +dtStatus dtNavMesh::getTileAndPolyByRef(const dtPolyRef ref, const dtMeshTile** tile, const dtPoly** poly) const +{ + if (!ref) return DT_FAILURE; + unsigned int salt, it, ip; + decodePolyId(ref, salt, it, ip); + if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM; + if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM; + if (ip >= (unsigned int)m_tiles[it].header->polyCount) return DT_FAILURE | DT_INVALID_PARAM; + *tile = &m_tiles[it]; + *poly = &m_tiles[it].polys[ip]; + return DT_SUCCESS; +} + +/// @par +/// +/// @warning Only use this function if it is known that the provided polygon +/// reference is valid. This function is faster than #getTileAndPolyByRef, but +/// it does not validate the reference. +void dtNavMesh::getTileAndPolyByRefUnsafe(const dtPolyRef ref, const dtMeshTile** tile, const dtPoly** poly) const +{ + unsigned int salt, it, ip; + decodePolyId(ref, salt, it, ip); + *tile = &m_tiles[it]; + *poly = &m_tiles[it].polys[ip]; +} + +bool dtNavMesh::isValidPolyRef(dtPolyRef ref) const +{ + if (!ref) return false; + unsigned int salt, it, ip; + decodePolyId(ref, salt, it, ip); + if (it >= (unsigned int)m_maxTiles) return false; + if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return false; + if (ip >= (unsigned int)m_tiles[it].header->polyCount) return false; + return true; +} + +/// @par +/// +/// This function returns the data for the tile so that, if desired, +/// it can be added back to the navigation mesh at a later point. +/// +/// @see #addTile +dtStatus dtNavMesh::removeTile(dtTileRef ref, unsigned char** data, int* dataSize) +{ + if (!ref) + return DT_FAILURE | DT_INVALID_PARAM; + unsigned int tileIndex = decodePolyIdTile((dtPolyRef)ref); + unsigned int tileSalt = decodePolyIdSalt((dtPolyRef)ref); + if ((int)tileIndex >= m_maxTiles) + return DT_FAILURE | DT_INVALID_PARAM; + dtMeshTile* tile = &m_tiles[tileIndex]; + if (tile->salt != tileSalt) + return DT_FAILURE | DT_INVALID_PARAM; + + // Remove tile from hash lookup. + int h = computeTileHash(tile->header->x,tile->header->y,m_tileLutMask); + dtMeshTile* prev = 0; + dtMeshTile* cur = m_posLookup[h]; + while (cur) + { + if (cur == tile) + { + if (prev) + prev->next = cur->next; + else + m_posLookup[h] = cur->next; + break; + } + prev = cur; + cur = cur->next; + } + + // Remove connections to neighbour tiles. + static const int MAX_NEIS = 32; + dtMeshTile* neis[MAX_NEIS]; + int nneis; + + // Disconnect from other layers in current tile. + nneis = getTilesAt(tile->header->x, tile->header->y, neis, MAX_NEIS); + for (int j = 0; j < nneis; ++j) + { + if (neis[j] == tile) continue; + unconnectLinks(neis[j], tile); + } + + // Disconnect from neighbour tiles. + for (int i = 0; i < 8; ++i) + { + nneis = getNeighbourTilesAt(tile->header->x, tile->header->y, i, neis, MAX_NEIS); + for (int j = 0; j < nneis; ++j) + unconnectLinks(neis[j], tile); + } + + // Reset tile. + if (tile->flags & DT_TILE_FREE_DATA) + { + // Owns data + dtFree(tile->data); + tile->data = 0; + tile->dataSize = 0; + if (data) *data = 0; + if (dataSize) *dataSize = 0; + } + else + { + if (data) *data = tile->data; + if (dataSize) *dataSize = tile->dataSize; + } + + tile->header = 0; + tile->flags = 0; + tile->linksFreeList = 0; + tile->polys = 0; + tile->verts = 0; + tile->links = 0; + tile->detailMeshes = 0; + tile->detailVerts = 0; + tile->detailTris = 0; + tile->bvTree = 0; + tile->offMeshCons = 0; + + // Update salt, salt should never be zero. +#ifdef DT_POLYREF64 + tile->salt = (tile->salt+1) & ((1<salt = (tile->salt+1) & ((1<salt == 0) + tile->salt++; + + // Add to free list. + tile->next = m_nextFree; + m_nextFree = tile; + + return DT_SUCCESS; +} + +dtTileRef dtNavMesh::getTileRef(const dtMeshTile* tile) const +{ + if (!tile) return 0; + const unsigned int it = (unsigned int)(tile - m_tiles); + return (dtTileRef)encodePolyId(tile->salt, it, 0); +} + +/// @par +/// +/// Example use case: +/// @code +/// +/// const dtPolyRef base = navmesh->getPolyRefBase(tile); +/// for (int i = 0; i < tile->header->polyCount; ++i) +/// { +/// const dtPoly* p = &tile->polys[i]; +/// const dtPolyRef ref = base | (dtPolyRef)i; +/// +/// // Use the reference to access the polygon data. +/// } +/// @endcode +dtPolyRef dtNavMesh::getPolyRefBase(const dtMeshTile* tile) const +{ + if (!tile) return 0; + const unsigned int it = (unsigned int)(tile - m_tiles); + return encodePolyId(tile->salt, it, 0); +} + +struct dtTileState +{ + int magic; // Magic number, used to identify the data. + int version; // Data version number. + dtTileRef ref; // Tile ref at the time of storing the data. +}; + +struct dtPolyState +{ + unsigned short flags; // Flags (see dtPolyFlags). + unsigned char area; // Area ID of the polygon. +}; + +/// @see #storeTileState +int dtNavMesh::getTileStateSize(const dtMeshTile* tile) const +{ + if (!tile) return 0; + const int headerSize = dtAlign4(sizeof(dtTileState)); + const int polyStateSize = dtAlign4(sizeof(dtPolyState) * tile->header->polyCount); + return headerSize + polyStateSize; +} + +/// @par +/// +/// Tile state includes non-structural data such as polygon flags, area ids, etc. +/// @note The state data is only valid until the tile reference changes. +/// @see #getTileStateSize, #restoreTileState +dtStatus dtNavMesh::storeTileState(const dtMeshTile* tile, unsigned char* data, const int maxDataSize) const +{ + // Make sure there is enough space to store the state. + const int sizeReq = getTileStateSize(tile); + if (maxDataSize < sizeReq) + return DT_FAILURE | DT_BUFFER_TOO_SMALL; + + dtTileState* tileState = dtGetThenAdvanceBufferPointer(data, dtAlign4(sizeof(dtTileState))); + dtPolyState* polyStates = dtGetThenAdvanceBufferPointer(data, dtAlign4(sizeof(dtPolyState) * tile->header->polyCount)); + + // Store tile state. + tileState->magic = DT_NAVMESH_STATE_MAGIC; + tileState->version = DT_NAVMESH_STATE_VERSION; + tileState->ref = getTileRef(tile); + + // Store per poly state. + for (int i = 0; i < tile->header->polyCount; ++i) + { + const dtPoly* p = &tile->polys[i]; + dtPolyState* s = &polyStates[i]; + s->flags = p->flags; + s->area = p->getArea(); + } + + return DT_SUCCESS; +} + +/// @par +/// +/// Tile state includes non-structural data such as polygon flags, area ids, etc. +/// @note This function does not impact the tile's #dtTileRef and #dtPolyRef's. +/// @see #storeTileState +dtStatus dtNavMesh::restoreTileState(dtMeshTile* tile, const unsigned char* data, const int maxDataSize) +{ + // Make sure there is enough space to store the state. + const int sizeReq = getTileStateSize(tile); + if (maxDataSize < sizeReq) + return DT_FAILURE | DT_INVALID_PARAM; + + const dtTileState* tileState = dtGetThenAdvanceBufferPointer(data, dtAlign4(sizeof(dtTileState))); + const dtPolyState* polyStates = dtGetThenAdvanceBufferPointer(data, dtAlign4(sizeof(dtPolyState) * tile->header->polyCount)); + + // Check that the restore is possible. + if (tileState->magic != DT_NAVMESH_STATE_MAGIC) + return DT_FAILURE | DT_WRONG_MAGIC; + if (tileState->version != DT_NAVMESH_STATE_VERSION) + return DT_FAILURE | DT_WRONG_VERSION; + if (tileState->ref != getTileRef(tile)) + return DT_FAILURE | DT_INVALID_PARAM; + + // Restore per poly state. + for (int i = 0; i < tile->header->polyCount; ++i) + { + dtPoly* p = &tile->polys[i]; + const dtPolyState* s = &polyStates[i]; + p->flags = s->flags; + p->setArea(s->area); + } + + return DT_SUCCESS; +} + +/// @par +/// +/// Off-mesh connections are stored in the navigation mesh as special 2-vertex +/// polygons with a single edge. At least one of the vertices is expected to be +/// inside a normal polygon. So an off-mesh connection is "entered" from a +/// normal polygon at one of its endpoints. This is the polygon identified by +/// the prevRef parameter. +dtStatus dtNavMesh::getOffMeshConnectionPolyEndPoints(dtPolyRef prevRef, dtPolyRef polyRef, float* startPos, float* endPos) const +{ + unsigned int salt, it, ip; + + if (!polyRef) + return DT_FAILURE; + + // Get current polygon + decodePolyId(polyRef, salt, it, ip); + if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM; + if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM; + const dtMeshTile* tile = &m_tiles[it]; + if (ip >= (unsigned int)tile->header->polyCount) return DT_FAILURE | DT_INVALID_PARAM; + const dtPoly* poly = &tile->polys[ip]; + + // Make sure that the current poly is indeed off-mesh link. + if (poly->getType() != DT_POLYTYPE_OFFMESH_CONNECTION) + return DT_FAILURE; + + // Figure out which way to hand out the vertices. + int idx0 = 0, idx1 = 1; + + // Find link that points to first vertex. + for (unsigned int i = poly->firstLink; i != DT_NULL_LINK; i = tile->links[i].next) + { + if (tile->links[i].edge == 0) + { + if (tile->links[i].ref != prevRef) + { + idx0 = 1; + idx1 = 0; + } + break; + } + } + + dtVcopy(startPos, &tile->verts[poly->verts[idx0]*3]); + dtVcopy(endPos, &tile->verts[poly->verts[idx1]*3]); + + return DT_SUCCESS; +} + + +const dtOffMeshConnection* dtNavMesh::getOffMeshConnectionByRef(dtPolyRef ref) const +{ + unsigned int salt, it, ip; + + if (!ref) + return 0; + + // Get current polygon + decodePolyId(ref, salt, it, ip); + if (it >= (unsigned int)m_maxTiles) return 0; + if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return 0; + const dtMeshTile* tile = &m_tiles[it]; + if (ip >= (unsigned int)tile->header->polyCount) return 0; + const dtPoly* poly = &tile->polys[ip]; + + // Make sure that the current poly is indeed off-mesh link. + if (poly->getType() != DT_POLYTYPE_OFFMESH_CONNECTION) + return 0; + + const unsigned int idx = ip - tile->header->offMeshBase; + dtAssert(idx < (unsigned int)tile->header->offMeshConCount); + return &tile->offMeshCons[idx]; +} + + +dtStatus dtNavMesh::setPolyFlags(dtPolyRef ref, unsigned short flags) +{ + if (!ref) return DT_FAILURE; + unsigned int salt, it, ip; + decodePolyId(ref, salt, it, ip); + if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM; + if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM; + dtMeshTile* tile = &m_tiles[it]; + if (ip >= (unsigned int)tile->header->polyCount) return DT_FAILURE | DT_INVALID_PARAM; + dtPoly* poly = &tile->polys[ip]; + + // Change flags. + poly->flags = flags; + + return DT_SUCCESS; +} + +dtStatus dtNavMesh::getPolyFlags(dtPolyRef ref, unsigned short* resultFlags) const +{ + if (!ref) return DT_FAILURE; + unsigned int salt, it, ip; + decodePolyId(ref, salt, it, ip); + if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM; + if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM; + const dtMeshTile* tile = &m_tiles[it]; + if (ip >= (unsigned int)tile->header->polyCount) return DT_FAILURE | DT_INVALID_PARAM; + const dtPoly* poly = &tile->polys[ip]; + + *resultFlags = poly->flags; + + return DT_SUCCESS; +} + +dtStatus dtNavMesh::setPolyArea(dtPolyRef ref, unsigned char area) +{ + if (!ref) return DT_FAILURE; + unsigned int salt, it, ip; + decodePolyId(ref, salt, it, ip); + if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM; + if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM; + dtMeshTile* tile = &m_tiles[it]; + if (ip >= (unsigned int)tile->header->polyCount) return DT_FAILURE | DT_INVALID_PARAM; + dtPoly* poly = &tile->polys[ip]; + + poly->setArea(area); + + return DT_SUCCESS; +} + +dtStatus dtNavMesh::getPolyArea(dtPolyRef ref, unsigned char* resultArea) const +{ + if (!ref) return DT_FAILURE; + unsigned int salt, it, ip; + decodePolyId(ref, salt, it, ip); + if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM; + if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM; + const dtMeshTile* tile = &m_tiles[it]; + if (ip >= (unsigned int)tile->header->polyCount) return DT_FAILURE | DT_INVALID_PARAM; + const dtPoly* poly = &tile->polys[ip]; + + *resultArea = poly->getArea(); + + return DT_SUCCESS; +} + diff --git a/native/third_party/recastnavigation/Detour/Source/DetourNavMeshBuilder.cpp b/native/third_party/recastnavigation/Detour/Source/DetourNavMeshBuilder.cpp new file mode 100644 index 0000000..07ba863 --- /dev/null +++ b/native/third_party/recastnavigation/Detour/Source/DetourNavMeshBuilder.cpp @@ -0,0 +1,802 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#include +#include +#include +#include +#include "DetourNavMesh.h" +#include "DetourCommon.h" +#include "DetourMath.h" +#include "DetourNavMeshBuilder.h" +#include "DetourAlloc.h" +#include "DetourAssert.h" + +static unsigned short MESH_NULL_IDX = 0xffff; + + +struct BVItem +{ + unsigned short bmin[3]; + unsigned short bmax[3]; + int i; +}; + +static int compareItemX(const void* va, const void* vb) +{ + const BVItem* a = (const BVItem*)va; + const BVItem* b = (const BVItem*)vb; + if (a->bmin[0] < b->bmin[0]) + return -1; + if (a->bmin[0] > b->bmin[0]) + return 1; + return 0; +} + +static int compareItemY(const void* va, const void* vb) +{ + const BVItem* a = (const BVItem*)va; + const BVItem* b = (const BVItem*)vb; + if (a->bmin[1] < b->bmin[1]) + return -1; + if (a->bmin[1] > b->bmin[1]) + return 1; + return 0; +} + +static int compareItemZ(const void* va, const void* vb) +{ + const BVItem* a = (const BVItem*)va; + const BVItem* b = (const BVItem*)vb; + if (a->bmin[2] < b->bmin[2]) + return -1; + if (a->bmin[2] > b->bmin[2]) + return 1; + return 0; +} + +static void calcExtends(BVItem* items, const int /*nitems*/, const int imin, const int imax, + unsigned short* bmin, unsigned short* bmax) +{ + bmin[0] = items[imin].bmin[0]; + bmin[1] = items[imin].bmin[1]; + bmin[2] = items[imin].bmin[2]; + + bmax[0] = items[imin].bmax[0]; + bmax[1] = items[imin].bmax[1]; + bmax[2] = items[imin].bmax[2]; + + for (int i = imin+1; i < imax; ++i) + { + const BVItem& it = items[i]; + if (it.bmin[0] < bmin[0]) bmin[0] = it.bmin[0]; + if (it.bmin[1] < bmin[1]) bmin[1] = it.bmin[1]; + if (it.bmin[2] < bmin[2]) bmin[2] = it.bmin[2]; + + if (it.bmax[0] > bmax[0]) bmax[0] = it.bmax[0]; + if (it.bmax[1] > bmax[1]) bmax[1] = it.bmax[1]; + if (it.bmax[2] > bmax[2]) bmax[2] = it.bmax[2]; + } +} + +inline int longestAxis(unsigned short x, unsigned short y, unsigned short z) +{ + int axis = 0; + unsigned short maxVal = x; + if (y > maxVal) + { + axis = 1; + maxVal = y; + } + if (z > maxVal) + { + axis = 2; + } + return axis; +} + +static void subdivide(BVItem* items, int nitems, int imin, int imax, int& curNode, dtBVNode* nodes) +{ + int inum = imax - imin; + int icur = curNode; + + dtBVNode& node = nodes[curNode++]; + + if (inum == 1) + { + // Leaf + node.bmin[0] = items[imin].bmin[0]; + node.bmin[1] = items[imin].bmin[1]; + node.bmin[2] = items[imin].bmin[2]; + + node.bmax[0] = items[imin].bmax[0]; + node.bmax[1] = items[imin].bmax[1]; + node.bmax[2] = items[imin].bmax[2]; + + node.i = items[imin].i; + } + else + { + // Split + calcExtends(items, nitems, imin, imax, node.bmin, node.bmax); + + int axis = longestAxis(node.bmax[0] - node.bmin[0], + node.bmax[1] - node.bmin[1], + node.bmax[2] - node.bmin[2]); + + if (axis == 0) + { + // Sort along x-axis + qsort(items+imin, inum, sizeof(BVItem), compareItemX); + } + else if (axis == 1) + { + // Sort along y-axis + qsort(items+imin, inum, sizeof(BVItem), compareItemY); + } + else + { + // Sort along z-axis + qsort(items+imin, inum, sizeof(BVItem), compareItemZ); + } + + int isplit = imin+inum/2; + + // Left + subdivide(items, nitems, imin, isplit, curNode, nodes); + // Right + subdivide(items, nitems, isplit, imax, curNode, nodes); + + int iescape = curNode - icur; + // Negative index means escape. + node.i = -iescape; + } +} + +static int createBVTree(dtNavMeshCreateParams* params, dtBVNode* nodes, int /*nnodes*/) +{ + // Build tree + float quantFactor = 1 / params->cs; + BVItem* items = (BVItem*)dtAlloc(sizeof(BVItem)*params->polyCount, DT_ALLOC_TEMP); + for (int i = 0; i < params->polyCount; i++) + { + BVItem& it = items[i]; + it.i = i; + // Calc polygon bounds. Use detail meshes if available. + if (params->detailMeshes) + { + int vb = (int)params->detailMeshes[i*4+0]; + int ndv = (int)params->detailMeshes[i*4+1]; + float bmin[3]; + float bmax[3]; + + const float* dv = ¶ms->detailVerts[vb*3]; + dtVcopy(bmin, dv); + dtVcopy(bmax, dv); + + for (int j = 1; j < ndv; j++) + { + dtVmin(bmin, &dv[j * 3]); + dtVmax(bmax, &dv[j * 3]); + } + + // BV-tree uses cs for all dimensions + it.bmin[0] = (unsigned short)dtClamp((int)((bmin[0] - params->bmin[0])*quantFactor), 0, 0xffff); + it.bmin[1] = (unsigned short)dtClamp((int)((bmin[1] - params->bmin[1])*quantFactor), 0, 0xffff); + it.bmin[2] = (unsigned short)dtClamp((int)((bmin[2] - params->bmin[2])*quantFactor), 0, 0xffff); + + it.bmax[0] = (unsigned short)dtClamp((int)((bmax[0] - params->bmin[0])*quantFactor), 0, 0xffff); + it.bmax[1] = (unsigned short)dtClamp((int)((bmax[1] - params->bmin[1])*quantFactor), 0, 0xffff); + it.bmax[2] = (unsigned short)dtClamp((int)((bmax[2] - params->bmin[2])*quantFactor), 0, 0xffff); + } + else + { + const unsigned short* p = ¶ms->polys[i*params->nvp * 2]; + it.bmin[0] = it.bmax[0] = params->verts[p[0] * 3 + 0]; + it.bmin[1] = it.bmax[1] = params->verts[p[0] * 3 + 1]; + it.bmin[2] = it.bmax[2] = params->verts[p[0] * 3 + 2]; + + for (int j = 1; j < params->nvp; ++j) + { + if (p[j] == MESH_NULL_IDX) break; + unsigned short x = params->verts[p[j] * 3 + 0]; + unsigned short y = params->verts[p[j] * 3 + 1]; + unsigned short z = params->verts[p[j] * 3 + 2]; + + if (x < it.bmin[0]) it.bmin[0] = x; + if (y < it.bmin[1]) it.bmin[1] = y; + if (z < it.bmin[2]) it.bmin[2] = z; + + if (x > it.bmax[0]) it.bmax[0] = x; + if (y > it.bmax[1]) it.bmax[1] = y; + if (z > it.bmax[2]) it.bmax[2] = z; + } + // Remap y + it.bmin[1] = (unsigned short)dtMathFloorf((float)it.bmin[1] * params->ch / params->cs); + it.bmax[1] = (unsigned short)dtMathCeilf((float)it.bmax[1] * params->ch / params->cs); + } + } + + int curNode = 0; + subdivide(items, params->polyCount, 0, params->polyCount, curNode, nodes); + + dtFree(items); + + return curNode; +} + +static unsigned char classifyOffMeshPoint(const float* pt, const float* bmin, const float* bmax) +{ + static const unsigned char XP = 1<<0; + static const unsigned char ZP = 1<<1; + static const unsigned char XM = 1<<2; + static const unsigned char ZM = 1<<3; + + unsigned char outcode = 0; + outcode |= (pt[0] >= bmax[0]) ? XP : 0; + outcode |= (pt[2] >= bmax[2]) ? ZP : 0; + outcode |= (pt[0] < bmin[0]) ? XM : 0; + outcode |= (pt[2] < bmin[2]) ? ZM : 0; + + switch (outcode) + { + case XP: return 0; + case XP|ZP: return 1; + case ZP: return 2; + case XM|ZP: return 3; + case XM: return 4; + case XM|ZM: return 5; + case ZM: return 6; + case XP|ZM: return 7; + }; + + return 0xff; +} + +// TODO: Better error handling. + +/// @par +/// +/// The output data array is allocated using the detour allocator (dtAlloc()). The method +/// used to free the memory will be determined by how the tile is added to the navigation +/// mesh. +/// +/// @see dtNavMesh, dtNavMesh::addTile() +bool dtCreateNavMeshData(dtNavMeshCreateParams* params, unsigned char** outData, int* outDataSize) +{ + if (params->nvp > DT_VERTS_PER_POLYGON) + return false; + if (params->vertCount >= 0xffff) + return false; + if (!params->vertCount || !params->verts) + return false; + if (!params->polyCount || !params->polys) + return false; + + const int nvp = params->nvp; + + // Classify off-mesh connection points. We store only the connections + // whose start point is inside the tile. + unsigned char* offMeshConClass = 0; + int storedOffMeshConCount = 0; + int offMeshConLinkCount = 0; + + if (params->offMeshConCount > 0) + { + offMeshConClass = (unsigned char*)dtAlloc(sizeof(unsigned char)*params->offMeshConCount*2, DT_ALLOC_TEMP); + if (!offMeshConClass) + return false; + + // Find tight heigh bounds, used for culling out off-mesh start locations. + float hmin = FLT_MAX; + float hmax = -FLT_MAX; + + if (params->detailVerts && params->detailVertsCount) + { + for (int i = 0; i < params->detailVertsCount; ++i) + { + const float h = params->detailVerts[i*3+1]; + hmin = dtMin(hmin,h); + hmax = dtMax(hmax,h); + } + } + else + { + for (int i = 0; i < params->vertCount; ++i) + { + const unsigned short* iv = ¶ms->verts[i*3]; + const float h = params->bmin[1] + iv[1] * params->ch; + hmin = dtMin(hmin,h); + hmax = dtMax(hmax,h); + } + } + hmin -= params->walkableClimb; + hmax += params->walkableClimb; + float bmin[3], bmax[3]; + dtVcopy(bmin, params->bmin); + dtVcopy(bmax, params->bmax); + bmin[1] = hmin; + bmax[1] = hmax; + + for (int i = 0; i < params->offMeshConCount; ++i) + { + const float* p0 = ¶ms->offMeshConVerts[(i*2+0)*3]; + const float* p1 = ¶ms->offMeshConVerts[(i*2+1)*3]; + offMeshConClass[i*2+0] = classifyOffMeshPoint(p0, bmin, bmax); + offMeshConClass[i*2+1] = classifyOffMeshPoint(p1, bmin, bmax); + + // Zero out off-mesh start positions which are not even potentially touching the mesh. + if (offMeshConClass[i*2+0] == 0xff) + { + if (p0[1] < bmin[1] || p0[1] > bmax[1]) + offMeshConClass[i*2+0] = 0; + } + + // Cound how many links should be allocated for off-mesh connections. + if (offMeshConClass[i*2+0] == 0xff) + offMeshConLinkCount++; + if (offMeshConClass[i*2+1] == 0xff) + offMeshConLinkCount++; + + if (offMeshConClass[i*2+0] == 0xff) + storedOffMeshConCount++; + } + } + + // Off-mesh connections are stored as polygons, adjust values. + const int totPolyCount = params->polyCount + storedOffMeshConCount; + const int totVertCount = params->vertCount + storedOffMeshConCount*2; + + // Find portal edges which are at tile borders. + int edgeCount = 0; + int portalCount = 0; + for (int i = 0; i < params->polyCount; ++i) + { + const unsigned short* p = ¶ms->polys[i*2*nvp]; + for (int j = 0; j < nvp; ++j) + { + if (p[j] == MESH_NULL_IDX) break; + edgeCount++; + + if (p[nvp+j] & 0x8000) + { + unsigned short dir = p[nvp+j] & 0xf; + if (dir != 0xf) + portalCount++; + } + } + } + + const int maxLinkCount = edgeCount + portalCount*2 + offMeshConLinkCount*2; + + // Find unique detail vertices. + int uniqueDetailVertCount = 0; + int detailTriCount = 0; + if (params->detailMeshes) + { + // Has detail mesh, count unique detail vertex count and use input detail tri count. + detailTriCount = params->detailTriCount; + for (int i = 0; i < params->polyCount; ++i) + { + const unsigned short* p = ¶ms->polys[i*nvp*2]; + int ndv = params->detailMeshes[i*4+1]; + int nv = 0; + for (int j = 0; j < nvp; ++j) + { + if (p[j] == MESH_NULL_IDX) break; + nv++; + } + ndv -= nv; + uniqueDetailVertCount += ndv; + } + } + else + { + // No input detail mesh, build detail mesh from nav polys. + uniqueDetailVertCount = 0; // No extra detail verts. + detailTriCount = 0; + for (int i = 0; i < params->polyCount; ++i) + { + const unsigned short* p = ¶ms->polys[i*nvp*2]; + int nv = 0; + for (int j = 0; j < nvp; ++j) + { + if (p[j] == MESH_NULL_IDX) break; + nv++; + } + detailTriCount += nv-2; + } + } + + // Calculate data size + const int headerSize = dtAlign4(sizeof(dtMeshHeader)); + const int vertsSize = dtAlign4(sizeof(float)*3*totVertCount); + const int polysSize = dtAlign4(sizeof(dtPoly)*totPolyCount); + const int linksSize = dtAlign4(sizeof(dtLink)*maxLinkCount); + const int detailMeshesSize = dtAlign4(sizeof(dtPolyDetail)*params->polyCount); + const int detailVertsSize = dtAlign4(sizeof(float)*3*uniqueDetailVertCount); + const int detailTrisSize = dtAlign4(sizeof(unsigned char)*4*detailTriCount); + const int bvTreeSize = params->buildBvTree ? dtAlign4(sizeof(dtBVNode)*params->polyCount*2) : 0; + const int offMeshConsSize = dtAlign4(sizeof(dtOffMeshConnection)*storedOffMeshConCount); + + const int dataSize = headerSize + vertsSize + polysSize + linksSize + + detailMeshesSize + detailVertsSize + detailTrisSize + + bvTreeSize + offMeshConsSize; + + unsigned char* data = (unsigned char*)dtAlloc(sizeof(unsigned char)*dataSize, DT_ALLOC_PERM); + if (!data) + { + dtFree(offMeshConClass); + return false; + } + memset(data, 0, dataSize); + + unsigned char* d = data; + + dtMeshHeader* header = dtGetThenAdvanceBufferPointer(d, headerSize); + float* navVerts = dtGetThenAdvanceBufferPointer(d, vertsSize); + dtPoly* navPolys = dtGetThenAdvanceBufferPointer(d, polysSize); + d += linksSize; // Ignore links; just leave enough space for them. They'll be created on load. + dtPolyDetail* navDMeshes = dtGetThenAdvanceBufferPointer(d, detailMeshesSize); + float* navDVerts = dtGetThenAdvanceBufferPointer(d, detailVertsSize); + unsigned char* navDTris = dtGetThenAdvanceBufferPointer(d, detailTrisSize); + dtBVNode* navBvtree = dtGetThenAdvanceBufferPointer(d, bvTreeSize); + dtOffMeshConnection* offMeshCons = dtGetThenAdvanceBufferPointer(d, offMeshConsSize); + + + // Store header + header->magic = DT_NAVMESH_MAGIC; + header->version = DT_NAVMESH_VERSION; + header->x = params->tileX; + header->y = params->tileY; + header->layer = params->tileLayer; + header->userId = params->userId; + header->polyCount = totPolyCount; + header->vertCount = totVertCount; + header->maxLinkCount = maxLinkCount; + dtVcopy(header->bmin, params->bmin); + dtVcopy(header->bmax, params->bmax); + header->detailMeshCount = params->polyCount; + header->detailVertCount = uniqueDetailVertCount; + header->detailTriCount = detailTriCount; + header->bvQuantFactor = 1.0f / params->cs; + header->offMeshBase = params->polyCount; + header->walkableHeight = params->walkableHeight; + header->walkableRadius = params->walkableRadius; + header->walkableClimb = params->walkableClimb; + header->offMeshConCount = storedOffMeshConCount; + header->bvNodeCount = params->buildBvTree ? params->polyCount*2 : 0; + + const int offMeshVertsBase = params->vertCount; + const int offMeshPolyBase = params->polyCount; + + // Store vertices + // Mesh vertices + for (int i = 0; i < params->vertCount; ++i) + { + const unsigned short* iv = ¶ms->verts[i*3]; + float* v = &navVerts[i*3]; + v[0] = params->bmin[0] + iv[0] * params->cs; + v[1] = params->bmin[1] + iv[1] * params->ch; + v[2] = params->bmin[2] + iv[2] * params->cs; + } + // Off-mesh link vertices. + int n = 0; + for (int i = 0; i < params->offMeshConCount; ++i) + { + // Only store connections which start from this tile. + if (offMeshConClass[i*2+0] == 0xff) + { + const float* linkv = ¶ms->offMeshConVerts[i*2*3]; + float* v = &navVerts[(offMeshVertsBase + n*2)*3]; + dtVcopy(&v[0], &linkv[0]); + dtVcopy(&v[3], &linkv[3]); + n++; + } + } + + // Store polygons + // Mesh polys + const unsigned short* src = params->polys; + for (int i = 0; i < params->polyCount; ++i) + { + dtPoly* p = &navPolys[i]; + p->vertCount = 0; + p->flags = params->polyFlags[i]; + p->setArea(params->polyAreas[i]); + p->setType(DT_POLYTYPE_GROUND); + for (int j = 0; j < nvp; ++j) + { + if (src[j] == MESH_NULL_IDX) break; + p->verts[j] = src[j]; + if (src[nvp+j] & 0x8000) + { + // Border or portal edge. + unsigned short dir = src[nvp+j] & 0xf; + if (dir == 0xf) // Border + p->neis[j] = 0; + else if (dir == 0) // Portal x- + p->neis[j] = DT_EXT_LINK | 4; + else if (dir == 1) // Portal z+ + p->neis[j] = DT_EXT_LINK | 2; + else if (dir == 2) // Portal x+ + p->neis[j] = DT_EXT_LINK | 0; + else if (dir == 3) // Portal z- + p->neis[j] = DT_EXT_LINK | 6; + } + else + { + // Normal connection + p->neis[j] = src[nvp+j]+1; + } + + p->vertCount++; + } + src += nvp*2; + } + // Off-mesh connection vertices. + n = 0; + for (int i = 0; i < params->offMeshConCount; ++i) + { + // Only store connections which start from this tile. + if (offMeshConClass[i*2+0] == 0xff) + { + dtPoly* p = &navPolys[offMeshPolyBase+n]; + p->vertCount = 2; + p->verts[0] = (unsigned short)(offMeshVertsBase + n*2+0); + p->verts[1] = (unsigned short)(offMeshVertsBase + n*2+1); + p->flags = params->offMeshConFlags[i]; + p->setArea(params->offMeshConAreas[i]); + p->setType(DT_POLYTYPE_OFFMESH_CONNECTION); + n++; + } + } + + // Store detail meshes and vertices. + // The nav polygon vertices are stored as the first vertices on each mesh. + // We compress the mesh data by skipping them and using the navmesh coordinates. + if (params->detailMeshes) + { + unsigned short vbase = 0; + for (int i = 0; i < params->polyCount; ++i) + { + dtPolyDetail& dtl = navDMeshes[i]; + const int vb = (int)params->detailMeshes[i*4+0]; + const int ndv = (int)params->detailMeshes[i*4+1]; + const int nv = navPolys[i].vertCount; + dtl.vertBase = (unsigned int)vbase; + dtl.vertCount = (unsigned char)(ndv-nv); + dtl.triBase = (unsigned int)params->detailMeshes[i*4+2]; + dtl.triCount = (unsigned char)params->detailMeshes[i*4+3]; + // Copy vertices except the first 'nv' verts which are equal to nav poly verts. + if (ndv-nv) + { + memcpy(&navDVerts[vbase*3], ¶ms->detailVerts[(vb+nv)*3], sizeof(float)*3*(ndv-nv)); + vbase += (unsigned short)(ndv-nv); + } + } + // Store triangles. + memcpy(navDTris, params->detailTris, sizeof(unsigned char)*4*params->detailTriCount); + } + else + { + // Create dummy detail mesh by triangulating polys. + int tbase = 0; + for (int i = 0; i < params->polyCount; ++i) + { + dtPolyDetail& dtl = navDMeshes[i]; + const int nv = navPolys[i].vertCount; + dtl.vertBase = 0; + dtl.vertCount = 0; + dtl.triBase = (unsigned int)tbase; + dtl.triCount = (unsigned char)(nv-2); + // Triangulate polygon (local indices). + for (int j = 2; j < nv; ++j) + { + unsigned char* t = &navDTris[tbase*4]; + t[0] = 0; + t[1] = (unsigned char)(j-1); + t[2] = (unsigned char)j; + // Bit for each edge that belongs to poly boundary. + t[3] = (1<<2); + if (j == 2) t[3] |= (1<<0); + if (j == nv-1) t[3] |= (1<<4); + tbase++; + } + } + } + + // Store and create BVtree. + if (params->buildBvTree) + { + createBVTree(params, navBvtree, 2*params->polyCount); + } + + // Store Off-Mesh connections. + n = 0; + for (int i = 0; i < params->offMeshConCount; ++i) + { + // Only store connections which start from this tile. + if (offMeshConClass[i*2+0] == 0xff) + { + dtOffMeshConnection* con = &offMeshCons[n]; + con->poly = (unsigned short)(offMeshPolyBase + n); + // Copy connection end-points. + const float* endPts = ¶ms->offMeshConVerts[i*2*3]; + dtVcopy(&con->pos[0], &endPts[0]); + dtVcopy(&con->pos[3], &endPts[3]); + con->rad = params->offMeshConRad[i]; + con->flags = params->offMeshConDir[i] ? DT_OFFMESH_CON_BIDIR : 0; + con->side = offMeshConClass[i*2+1]; + if (params->offMeshConUserID) + con->userId = params->offMeshConUserID[i]; + n++; + } + } + + dtFree(offMeshConClass); + + *outData = data; + *outDataSize = dataSize; + + return true; +} + +bool dtNavMeshHeaderSwapEndian(unsigned char* data, const int /*dataSize*/) +{ + dtMeshHeader* header = (dtMeshHeader*)data; + + int swappedMagic = DT_NAVMESH_MAGIC; + int swappedVersion = DT_NAVMESH_VERSION; + dtSwapEndian(&swappedMagic); + dtSwapEndian(&swappedVersion); + + if ((header->magic != DT_NAVMESH_MAGIC || header->version != DT_NAVMESH_VERSION) && + (header->magic != swappedMagic || header->version != swappedVersion)) + { + return false; + } + + dtSwapEndian(&header->magic); + dtSwapEndian(&header->version); + dtSwapEndian(&header->x); + dtSwapEndian(&header->y); + dtSwapEndian(&header->layer); + dtSwapEndian(&header->userId); + dtSwapEndian(&header->polyCount); + dtSwapEndian(&header->vertCount); + dtSwapEndian(&header->maxLinkCount); + dtSwapEndian(&header->detailMeshCount); + dtSwapEndian(&header->detailVertCount); + dtSwapEndian(&header->detailTriCount); + dtSwapEndian(&header->bvNodeCount); + dtSwapEndian(&header->offMeshConCount); + dtSwapEndian(&header->offMeshBase); + dtSwapEndian(&header->walkableHeight); + dtSwapEndian(&header->walkableRadius); + dtSwapEndian(&header->walkableClimb); + dtSwapEndian(&header->bmin[0]); + dtSwapEndian(&header->bmin[1]); + dtSwapEndian(&header->bmin[2]); + dtSwapEndian(&header->bmax[0]); + dtSwapEndian(&header->bmax[1]); + dtSwapEndian(&header->bmax[2]); + dtSwapEndian(&header->bvQuantFactor); + + // Freelist index and pointers are updated when tile is added, no need to swap. + + return true; +} + +/// @par +/// +/// @warning This function assumes that the header is in the correct endianness already. +/// Call #dtNavMeshHeaderSwapEndian() first on the data if the data is expected to be in wrong endianness +/// to start with. Call #dtNavMeshHeaderSwapEndian() after the data has been swapped if converting from +/// native to foreign endianness. +bool dtNavMeshDataSwapEndian(unsigned char* data, const int /*dataSize*/) +{ + // Make sure the data is in right format. + dtMeshHeader* header = (dtMeshHeader*)data; + if (header->magic != DT_NAVMESH_MAGIC) + return false; + if (header->version != DT_NAVMESH_VERSION) + return false; + + // Patch header pointers. + const int headerSize = dtAlign4(sizeof(dtMeshHeader)); + const int vertsSize = dtAlign4(sizeof(float)*3*header->vertCount); + const int polysSize = dtAlign4(sizeof(dtPoly)*header->polyCount); + const int linksSize = dtAlign4(sizeof(dtLink)*(header->maxLinkCount)); + const int detailMeshesSize = dtAlign4(sizeof(dtPolyDetail)*header->detailMeshCount); + const int detailVertsSize = dtAlign4(sizeof(float)*3*header->detailVertCount); + const int detailTrisSize = dtAlign4(sizeof(unsigned char)*4*header->detailTriCount); + const int bvtreeSize = dtAlign4(sizeof(dtBVNode)*header->bvNodeCount); + const int offMeshLinksSize = dtAlign4(sizeof(dtOffMeshConnection)*header->offMeshConCount); + + unsigned char* d = data + headerSize; + float* verts = dtGetThenAdvanceBufferPointer(d, vertsSize); + dtPoly* polys = dtGetThenAdvanceBufferPointer(d, polysSize); + d += linksSize; // Ignore links; they technically should be endian-swapped but all their data is overwritten on load anyway. + //dtLink* links = dtGetThenAdvanceBufferPointer(d, linksSize); + dtPolyDetail* detailMeshes = dtGetThenAdvanceBufferPointer(d, detailMeshesSize); + float* detailVerts = dtGetThenAdvanceBufferPointer(d, detailVertsSize); + d += detailTrisSize; // Ignore detail tris; single bytes can't be endian-swapped. + //unsigned char* detailTris = dtGetThenAdvanceBufferPointer(d, detailTrisSize); + dtBVNode* bvTree = dtGetThenAdvanceBufferPointer(d, bvtreeSize); + dtOffMeshConnection* offMeshCons = dtGetThenAdvanceBufferPointer(d, offMeshLinksSize); + + // Vertices + for (int i = 0; i < header->vertCount*3; ++i) + { + dtSwapEndian(&verts[i]); + } + + // Polys + for (int i = 0; i < header->polyCount; ++i) + { + dtPoly* p = &polys[i]; + // poly->firstLink is update when tile is added, no need to swap. + for (int j = 0; j < DT_VERTS_PER_POLYGON; ++j) + { + dtSwapEndian(&p->verts[j]); + dtSwapEndian(&p->neis[j]); + } + dtSwapEndian(&p->flags); + } + + // Links are rebuild when tile is added, no need to swap. + + // Detail meshes + for (int i = 0; i < header->detailMeshCount; ++i) + { + dtPolyDetail* pd = &detailMeshes[i]; + dtSwapEndian(&pd->vertBase); + dtSwapEndian(&pd->triBase); + } + + // Detail verts + for (int i = 0; i < header->detailVertCount*3; ++i) + { + dtSwapEndian(&detailVerts[i]); + } + + // BV-tree + for (int i = 0; i < header->bvNodeCount; ++i) + { + dtBVNode* node = &bvTree[i]; + for (int j = 0; j < 3; ++j) + { + dtSwapEndian(&node->bmin[j]); + dtSwapEndian(&node->bmax[j]); + } + dtSwapEndian(&node->i); + } + + // Off-mesh Connections. + for (int i = 0; i < header->offMeshConCount; ++i) + { + dtOffMeshConnection* con = &offMeshCons[i]; + for (int j = 0; j < 6; ++j) + dtSwapEndian(&con->pos[j]); + dtSwapEndian(&con->rad); + dtSwapEndian(&con->poly); + } + + return true; +} diff --git a/native/third_party/recastnavigation/Detour/Source/DetourNavMeshQuery.cpp b/native/third_party/recastnavigation/Detour/Source/DetourNavMeshQuery.cpp new file mode 100644 index 0000000..7edbe3b --- /dev/null +++ b/native/third_party/recastnavigation/Detour/Source/DetourNavMeshQuery.cpp @@ -0,0 +1,3696 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#include +#include +#include "DetourNavMeshQuery.h" +#include "DetourNavMesh.h" +#include "DetourNode.h" +#include "DetourCommon.h" +#include "DetourMath.h" +#include "DetourAlloc.h" +#include "DetourAssert.h" +#include + +/// @class dtQueryFilter +/// +/// The Default Implementation +/// +/// At construction: All area costs default to 1.0. All flags are included +/// and none are excluded. +/// +/// If a polygon has both an include and an exclude flag, it will be excluded. +/// +/// The way filtering works, a navigation mesh polygon must have at least one flag +/// set to ever be considered by a query. So a polygon with no flags will never +/// be considered. +/// +/// Setting the include flags to 0 will result in all polygons being excluded. +/// +/// Custom Implementations +/// +/// DT_VIRTUAL_QUERYFILTER must be defined in order to extend this class. +/// +/// Implement a custom query filter by overriding the virtual passFilter() +/// and getCost() functions. If this is done, both functions should be as +/// fast as possible. Use cached local copies of data rather than accessing +/// your own objects where possible. +/// +/// Custom implementations do not need to adhere to the flags or cost logic +/// used by the default implementation. +/// +/// In order for A* searches to work properly, the cost should be proportional to +/// the travel distance. Implementing a cost modifier less than 1.0 is likely +/// to lead to problems during pathfinding. +/// +/// @see dtNavMeshQuery + +dtQueryFilter::dtQueryFilter() : + m_includeFlags(0xffff), + m_excludeFlags(0) +{ + for (int i = 0; i < DT_MAX_AREAS; ++i) + m_areaCost[i] = 1.0f; +} + +#ifdef DT_VIRTUAL_QUERYFILTER +bool dtQueryFilter::passFilter(const dtPolyRef /*ref*/, + const dtMeshTile* /*tile*/, + const dtPoly* poly) const +{ + return (poly->flags & m_includeFlags) != 0 && (poly->flags & m_excludeFlags) == 0; +} + +float dtQueryFilter::getCost(const float* pa, const float* pb, + const dtPolyRef /*prevRef*/, const dtMeshTile* /*prevTile*/, const dtPoly* /*prevPoly*/, + const dtPolyRef /*curRef*/, const dtMeshTile* /*curTile*/, const dtPoly* curPoly, + const dtPolyRef /*nextRef*/, const dtMeshTile* /*nextTile*/, const dtPoly* /*nextPoly*/) const +{ + return dtVdist(pa, pb) * m_areaCost[curPoly->getArea()]; +} +#else +inline bool dtQueryFilter::passFilter(const dtPolyRef /*ref*/, + const dtMeshTile* /*tile*/, + const dtPoly* poly) const +{ + return (poly->flags & m_includeFlags) != 0 && (poly->flags & m_excludeFlags) == 0; +} + +inline float dtQueryFilter::getCost(const float* pa, const float* pb, + const dtPolyRef /*prevRef*/, const dtMeshTile* /*prevTile*/, const dtPoly* /*prevPoly*/, + const dtPolyRef /*curRef*/, const dtMeshTile* /*curTile*/, const dtPoly* curPoly, + const dtPolyRef /*nextRef*/, const dtMeshTile* /*nextTile*/, const dtPoly* /*nextPoly*/) const +{ + return dtVdist(pa, pb) * m_areaCost[curPoly->getArea()]; +} +#endif + +static const float H_SCALE = 0.999f; // Search heuristic scale. + + +dtNavMeshQuery* dtAllocNavMeshQuery() +{ + void* mem = dtAlloc(sizeof(dtNavMeshQuery), DT_ALLOC_PERM); + if (!mem) return 0; + return new(mem) dtNavMeshQuery; +} + +void dtFreeNavMeshQuery(dtNavMeshQuery* navmesh) +{ + if (!navmesh) return; + navmesh->~dtNavMeshQuery(); + dtFree(navmesh); +} + +dtPolyQuery::~dtPolyQuery() +{ + // Defined out of line to fix the weak v-tables warning +} + +////////////////////////////////////////////////////////////////////////////////////////// + +/// @class dtNavMeshQuery +/// +/// For methods that support undersized buffers, if the buffer is too small +/// to hold the entire result set the return status of the method will include +/// the #DT_BUFFER_TOO_SMALL flag. +/// +/// Constant member functions can be used by multiple clients without side +/// effects. (E.g. No change to the closed list. No impact on an in-progress +/// sliced path query. Etc.) +/// +/// Walls and portals: A @e wall is a polygon segment that is +/// considered impassable. A @e portal is a passable segment between polygons. +/// A portal may be treated as a wall based on the dtQueryFilter used for a query. +/// +/// @see dtNavMesh, dtQueryFilter, #dtAllocNavMeshQuery(), #dtAllocNavMeshQuery() + +dtNavMeshQuery::dtNavMeshQuery() : + m_nav(0), + m_tinyNodePool(0), + m_nodePool(0), + m_openList(0) +{ + memset(&m_query, 0, sizeof(dtQueryData)); +} + +dtNavMeshQuery::~dtNavMeshQuery() +{ + if (m_tinyNodePool) + m_tinyNodePool->~dtNodePool(); + if (m_nodePool) + m_nodePool->~dtNodePool(); + if (m_openList) + m_openList->~dtNodeQueue(); + dtFree(m_tinyNodePool); + dtFree(m_nodePool); + dtFree(m_openList); +} + +/// @par +/// +/// Must be the first function called after construction, before other +/// functions are used. +/// +/// This function can be used multiple times. +dtStatus dtNavMeshQuery::init(const dtNavMesh* nav, const int maxNodes) +{ + if (maxNodes > DT_NULL_IDX || maxNodes > (1 << DT_NODE_PARENT_BITS) - 1) + return DT_FAILURE | DT_INVALID_PARAM; + + m_nav = nav; + + if (!m_nodePool || m_nodePool->getMaxNodes() < maxNodes) + { + if (m_nodePool) + { + m_nodePool->~dtNodePool(); + dtFree(m_nodePool); + m_nodePool = 0; + } + m_nodePool = new (dtAlloc(sizeof(dtNodePool), DT_ALLOC_PERM)) dtNodePool(maxNodes, dtNextPow2(maxNodes/4)); + if (!m_nodePool) + return DT_FAILURE | DT_OUT_OF_MEMORY; + } + else + { + m_nodePool->clear(); + } + + if (!m_tinyNodePool) + { + m_tinyNodePool = new (dtAlloc(sizeof(dtNodePool), DT_ALLOC_PERM)) dtNodePool(64, 32); + if (!m_tinyNodePool) + return DT_FAILURE | DT_OUT_OF_MEMORY; + } + else + { + m_tinyNodePool->clear(); + } + + if (!m_openList || m_openList->getCapacity() < maxNodes) + { + if (m_openList) + { + m_openList->~dtNodeQueue(); + dtFree(m_openList); + m_openList = 0; + } + m_openList = new (dtAlloc(sizeof(dtNodeQueue), DT_ALLOC_PERM)) dtNodeQueue(maxNodes); + if (!m_openList) + return DT_FAILURE | DT_OUT_OF_MEMORY; + } + else + { + m_openList->clear(); + } + + return DT_SUCCESS; +} + +dtStatus dtNavMeshQuery::findRandomPoint(const dtQueryFilter* filter, float (*frand)(), + dtPolyRef* randomRef, float* randomPt) const +{ + dtAssert(m_nav); + + if (!filter || !frand || !randomRef || !randomPt) + return DT_FAILURE | DT_INVALID_PARAM; + + // Randomly pick one tile. Assume that all tiles cover roughly the same area. + const dtMeshTile* tile = 0; + float tsum = 0.0f; + for (int i = 0; i < m_nav->getMaxTiles(); i++) + { + const dtMeshTile* t = m_nav->getTile(i); + if (!t || !t->header) continue; + + // Choose random tile using reservoir sampling. + const float area = 1.0f; // Could be tile area too. + tsum += area; + const float u = frand(); + if (u*tsum <= area) + tile = t; + } + if (!tile) + return DT_FAILURE; + + // Randomly pick one polygon weighted by polygon area. + const dtPoly* poly = 0; + dtPolyRef polyRef = 0; + const dtPolyRef base = m_nav->getPolyRefBase(tile); + + float areaSum = 0.0f; + for (int i = 0; i < tile->header->polyCount; ++i) + { + const dtPoly* p = &tile->polys[i]; + // Do not return off-mesh connection polygons. + if (p->getType() != DT_POLYTYPE_GROUND) + continue; + // Must pass filter + const dtPolyRef ref = base | (dtPolyRef)i; + if (!filter->passFilter(ref, tile, p)) + continue; + + // Calc area of the polygon. + float polyArea = 0.0f; + for (int j = 2; j < p->vertCount; ++j) + { + const float* va = &tile->verts[p->verts[0]*3]; + const float* vb = &tile->verts[p->verts[j-1]*3]; + const float* vc = &tile->verts[p->verts[j]*3]; + polyArea += dtTriArea2D(va,vb,vc); + } + + // Choose random polygon weighted by area, using reservoir sampling. + areaSum += polyArea; + const float u = frand(); + if (u*areaSum <= polyArea) + { + poly = p; + polyRef = ref; + } + } + + if (!poly) + return DT_FAILURE; + + // Randomly pick point on polygon. + const float* v = &tile->verts[poly->verts[0]*3]; + float verts[3*DT_VERTS_PER_POLYGON]; + float areas[DT_VERTS_PER_POLYGON]; + dtVcopy(&verts[0*3],v); + for (int j = 1; j < poly->vertCount; ++j) + { + v = &tile->verts[poly->verts[j]*3]; + dtVcopy(&verts[j*3],v); + } + + const float s = frand(); + const float t = frand(); + + float pt[3]; + dtRandomPointInConvexPoly(verts, poly->vertCount, areas, s, t, pt); + + closestPointOnPoly(polyRef, pt, pt, NULL); + + dtVcopy(randomPt, pt); + *randomRef = polyRef; + + return DT_SUCCESS; +} + +dtStatus dtNavMeshQuery::findRandomPointAroundCircle(dtPolyRef startRef, const float* centerPos, const float maxRadius, + const dtQueryFilter* filter, float (*frand)(), + dtPolyRef* randomRef, float* randomPt) const +{ + dtAssert(m_nav); + dtAssert(m_nodePool); + dtAssert(m_openList); + + // Validate input + if (!m_nav->isValidPolyRef(startRef) || + !centerPos || !dtVisfinite(centerPos) || + maxRadius < 0 || !dtMathIsfinite(maxRadius) || + !filter || !frand || !randomRef || !randomPt) + { + return DT_FAILURE | DT_INVALID_PARAM; + } + + const dtMeshTile* startTile = 0; + const dtPoly* startPoly = 0; + m_nav->getTileAndPolyByRefUnsafe(startRef, &startTile, &startPoly); + if (!filter->passFilter(startRef, startTile, startPoly)) + return DT_FAILURE | DT_INVALID_PARAM; + + m_nodePool->clear(); + m_openList->clear(); + + dtNode* startNode = m_nodePool->getNode(startRef); + dtVcopy(startNode->pos, centerPos); + startNode->pidx = 0; + startNode->cost = 0; + startNode->total = 0; + startNode->id = startRef; + startNode->flags = DT_NODE_OPEN; + m_openList->push(startNode); + + dtStatus status = DT_SUCCESS; + + const float radiusSqr = dtSqr(maxRadius); + float areaSum = 0.0f; + + const dtMeshTile* randomTile = 0; + const dtPoly* randomPoly = 0; + dtPolyRef randomPolyRef = 0; + + while (!m_openList->empty()) + { + dtNode* bestNode = m_openList->pop(); + bestNode->flags &= ~DT_NODE_OPEN; + bestNode->flags |= DT_NODE_CLOSED; + + // Get poly and tile. + // The API input has been checked already, skip checking internal data. + const dtPolyRef bestRef = bestNode->id; + const dtMeshTile* bestTile = 0; + const dtPoly* bestPoly = 0; + m_nav->getTileAndPolyByRefUnsafe(bestRef, &bestTile, &bestPoly); + + // Place random locations on on ground. + if (bestPoly->getType() == DT_POLYTYPE_GROUND) + { + // Calc area of the polygon. + float polyArea = 0.0f; + for (int j = 2; j < bestPoly->vertCount; ++j) + { + const float* va = &bestTile->verts[bestPoly->verts[0]*3]; + const float* vb = &bestTile->verts[bestPoly->verts[j-1]*3]; + const float* vc = &bestTile->verts[bestPoly->verts[j]*3]; + polyArea += dtTriArea2D(va,vb,vc); + } + // Choose random polygon weighted by area, using reservoir sampling. + areaSum += polyArea; + const float u = frand(); + if (u*areaSum <= polyArea) + { + randomTile = bestTile; + randomPoly = bestPoly; + randomPolyRef = bestRef; + } + } + + + // Get parent poly and tile. + dtPolyRef parentRef = 0; + const dtMeshTile* parentTile = 0; + const dtPoly* parentPoly = 0; + if (bestNode->pidx) + parentRef = m_nodePool->getNodeAtIdx(bestNode->pidx)->id; + if (parentRef) + m_nav->getTileAndPolyByRefUnsafe(parentRef, &parentTile, &parentPoly); + + for (unsigned int i = bestPoly->firstLink; i != DT_NULL_LINK; i = bestTile->links[i].next) + { + const dtLink* link = &bestTile->links[i]; + dtPolyRef neighbourRef = link->ref; + // Skip invalid neighbours and do not follow back to parent. + if (!neighbourRef || neighbourRef == parentRef) + continue; + + // Expand to neighbour + const dtMeshTile* neighbourTile = 0; + const dtPoly* neighbourPoly = 0; + m_nav->getTileAndPolyByRefUnsafe(neighbourRef, &neighbourTile, &neighbourPoly); + + // Do not advance if the polygon is excluded by the filter. + if (!filter->passFilter(neighbourRef, neighbourTile, neighbourPoly)) + continue; + + // Find edge and calc distance to the edge. + float va[3], vb[3]; + if (!getPortalPoints(bestRef, bestPoly, bestTile, neighbourRef, neighbourPoly, neighbourTile, va, vb)) + continue; + + // If the circle is not touching the next polygon, skip it. + float tseg; + float distSqr = dtDistancePtSegSqr2D(centerPos, va, vb, tseg); + if (distSqr > radiusSqr) + continue; + + dtNode* neighbourNode = m_nodePool->getNode(neighbourRef); + if (!neighbourNode) + { + status |= DT_OUT_OF_NODES; + continue; + } + + if (neighbourNode->flags & DT_NODE_CLOSED) + continue; + + // Cost + if (neighbourNode->flags == 0) + dtVlerp(neighbourNode->pos, va, vb, 0.5f); + + const float total = bestNode->total + dtVdist(bestNode->pos, neighbourNode->pos); + + // The node is already in open list and the new result is worse, skip. + if ((neighbourNode->flags & DT_NODE_OPEN) && total >= neighbourNode->total) + continue; + + neighbourNode->id = neighbourRef; + neighbourNode->flags = (neighbourNode->flags & ~DT_NODE_CLOSED); + neighbourNode->pidx = m_nodePool->getNodeIdx(bestNode); + neighbourNode->total = total; + + if (neighbourNode->flags & DT_NODE_OPEN) + { + m_openList->modify(neighbourNode); + } + else + { + neighbourNode->flags = DT_NODE_OPEN; + m_openList->push(neighbourNode); + } + } + } + + if (!randomPoly) + return DT_FAILURE; + + // Randomly pick point on polygon. + const float* v = &randomTile->verts[randomPoly->verts[0]*3]; + float verts[3*DT_VERTS_PER_POLYGON]; + float areas[DT_VERTS_PER_POLYGON]; + dtVcopy(&verts[0*3],v); + for (int j = 1; j < randomPoly->vertCount; ++j) + { + v = &randomTile->verts[randomPoly->verts[j]*3]; + dtVcopy(&verts[j*3],v); + } + + const float s = frand(); + const float t = frand(); + + float pt[3]; + dtRandomPointInConvexPoly(verts, randomPoly->vertCount, areas, s, t, pt); + + closestPointOnPoly(randomPolyRef, pt, pt, NULL); + + dtVcopy(randomPt, pt); + *randomRef = randomPolyRef; + + return status; +} + + +////////////////////////////////////////////////////////////////////////////////////////// + +/// @par +/// +/// Uses the detail polygons to find the surface height. (Most accurate.) +/// +/// @p pos does not have to be within the bounds of the polygon or navigation mesh. +/// +/// See closestPointOnPolyBoundary() for a limited but faster option. +/// +dtStatus dtNavMeshQuery::closestPointOnPoly(dtPolyRef ref, const float* pos, float* closest, bool* posOverPoly) const +{ + dtAssert(m_nav); + if (!m_nav->isValidPolyRef(ref) || + !pos || !dtVisfinite(pos) || + !closest) + { + return DT_FAILURE | DT_INVALID_PARAM; + } + + m_nav->closestPointOnPoly(ref, pos, closest, posOverPoly); + return DT_SUCCESS; +} + +/// @par +/// +/// Much faster than closestPointOnPoly(). +/// +/// If the provided position lies within the polygon's xz-bounds (above or below), +/// then @p pos and @p closest will be equal. +/// +/// The height of @p closest will be the polygon boundary. The height detail is not used. +/// +/// @p pos does not have to be within the bounds of the polybon or the navigation mesh. +/// +dtStatus dtNavMeshQuery::closestPointOnPolyBoundary(dtPolyRef ref, const float* pos, float* closest) const +{ + dtAssert(m_nav); + + const dtMeshTile* tile = 0; + const dtPoly* poly = 0; + if (dtStatusFailed(m_nav->getTileAndPolyByRef(ref, &tile, &poly))) + return DT_FAILURE | DT_INVALID_PARAM; + + if (!pos || !dtVisfinite(pos) || !closest) + return DT_FAILURE | DT_INVALID_PARAM; + + // Collect vertices. + float verts[DT_VERTS_PER_POLYGON*3]; + float edged[DT_VERTS_PER_POLYGON]; + float edget[DT_VERTS_PER_POLYGON]; + int nv = 0; + for (int i = 0; i < (int)poly->vertCount; ++i) + { + dtVcopy(&verts[nv*3], &tile->verts[poly->verts[i]*3]); + nv++; + } + + bool inside = dtDistancePtPolyEdgesSqr(pos, verts, nv, edged, edget); + if (inside) + { + // Point is inside the polygon, return the point. + dtVcopy(closest, pos); + } + else + { + // Point is outside the polygon, dtClamp to nearest edge. + float dmin = edged[0]; + int imin = 0; + for (int i = 1; i < nv; ++i) + { + if (edged[i] < dmin) + { + dmin = edged[i]; + imin = i; + } + } + const float* va = &verts[imin*3]; + const float* vb = &verts[((imin+1)%nv)*3]; + dtVlerp(closest, va, vb, edget[imin]); + } + + return DT_SUCCESS; +} + +/// @par +/// +/// Will return #DT_FAILURE | DT_INVALID_PARAM if the provided position is outside the xz-bounds +/// of the polygon. +/// +dtStatus dtNavMeshQuery::getPolyHeight(dtPolyRef ref, const float* pos, float* height) const +{ + dtAssert(m_nav); + + const dtMeshTile* tile = 0; + const dtPoly* poly = 0; + if (dtStatusFailed(m_nav->getTileAndPolyByRef(ref, &tile, &poly))) + return DT_FAILURE | DT_INVALID_PARAM; + + if (!pos || !dtVisfinite2D(pos)) + return DT_FAILURE | DT_INVALID_PARAM; + + // We used to return success for offmesh connections, but the + // getPolyHeight in DetourNavMesh does not do this, so special + // case it here. + if (poly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION) + { + const float* v0 = &tile->verts[poly->verts[0]*3]; + const float* v1 = &tile->verts[poly->verts[1]*3]; + float t; + dtDistancePtSegSqr2D(pos, v0, v1, t); + if (height) + *height = v0[1] + (v1[1] - v0[1])*t; + + return DT_SUCCESS; + } + + return m_nav->getPolyHeight(tile, poly, pos, height) + ? DT_SUCCESS + : DT_FAILURE | DT_INVALID_PARAM; +} + +class dtFindNearestPolyQuery : public dtPolyQuery +{ + const dtNavMeshQuery* m_query; + const float* m_center; + float m_nearestDistanceSqr; + dtPolyRef m_nearestRef; + float m_nearestPoint[3]; + bool m_overPoly; + +public: + dtFindNearestPolyQuery(const dtNavMeshQuery* query, const float* center) + : m_query(query), m_center(center), m_nearestDistanceSqr(FLT_MAX), m_nearestRef(0), m_nearestPoint(), m_overPoly(false) + { + } + + virtual ~dtFindNearestPolyQuery(); + + dtPolyRef nearestRef() const { return m_nearestRef; } + const float* nearestPoint() const { return m_nearestPoint; } + bool isOverPoly() const { return m_overPoly; } + + void process(const dtMeshTile* tile, dtPoly** polys, dtPolyRef* refs, int count) + { + dtIgnoreUnused(polys); + + for (int i = 0; i < count; ++i) + { + dtPolyRef ref = refs[i]; + float closestPtPoly[3]; + float diff[3]; + bool posOverPoly = false; + float d; + m_query->closestPointOnPoly(ref, m_center, closestPtPoly, &posOverPoly); + + // If a point is directly over a polygon and closer than + // climb height, favor that instead of straight line nearest point. + dtVsub(diff, m_center, closestPtPoly); + if (posOverPoly) + { + d = dtAbs(diff[1]) - tile->header->walkableClimb; + d = d > 0 ? d*d : 0; + } + else + { + d = dtVlenSqr(diff); + } + + if (d < m_nearestDistanceSqr) + { + dtVcopy(m_nearestPoint, closestPtPoly); + + m_nearestDistanceSqr = d; + m_nearestRef = ref; + m_overPoly = posOverPoly; + } + } + } +}; + +dtFindNearestPolyQuery::~dtFindNearestPolyQuery() +{ + // Defined out of line to fix the weak v-tables warning +} + +/// @par +/// +/// @note If the search box does not intersect any polygons the search will +/// return #DT_SUCCESS, but @p nearestRef will be zero. So if in doubt, check +/// @p nearestRef before using @p nearestPt. +/// +dtStatus dtNavMeshQuery::findNearestPoly(const float* center, const float* halfExtents, + const dtQueryFilter* filter, + dtPolyRef* nearestRef, float* nearestPt) const +{ + return findNearestPoly(center, halfExtents, filter, nearestRef, nearestPt, NULL); +} + +// If center and nearestPt point to an equal position, isOverPoly will be true; +// however there's also a special case of climb height inside the polygon (see dtFindNearestPolyQuery) +dtStatus dtNavMeshQuery::findNearestPoly(const float* center, const float* halfExtents, + const dtQueryFilter* filter, + dtPolyRef* nearestRef, float* nearestPt, bool* isOverPoly) const +{ + dtAssert(m_nav); + + if (!nearestRef) + return DT_FAILURE | DT_INVALID_PARAM; + + // queryPolygons below will check rest of params + + dtFindNearestPolyQuery query(this, center); + + dtStatus status = queryPolygons(center, halfExtents, filter, &query); + if (dtStatusFailed(status)) + return status; + + *nearestRef = query.nearestRef(); + // Only override nearestPt if we actually found a poly so the nearest point + // is valid. + if (nearestPt && *nearestRef) + { + dtVcopy(nearestPt, query.nearestPoint()); + if (isOverPoly) + *isOverPoly = query.isOverPoly(); + } + + return DT_SUCCESS; +} + +void dtNavMeshQuery::queryPolygonsInTile(const dtMeshTile* tile, const float* qmin, const float* qmax, + const dtQueryFilter* filter, dtPolyQuery* query) const +{ + dtAssert(m_nav); + static const int batchSize = 32; + dtPolyRef polyRefs[batchSize]; + dtPoly* polys[batchSize]; + int n = 0; + + if (tile->bvTree) + { + const dtBVNode* node = &tile->bvTree[0]; + const dtBVNode* end = &tile->bvTree[tile->header->bvNodeCount]; + const float* tbmin = tile->header->bmin; + const float* tbmax = tile->header->bmax; + const float qfac = tile->header->bvQuantFactor; + + // Calculate quantized box + unsigned short bmin[3], bmax[3]; + // dtClamp query box to world box. + float minx = dtClamp(qmin[0], tbmin[0], tbmax[0]) - tbmin[0]; + float miny = dtClamp(qmin[1], tbmin[1], tbmax[1]) - tbmin[1]; + float minz = dtClamp(qmin[2], tbmin[2], tbmax[2]) - tbmin[2]; + float maxx = dtClamp(qmax[0], tbmin[0], tbmax[0]) - tbmin[0]; + float maxy = dtClamp(qmax[1], tbmin[1], tbmax[1]) - tbmin[1]; + float maxz = dtClamp(qmax[2], tbmin[2], tbmax[2]) - tbmin[2]; + // Quantize + bmin[0] = (unsigned short)(qfac * minx) & 0xfffe; + bmin[1] = (unsigned short)(qfac * miny) & 0xfffe; + bmin[2] = (unsigned short)(qfac * minz) & 0xfffe; + bmax[0] = (unsigned short)(qfac * maxx + 1) | 1; + bmax[1] = (unsigned short)(qfac * maxy + 1) | 1; + bmax[2] = (unsigned short)(qfac * maxz + 1) | 1; + + // Traverse tree + const dtPolyRef base = m_nav->getPolyRefBase(tile); + while (node < end) + { + const bool overlap = dtOverlapQuantBounds(bmin, bmax, node->bmin, node->bmax); + const bool isLeafNode = node->i >= 0; + + if (isLeafNode && overlap) + { + dtPolyRef ref = base | (dtPolyRef)node->i; + if (filter->passFilter(ref, tile, &tile->polys[node->i])) + { + polyRefs[n] = ref; + polys[n] = &tile->polys[node->i]; + + if (n == batchSize - 1) + { + query->process(tile, polys, polyRefs, batchSize); + n = 0; + } + else + { + n++; + } + } + } + + if (overlap || isLeafNode) + node++; + else + { + const int escapeIndex = -node->i; + node += escapeIndex; + } + } + } + else + { + float bmin[3], bmax[3]; + const dtPolyRef base = m_nav->getPolyRefBase(tile); + for (int i = 0; i < tile->header->polyCount; ++i) + { + dtPoly* p = &tile->polys[i]; + // Do not return off-mesh connection polygons. + if (p->getType() == DT_POLYTYPE_OFFMESH_CONNECTION) + continue; + // Must pass filter + const dtPolyRef ref = base | (dtPolyRef)i; + if (!filter->passFilter(ref, tile, p)) + continue; + // Calc polygon bounds. + const float* v = &tile->verts[p->verts[0]*3]; + dtVcopy(bmin, v); + dtVcopy(bmax, v); + for (int j = 1; j < p->vertCount; ++j) + { + v = &tile->verts[p->verts[j]*3]; + dtVmin(bmin, v); + dtVmax(bmax, v); + } + if (dtOverlapBounds(qmin, qmax, bmin, bmax)) + { + polyRefs[n] = ref; + polys[n] = p; + + if (n == batchSize - 1) + { + query->process(tile, polys, polyRefs, batchSize); + n = 0; + } + else + { + n++; + } + } + } + } + + // Process the last polygons that didn't make a full batch. + if (n > 0) + query->process(tile, polys, polyRefs, n); +} + +class dtCollectPolysQuery : public dtPolyQuery +{ + dtPolyRef* m_polys; + const int m_maxPolys; + int m_numCollected; + bool m_overflow; + +public: + dtCollectPolysQuery(dtPolyRef* polys, const int maxPolys) + : m_polys(polys), m_maxPolys(maxPolys), m_numCollected(0), m_overflow(false) + { + } + + virtual ~dtCollectPolysQuery(); + + int numCollected() const { return m_numCollected; } + bool overflowed() const { return m_overflow; } + + void process(const dtMeshTile* tile, dtPoly** polys, dtPolyRef* refs, int count) + { + dtIgnoreUnused(tile); + dtIgnoreUnused(polys); + + int numLeft = m_maxPolys - m_numCollected; + int toCopy = count; + if (toCopy > numLeft) + { + m_overflow = true; + toCopy = numLeft; + } + + memcpy(m_polys + m_numCollected, refs, (size_t)toCopy * sizeof(dtPolyRef)); + m_numCollected += toCopy; + } +}; + +dtCollectPolysQuery::~dtCollectPolysQuery() +{ + // Defined out of line to fix the weak v-tables warning +} + +/// @par +/// +/// If no polygons are found, the function will return #DT_SUCCESS with a +/// @p polyCount of zero. +/// +/// If @p polys is too small to hold the entire result set, then the array will +/// be filled to capacity. The method of choosing which polygons from the +/// full set are included in the partial result set is undefined. +/// +dtStatus dtNavMeshQuery::queryPolygons(const float* center, const float* halfExtents, + const dtQueryFilter* filter, + dtPolyRef* polys, int* polyCount, const int maxPolys) const +{ + if (!polys || !polyCount || maxPolys < 0) + return DT_FAILURE | DT_INVALID_PARAM; + + dtCollectPolysQuery collector(polys, maxPolys); + + dtStatus status = queryPolygons(center, halfExtents, filter, &collector); + if (dtStatusFailed(status)) + return status; + + *polyCount = collector.numCollected(); + return collector.overflowed() ? DT_SUCCESS | DT_BUFFER_TOO_SMALL : DT_SUCCESS; +} + +/// @par +/// +/// The query will be invoked with batches of polygons. Polygons passed +/// to the query have bounding boxes that overlap with the center and halfExtents +/// passed to this function. The dtPolyQuery::process function is invoked multiple +/// times until all overlapping polygons have been processed. +/// +dtStatus dtNavMeshQuery::queryPolygons(const float* center, const float* halfExtents, + const dtQueryFilter* filter, dtPolyQuery* query) const +{ + dtAssert(m_nav); + + if (!center || !dtVisfinite(center) || + !halfExtents || !dtVisfinite(halfExtents) || + !filter || !query) + { + return DT_FAILURE | DT_INVALID_PARAM; + } + + float bmin[3], bmax[3]; + dtVsub(bmin, center, halfExtents); + dtVadd(bmax, center, halfExtents); + + // Find tiles the query touches. + int minx, miny, maxx, maxy; + m_nav->calcTileLoc(bmin, &minx, &miny); + m_nav->calcTileLoc(bmax, &maxx, &maxy); + + static const int MAX_NEIS = 32; + const dtMeshTile* neis[MAX_NEIS]; + + for (int y = miny; y <= maxy; ++y) + { + for (int x = minx; x <= maxx; ++x) + { + const int nneis = m_nav->getTilesAt(x,y,neis,MAX_NEIS); + for (int j = 0; j < nneis; ++j) + { + queryPolygonsInTile(neis[j], bmin, bmax, filter, query); + } + } + } + + return DT_SUCCESS; +} + +/// @par +/// +/// If the end polygon cannot be reached through the navigation graph, +/// the last polygon in the path will be the nearest the end polygon. +/// +/// If the path array is to small to hold the full result, it will be filled as +/// far as possible from the start polygon toward the end polygon. +/// +/// The start and end positions are used to calculate traversal costs. +/// (The y-values impact the result.) +/// +dtStatus dtNavMeshQuery::findPath(dtPolyRef startRef, dtPolyRef endRef, + const float* startPos, const float* endPos, + const dtQueryFilter* filter, + dtPolyRef* path, int* pathCount, const int maxPath) const +{ + dtAssert(m_nav); + dtAssert(m_nodePool); + dtAssert(m_openList); + + if (!pathCount) + return DT_FAILURE | DT_INVALID_PARAM; + + *pathCount = 0; + + // Validate input + if (!m_nav->isValidPolyRef(startRef) || !m_nav->isValidPolyRef(endRef) || + !startPos || !dtVisfinite(startPos) || + !endPos || !dtVisfinite(endPos) || + !filter || !path || maxPath <= 0) + { + return DT_FAILURE | DT_INVALID_PARAM; + } + + if (startRef == endRef) + { + path[0] = startRef; + *pathCount = 1; + return DT_SUCCESS; + } + + m_nodePool->clear(); + m_openList->clear(); + + dtNode* startNode = m_nodePool->getNode(startRef); + dtVcopy(startNode->pos, startPos); + startNode->pidx = 0; + startNode->cost = 0; + startNode->total = dtVdist(startPos, endPos) * H_SCALE; + startNode->id = startRef; + startNode->flags = DT_NODE_OPEN; + m_openList->push(startNode); + + dtNode* lastBestNode = startNode; + float lastBestNodeCost = startNode->total; + + bool outOfNodes = false; + + while (!m_openList->empty()) + { + // Remove node from open list and put it in closed list. + dtNode* bestNode = m_openList->pop(); + bestNode->flags &= ~DT_NODE_OPEN; + bestNode->flags |= DT_NODE_CLOSED; + + // Reached the goal, stop searching. + if (bestNode->id == endRef) + { + lastBestNode = bestNode; + break; + } + + // Get current poly and tile. + // The API input has been checked already, skip checking internal data. + const dtPolyRef bestRef = bestNode->id; + const dtMeshTile* bestTile = 0; + const dtPoly* bestPoly = 0; + m_nav->getTileAndPolyByRefUnsafe(bestRef, &bestTile, &bestPoly); + + // Get parent poly and tile. + dtPolyRef parentRef = 0; + const dtMeshTile* parentTile = 0; + const dtPoly* parentPoly = 0; + if (bestNode->pidx) + parentRef = m_nodePool->getNodeAtIdx(bestNode->pidx)->id; + if (parentRef) + m_nav->getTileAndPolyByRefUnsafe(parentRef, &parentTile, &parentPoly); + + for (unsigned int i = bestPoly->firstLink; i != DT_NULL_LINK; i = bestTile->links[i].next) + { + dtPolyRef neighbourRef = bestTile->links[i].ref; + + // Skip invalid ids and do not expand back to where we came from. + if (!neighbourRef || neighbourRef == parentRef) + continue; + + // Get neighbour poly and tile. + // The API input has been checked already, skip checking internal data. + const dtMeshTile* neighbourTile = 0; + const dtPoly* neighbourPoly = 0; + m_nav->getTileAndPolyByRefUnsafe(neighbourRef, &neighbourTile, &neighbourPoly); + + if (!filter->passFilter(neighbourRef, neighbourTile, neighbourPoly)) + continue; + + // deal explicitly with crossing tile boundaries + unsigned char crossSide = 0; + if (bestTile->links[i].side != 0xff) + crossSide = bestTile->links[i].side >> 1; + + // get the node + dtNode* neighbourNode = m_nodePool->getNode(neighbourRef, crossSide); + if (!neighbourNode) + { + outOfNodes = true; + continue; + } + + // If the node is visited the first time, calculate node position. + if (neighbourNode->flags == 0) + { + getEdgeMidPoint(bestRef, bestPoly, bestTile, + neighbourRef, neighbourPoly, neighbourTile, + neighbourNode->pos); + } + + // Calculate cost and heuristic. + float cost = 0; + float heuristic = 0; + + // Special case for last node. + if (neighbourRef == endRef) + { + // Cost + const float curCost = filter->getCost(bestNode->pos, neighbourNode->pos, + parentRef, parentTile, parentPoly, + bestRef, bestTile, bestPoly, + neighbourRef, neighbourTile, neighbourPoly); + const float endCost = filter->getCost(neighbourNode->pos, endPos, + bestRef, bestTile, bestPoly, + neighbourRef, neighbourTile, neighbourPoly, + 0, 0, 0); + + cost = bestNode->cost + curCost + endCost; + heuristic = 0; + } + else + { + // Cost + const float curCost = filter->getCost(bestNode->pos, neighbourNode->pos, + parentRef, parentTile, parentPoly, + bestRef, bestTile, bestPoly, + neighbourRef, neighbourTile, neighbourPoly); + cost = bestNode->cost + curCost; + heuristic = dtVdist(neighbourNode->pos, endPos)*H_SCALE; + } + + const float total = cost + heuristic; + + // The node is already in open list and the new result is worse, skip. + if ((neighbourNode->flags & DT_NODE_OPEN) && total >= neighbourNode->total) + continue; + // The node is already visited and process, and the new result is worse, skip. + if ((neighbourNode->flags & DT_NODE_CLOSED) && total >= neighbourNode->total) + continue; + + // Add or update the node. + neighbourNode->pidx = m_nodePool->getNodeIdx(bestNode); + neighbourNode->id = neighbourRef; + neighbourNode->flags = (neighbourNode->flags & ~DT_NODE_CLOSED); + neighbourNode->cost = cost; + neighbourNode->total = total; + + if (neighbourNode->flags & DT_NODE_OPEN) + { + // Already in open, update node location. + m_openList->modify(neighbourNode); + } + else + { + // Put the node in open list. + neighbourNode->flags |= DT_NODE_OPEN; + m_openList->push(neighbourNode); + } + + // Update nearest node to target so far. + if (heuristic < lastBestNodeCost) + { + lastBestNodeCost = heuristic; + lastBestNode = neighbourNode; + } + } + } + + dtStatus status = getPathToNode(lastBestNode, path, pathCount, maxPath); + + if (lastBestNode->id != endRef) + status |= DT_PARTIAL_RESULT; + + if (outOfNodes) + status |= DT_OUT_OF_NODES; + + return status; +} + +dtStatus dtNavMeshQuery::getPathToNode(dtNode* endNode, dtPolyRef* path, int* pathCount, int maxPath) const +{ + // Find the length of the entire path. + dtNode* curNode = endNode; + int length = 0; + do + { + length++; + curNode = m_nodePool->getNodeAtIdx(curNode->pidx); + } while (curNode); + + // If the path cannot be fully stored then advance to the last node we will be able to store. + curNode = endNode; + int writeCount; + for (writeCount = length; writeCount > maxPath; writeCount--) + { + dtAssert(curNode); + + curNode = m_nodePool->getNodeAtIdx(curNode->pidx); + } + + // Write path + for (int i = writeCount - 1; i >= 0; i--) + { + dtAssert(curNode); + + path[i] = curNode->id; + curNode = m_nodePool->getNodeAtIdx(curNode->pidx); + } + + dtAssert(!curNode); + + *pathCount = dtMin(length, maxPath); + + if (length > maxPath) + return DT_SUCCESS | DT_BUFFER_TOO_SMALL; + + return DT_SUCCESS; +} + + +/// @par +/// +/// @warning Calling any non-slice methods before calling finalizeSlicedFindPath() +/// or finalizeSlicedFindPathPartial() may result in corrupted data! +/// +/// The @p filter pointer is stored and used for the duration of the sliced +/// path query. +/// +dtStatus dtNavMeshQuery::initSlicedFindPath(dtPolyRef startRef, dtPolyRef endRef, + const float* startPos, const float* endPos, + const dtQueryFilter* filter, const unsigned int options) +{ + dtAssert(m_nav); + dtAssert(m_nodePool); + dtAssert(m_openList); + + // Init path state. + memset(&m_query, 0, sizeof(dtQueryData)); + m_query.status = DT_FAILURE; + m_query.startRef = startRef; + m_query.endRef = endRef; + if (startPos) + dtVcopy(m_query.startPos, startPos); + if (endPos) + dtVcopy(m_query.endPos, endPos); + m_query.filter = filter; + m_query.options = options; + m_query.raycastLimitSqr = FLT_MAX; + + // Validate input + if (!m_nav->isValidPolyRef(startRef) || !m_nav->isValidPolyRef(endRef) || + !startPos || !dtVisfinite(startPos) || + !endPos || !dtVisfinite(endPos) || !filter) + { + return DT_FAILURE | DT_INVALID_PARAM; + } + + // trade quality with performance? + if (options & DT_FINDPATH_ANY_ANGLE) + { + // limiting to several times the character radius yields nice results. It is not sensitive + // so it is enough to compute it from the first tile. + const dtMeshTile* tile = m_nav->getTileByRef(startRef); + float agentRadius = tile->header->walkableRadius; + m_query.raycastLimitSqr = dtSqr(agentRadius * DT_RAY_CAST_LIMIT_PROPORTIONS); + } + + if (startRef == endRef) + { + m_query.status = DT_SUCCESS; + return DT_SUCCESS; + } + + m_nodePool->clear(); + m_openList->clear(); + + dtNode* startNode = m_nodePool->getNode(startRef); + dtVcopy(startNode->pos, startPos); + startNode->pidx = 0; + startNode->cost = 0; + startNode->total = dtVdist(startPos, endPos) * H_SCALE; + startNode->id = startRef; + startNode->flags = DT_NODE_OPEN; + m_openList->push(startNode); + + m_query.status = DT_IN_PROGRESS; + m_query.lastBestNode = startNode; + m_query.lastBestNodeCost = startNode->total; + + return m_query.status; +} + +dtStatus dtNavMeshQuery::updateSlicedFindPath(const int maxIter, int* doneIters) +{ + if (!dtStatusInProgress(m_query.status)) + return m_query.status; + + // Make sure the request is still valid. + if (!m_nav->isValidPolyRef(m_query.startRef) || !m_nav->isValidPolyRef(m_query.endRef)) + { + m_query.status = DT_FAILURE; + return DT_FAILURE; + } + + dtRaycastHit rayHit; + rayHit.maxPath = 0; + + int iter = 0; + while (iter < maxIter && !m_openList->empty()) + { + iter++; + + // Remove node from open list and put it in closed list. + dtNode* bestNode = m_openList->pop(); + bestNode->flags &= ~DT_NODE_OPEN; + bestNode->flags |= DT_NODE_CLOSED; + + // Reached the goal, stop searching. + if (bestNode->id == m_query.endRef) + { + m_query.lastBestNode = bestNode; + const dtStatus details = m_query.status & DT_STATUS_DETAIL_MASK; + m_query.status = DT_SUCCESS | details; + if (doneIters) + *doneIters = iter; + return m_query.status; + } + + // Get current poly and tile. + // The API input has been checked already, skip checking internal data. + const dtPolyRef bestRef = bestNode->id; + const dtMeshTile* bestTile = 0; + const dtPoly* bestPoly = 0; + if (dtStatusFailed(m_nav->getTileAndPolyByRef(bestRef, &bestTile, &bestPoly))) + { + // The polygon has disappeared during the sliced query, fail. + m_query.status = DT_FAILURE; + if (doneIters) + *doneIters = iter; + return m_query.status; + } + + // Get parent and grand parent poly and tile. + dtPolyRef parentRef = 0, grandpaRef = 0; + const dtMeshTile* parentTile = 0; + const dtPoly* parentPoly = 0; + dtNode* parentNode = 0; + if (bestNode->pidx) + { + parentNode = m_nodePool->getNodeAtIdx(bestNode->pidx); + parentRef = parentNode->id; + if (parentNode->pidx) + grandpaRef = m_nodePool->getNodeAtIdx(parentNode->pidx)->id; + } + if (parentRef) + { + bool invalidParent = dtStatusFailed(m_nav->getTileAndPolyByRef(parentRef, &parentTile, &parentPoly)); + if (invalidParent || (grandpaRef && !m_nav->isValidPolyRef(grandpaRef)) ) + { + // The polygon has disappeared during the sliced query, fail. + m_query.status = DT_FAILURE; + if (doneIters) + *doneIters = iter; + return m_query.status; + } + } + + // decide whether to test raycast to previous nodes + bool tryLOS = false; + if (m_query.options & DT_FINDPATH_ANY_ANGLE) + { + if ((parentRef != 0) && (dtVdistSqr(parentNode->pos, bestNode->pos) < m_query.raycastLimitSqr)) + tryLOS = true; + } + + for (unsigned int i = bestPoly->firstLink; i != DT_NULL_LINK; i = bestTile->links[i].next) + { + dtPolyRef neighbourRef = bestTile->links[i].ref; + + // Skip invalid ids and do not expand back to where we came from. + if (!neighbourRef || neighbourRef == parentRef) + continue; + + // Get neighbour poly and tile. + // The API input has been checked already, skip checking internal data. + const dtMeshTile* neighbourTile = 0; + const dtPoly* neighbourPoly = 0; + m_nav->getTileAndPolyByRefUnsafe(neighbourRef, &neighbourTile, &neighbourPoly); + + if (!m_query.filter->passFilter(neighbourRef, neighbourTile, neighbourPoly)) + continue; + + // get the neighbor node + dtNode* neighbourNode = m_nodePool->getNode(neighbourRef, 0); + if (!neighbourNode) + { + m_query.status |= DT_OUT_OF_NODES; + continue; + } + + // do not expand to nodes that were already visited from the same parent + if (neighbourNode->pidx != 0 && neighbourNode->pidx == bestNode->pidx) + continue; + + // If the node is visited the first time, calculate node position. + if (neighbourNode->flags == 0) + { + getEdgeMidPoint(bestRef, bestPoly, bestTile, + neighbourRef, neighbourPoly, neighbourTile, + neighbourNode->pos); + } + + // Calculate cost and heuristic. + float cost = 0; + float heuristic = 0; + + // raycast parent + bool foundShortCut = false; + rayHit.pathCost = rayHit.t = 0; + if (tryLOS) + { + raycast(parentRef, parentNode->pos, neighbourNode->pos, m_query.filter, DT_RAYCAST_USE_COSTS, &rayHit, grandpaRef); + foundShortCut = rayHit.t >= 1.0f; + } + + // update move cost + if (foundShortCut) + { + // shortcut found using raycast. Using shorter cost instead + cost = parentNode->cost + rayHit.pathCost; + } + else + { + // No shortcut found. + const float curCost = m_query.filter->getCost(bestNode->pos, neighbourNode->pos, + parentRef, parentTile, parentPoly, + bestRef, bestTile, bestPoly, + neighbourRef, neighbourTile, neighbourPoly); + cost = bestNode->cost + curCost; + } + + // Special case for last node. + if (neighbourRef == m_query.endRef) + { + const float endCost = m_query.filter->getCost(neighbourNode->pos, m_query.endPos, + bestRef, bestTile, bestPoly, + neighbourRef, neighbourTile, neighbourPoly, + 0, 0, 0); + + cost = cost + endCost; + heuristic = 0; + } + else + { + heuristic = dtVdist(neighbourNode->pos, m_query.endPos)*H_SCALE; + } + + const float total = cost + heuristic; + + // The node is already in open list and the new result is worse, skip. + if ((neighbourNode->flags & DT_NODE_OPEN) && total >= neighbourNode->total) + continue; + // The node is already visited and process, and the new result is worse, skip. + if ((neighbourNode->flags & DT_NODE_CLOSED) && total >= neighbourNode->total) + continue; + + // Add or update the node. + neighbourNode->pidx = foundShortCut ? bestNode->pidx : m_nodePool->getNodeIdx(bestNode); + neighbourNode->id = neighbourRef; + neighbourNode->flags = (neighbourNode->flags & ~(DT_NODE_CLOSED | DT_NODE_PARENT_DETACHED)); + neighbourNode->cost = cost; + neighbourNode->total = total; + if (foundShortCut) + neighbourNode->flags = (neighbourNode->flags | DT_NODE_PARENT_DETACHED); + + if (neighbourNode->flags & DT_NODE_OPEN) + { + // Already in open, update node location. + m_openList->modify(neighbourNode); + } + else + { + // Put the node in open list. + neighbourNode->flags |= DT_NODE_OPEN; + m_openList->push(neighbourNode); + } + + // Update nearest node to target so far. + if (heuristic < m_query.lastBestNodeCost) + { + m_query.lastBestNodeCost = heuristic; + m_query.lastBestNode = neighbourNode; + } + } + } + + // Exhausted all nodes, but could not find path. + if (m_openList->empty()) + { + const dtStatus details = m_query.status & DT_STATUS_DETAIL_MASK; + m_query.status = DT_SUCCESS | details; + } + + if (doneIters) + *doneIters = iter; + + return m_query.status; +} + +dtStatus dtNavMeshQuery::finalizeSlicedFindPath(dtPolyRef* path, int* pathCount, const int maxPath) +{ + if (!pathCount) + return DT_FAILURE | DT_INVALID_PARAM; + + *pathCount = 0; + + if (!path || maxPath <= 0) + return DT_FAILURE | DT_INVALID_PARAM; + + if (dtStatusFailed(m_query.status)) + { + // Reset query. + memset(&m_query, 0, sizeof(dtQueryData)); + return DT_FAILURE; + } + + int n = 0; + + if (m_query.startRef == m_query.endRef) + { + // Special case: the search starts and ends at same poly. + path[n++] = m_query.startRef; + } + else + { + // Reverse the path. + dtAssert(m_query.lastBestNode); + + if (m_query.lastBestNode->id != m_query.endRef) + m_query.status |= DT_PARTIAL_RESULT; + + dtNode* prev = 0; + dtNode* node = m_query.lastBestNode; + int prevRay = 0; + do + { + dtNode* next = m_nodePool->getNodeAtIdx(node->pidx); + node->pidx = m_nodePool->getNodeIdx(prev); + prev = node; + int nextRay = node->flags & DT_NODE_PARENT_DETACHED; // keep track of whether parent is not adjacent (i.e. due to raycast shortcut) + node->flags = (node->flags & ~DT_NODE_PARENT_DETACHED) | prevRay; // and store it in the reversed path's node + prevRay = nextRay; + node = next; + } + while (node); + + // Store path + node = prev; + do + { + dtNode* next = m_nodePool->getNodeAtIdx(node->pidx); + dtStatus status = 0; + if (node->flags & DT_NODE_PARENT_DETACHED) + { + float t, normal[3]; + int m; + status = raycast(node->id, node->pos, next->pos, m_query.filter, &t, normal, path+n, &m, maxPath-n); + n += m; + // raycast ends on poly boundary and the path might include the next poly boundary. + if (path[n-1] == next->id) + n--; // remove to avoid duplicates + } + else + { + path[n++] = node->id; + if (n >= maxPath) + status = DT_BUFFER_TOO_SMALL; + } + + if (status & DT_STATUS_DETAIL_MASK) + { + m_query.status |= status & DT_STATUS_DETAIL_MASK; + break; + } + node = next; + } + while (node); + } + + const dtStatus details = m_query.status & DT_STATUS_DETAIL_MASK; + + // Reset query. + memset(&m_query, 0, sizeof(dtQueryData)); + + *pathCount = n; + + return DT_SUCCESS | details; +} + +dtStatus dtNavMeshQuery::finalizeSlicedFindPathPartial(const dtPolyRef* existing, const int existingSize, + dtPolyRef* path, int* pathCount, const int maxPath) +{ + if (!pathCount) + return DT_FAILURE | DT_INVALID_PARAM; + + *pathCount = 0; + + if (!existing || existingSize <= 0 || !path || !pathCount || maxPath <= 0) + return DT_FAILURE | DT_INVALID_PARAM; + + if (dtStatusFailed(m_query.status)) + { + // Reset query. + memset(&m_query, 0, sizeof(dtQueryData)); + return DT_FAILURE; + } + + int n = 0; + + if (m_query.startRef == m_query.endRef) + { + // Special case: the search starts and ends at same poly. + path[n++] = m_query.startRef; + } + else + { + // Find furthest existing node that was visited. + dtNode* prev = 0; + dtNode* node = 0; + for (int i = existingSize-1; i >= 0; --i) + { + m_nodePool->findNodes(existing[i], &node, 1); + if (node) + break; + } + + if (!node) + { + m_query.status |= DT_PARTIAL_RESULT; + dtAssert(m_query.lastBestNode); + node = m_query.lastBestNode; + } + + // Reverse the path. + int prevRay = 0; + do + { + dtNode* next = m_nodePool->getNodeAtIdx(node->pidx); + node->pidx = m_nodePool->getNodeIdx(prev); + prev = node; + int nextRay = node->flags & DT_NODE_PARENT_DETACHED; // keep track of whether parent is not adjacent (i.e. due to raycast shortcut) + node->flags = (node->flags & ~DT_NODE_PARENT_DETACHED) | prevRay; // and store it in the reversed path's node + prevRay = nextRay; + node = next; + } + while (node); + + // Store path + node = prev; + do + { + dtNode* next = m_nodePool->getNodeAtIdx(node->pidx); + dtStatus status = 0; + if (node->flags & DT_NODE_PARENT_DETACHED) + { + float t, normal[3]; + int m; + status = raycast(node->id, node->pos, next->pos, m_query.filter, &t, normal, path+n, &m, maxPath-n); + n += m; + // raycast ends on poly boundary and the path might include the next poly boundary. + if (path[n-1] == next->id) + n--; // remove to avoid duplicates + } + else + { + path[n++] = node->id; + if (n >= maxPath) + status = DT_BUFFER_TOO_SMALL; + } + + if (status & DT_STATUS_DETAIL_MASK) + { + m_query.status |= status & DT_STATUS_DETAIL_MASK; + break; + } + node = next; + } + while (node); + } + + const dtStatus details = m_query.status & DT_STATUS_DETAIL_MASK; + + // Reset query. + memset(&m_query, 0, sizeof(dtQueryData)); + + *pathCount = n; + + return DT_SUCCESS | details; +} + + +dtStatus dtNavMeshQuery::appendVertex(const float* pos, const unsigned char flags, const dtPolyRef ref, + float* straightPath, unsigned char* straightPathFlags, dtPolyRef* straightPathRefs, + int* straightPathCount, const int maxStraightPath) const +{ + if ((*straightPathCount) > 0 && dtVequal(&straightPath[((*straightPathCount)-1)*3], pos)) + { + // The vertices are equal, update flags and poly. + if (straightPathFlags) + straightPathFlags[(*straightPathCount)-1] = flags; + if (straightPathRefs) + straightPathRefs[(*straightPathCount)-1] = ref; + } + else + { + // Append new vertex. + dtVcopy(&straightPath[(*straightPathCount)*3], pos); + if (straightPathFlags) + straightPathFlags[(*straightPathCount)] = flags; + if (straightPathRefs) + straightPathRefs[(*straightPathCount)] = ref; + (*straightPathCount)++; + + // If there is no space to append more vertices, return. + if ((*straightPathCount) >= maxStraightPath) + { + return DT_SUCCESS | DT_BUFFER_TOO_SMALL; + } + + // If reached end of path, return. + if (flags == DT_STRAIGHTPATH_END) + { + return DT_SUCCESS; + } + } + return DT_IN_PROGRESS; +} + +dtStatus dtNavMeshQuery::appendPortals(const int startIdx, const int endIdx, const float* endPos, const dtPolyRef* path, + float* straightPath, unsigned char* straightPathFlags, dtPolyRef* straightPathRefs, + int* straightPathCount, const int maxStraightPath, const int options) const +{ + const float* startPos = &straightPath[(*straightPathCount-1)*3]; + // Append or update last vertex + dtStatus stat = 0; + for (int i = startIdx; i < endIdx; i++) + { + // Calculate portal + const dtPolyRef from = path[i]; + const dtMeshTile* fromTile = 0; + const dtPoly* fromPoly = 0; + if (dtStatusFailed(m_nav->getTileAndPolyByRef(from, &fromTile, &fromPoly))) + return DT_FAILURE | DT_INVALID_PARAM; + + const dtPolyRef to = path[i+1]; + const dtMeshTile* toTile = 0; + const dtPoly* toPoly = 0; + if (dtStatusFailed(m_nav->getTileAndPolyByRef(to, &toTile, &toPoly))) + return DT_FAILURE | DT_INVALID_PARAM; + + float left[3], right[3]; + if (dtStatusFailed(getPortalPoints(from, fromPoly, fromTile, to, toPoly, toTile, left, right))) + break; + + if (options & DT_STRAIGHTPATH_AREA_CROSSINGS) + { + // Skip intersection if only area crossings are requested. + if (fromPoly->getArea() == toPoly->getArea()) + continue; + } + + // Append intersection + float s,t; + if (dtIntersectSegSeg2D(startPos, endPos, left, right, s, t)) + { + float pt[3]; + dtVlerp(pt, left,right, t); + + stat = appendVertex(pt, 0, path[i+1], + straightPath, straightPathFlags, straightPathRefs, + straightPathCount, maxStraightPath); + if (stat != DT_IN_PROGRESS) + return stat; + } + } + return DT_IN_PROGRESS; +} + +/// @par +/// +/// This method peforms what is often called 'string pulling'. +/// +/// The start position is clamped to the first polygon in the path, and the +/// end position is clamped to the last. So the start and end positions should +/// normally be within or very near the first and last polygons respectively. +/// +/// The returned polygon references represent the reference id of the polygon +/// that is entered at the associated path position. The reference id associated +/// with the end point will always be zero. This allows, for example, matching +/// off-mesh link points to their representative polygons. +/// +/// If the provided result buffers are too small for the entire result set, +/// they will be filled as far as possible from the start toward the end +/// position. +/// +dtStatus dtNavMeshQuery::findStraightPath(const float* startPos, const float* endPos, + const dtPolyRef* path, const int pathSize, + float* straightPath, unsigned char* straightPathFlags, dtPolyRef* straightPathRefs, + int* straightPathCount, const int maxStraightPath, const int options) const +{ + dtAssert(m_nav); + + if (!straightPathCount) + return DT_FAILURE | DT_INVALID_PARAM; + + *straightPathCount = 0; + + if (!startPos || !dtVisfinite(startPos) || + !endPos || !dtVisfinite(endPos) || + !path || pathSize <= 0 || !path[0] || + maxStraightPath <= 0) + { + return DT_FAILURE | DT_INVALID_PARAM; + } + + dtStatus stat = 0; + + // TODO: Should this be callers responsibility? + float closestStartPos[3]; + if (dtStatusFailed(closestPointOnPolyBoundary(path[0], startPos, closestStartPos))) + return DT_FAILURE | DT_INVALID_PARAM; + + float closestEndPos[3]; + if (dtStatusFailed(closestPointOnPolyBoundary(path[pathSize-1], endPos, closestEndPos))) + return DT_FAILURE | DT_INVALID_PARAM; + + // Add start point. + stat = appendVertex(closestStartPos, DT_STRAIGHTPATH_START, path[0], + straightPath, straightPathFlags, straightPathRefs, + straightPathCount, maxStraightPath); + if (stat != DT_IN_PROGRESS) + return stat; + + if (pathSize > 1) + { + float portalApex[3], portalLeft[3], portalRight[3]; + dtVcopy(portalApex, closestStartPos); + dtVcopy(portalLeft, portalApex); + dtVcopy(portalRight, portalApex); + int apexIndex = 0; + int leftIndex = 0; + int rightIndex = 0; + + unsigned char leftPolyType = 0; + unsigned char rightPolyType = 0; + + dtPolyRef leftPolyRef = path[0]; + dtPolyRef rightPolyRef = path[0]; + + for (int i = 0; i < pathSize; ++i) + { + float left[3], right[3]; + unsigned char toType; + + if (i+1 < pathSize) + { + unsigned char fromType; // fromType is ignored. + + // Next portal. + if (dtStatusFailed(getPortalPoints(path[i], path[i+1], left, right, fromType, toType))) + { + // Failed to get portal points, in practice this means that path[i+1] is invalid polygon. + // Clamp the end point to path[i], and return the path so far. + + if (dtStatusFailed(closestPointOnPolyBoundary(path[i], endPos, closestEndPos))) + { + // This should only happen when the first polygon is invalid. + return DT_FAILURE | DT_INVALID_PARAM; + } + + // Apeend portals along the current straight path segment. + if (options & (DT_STRAIGHTPATH_AREA_CROSSINGS | DT_STRAIGHTPATH_ALL_CROSSINGS)) + { + // Ignore status return value as we're just about to return anyway. + appendPortals(apexIndex, i, closestEndPos, path, + straightPath, straightPathFlags, straightPathRefs, + straightPathCount, maxStraightPath, options); + } + + // Ignore status return value as we're just about to return anyway. + appendVertex(closestEndPos, 0, path[i], + straightPath, straightPathFlags, straightPathRefs, + straightPathCount, maxStraightPath); + + return DT_SUCCESS | DT_PARTIAL_RESULT | ((*straightPathCount >= maxStraightPath) ? DT_BUFFER_TOO_SMALL : 0); + } + + // If starting really close the portal, advance. + if (i == 0) + { + float t; + if (dtDistancePtSegSqr2D(portalApex, left, right, t) < dtSqr(0.001f)) + continue; + } + } + else + { + // End of the path. + dtVcopy(left, closestEndPos); + dtVcopy(right, closestEndPos); + + toType = DT_POLYTYPE_GROUND; + } + + // Right vertex. + if (dtTriArea2D(portalApex, portalRight, right) <= 0.0f) + { + if (dtVequal(portalApex, portalRight) || dtTriArea2D(portalApex, portalLeft, right) > 0.0f) + { + dtVcopy(portalRight, right); + rightPolyRef = (i+1 < pathSize) ? path[i+1] : 0; + rightPolyType = toType; + rightIndex = i; + } + else + { + // Append portals along the current straight path segment. + if (options & (DT_STRAIGHTPATH_AREA_CROSSINGS | DT_STRAIGHTPATH_ALL_CROSSINGS)) + { + stat = appendPortals(apexIndex, leftIndex, portalLeft, path, + straightPath, straightPathFlags, straightPathRefs, + straightPathCount, maxStraightPath, options); + if (stat != DT_IN_PROGRESS) + return stat; + } + + dtVcopy(portalApex, portalLeft); + apexIndex = leftIndex; + + unsigned char flags = 0; + if (!leftPolyRef) + flags = DT_STRAIGHTPATH_END; + else if (leftPolyType == DT_POLYTYPE_OFFMESH_CONNECTION) + flags = DT_STRAIGHTPATH_OFFMESH_CONNECTION; + dtPolyRef ref = leftPolyRef; + + // Append or update vertex + stat = appendVertex(portalApex, flags, ref, + straightPath, straightPathFlags, straightPathRefs, + straightPathCount, maxStraightPath); + if (stat != DT_IN_PROGRESS) + return stat; + + dtVcopy(portalLeft, portalApex); + dtVcopy(portalRight, portalApex); + leftIndex = apexIndex; + rightIndex = apexIndex; + + // Restart + i = apexIndex; + + continue; + } + } + + // Left vertex. + if (dtTriArea2D(portalApex, portalLeft, left) >= 0.0f) + { + if (dtVequal(portalApex, portalLeft) || dtTriArea2D(portalApex, portalRight, left) < 0.0f) + { + dtVcopy(portalLeft, left); + leftPolyRef = (i+1 < pathSize) ? path[i+1] : 0; + leftPolyType = toType; + leftIndex = i; + } + else + { + // Append portals along the current straight path segment. + if (options & (DT_STRAIGHTPATH_AREA_CROSSINGS | DT_STRAIGHTPATH_ALL_CROSSINGS)) + { + stat = appendPortals(apexIndex, rightIndex, portalRight, path, + straightPath, straightPathFlags, straightPathRefs, + straightPathCount, maxStraightPath, options); + if (stat != DT_IN_PROGRESS) + return stat; + } + + dtVcopy(portalApex, portalRight); + apexIndex = rightIndex; + + unsigned char flags = 0; + if (!rightPolyRef) + flags = DT_STRAIGHTPATH_END; + else if (rightPolyType == DT_POLYTYPE_OFFMESH_CONNECTION) + flags = DT_STRAIGHTPATH_OFFMESH_CONNECTION; + dtPolyRef ref = rightPolyRef; + + // Append or update vertex + stat = appendVertex(portalApex, flags, ref, + straightPath, straightPathFlags, straightPathRefs, + straightPathCount, maxStraightPath); + if (stat != DT_IN_PROGRESS) + return stat; + + dtVcopy(portalLeft, portalApex); + dtVcopy(portalRight, portalApex); + leftIndex = apexIndex; + rightIndex = apexIndex; + + // Restart + i = apexIndex; + + continue; + } + } + } + + // Append portals along the current straight path segment. + if (options & (DT_STRAIGHTPATH_AREA_CROSSINGS | DT_STRAIGHTPATH_ALL_CROSSINGS)) + { + stat = appendPortals(apexIndex, pathSize-1, closestEndPos, path, + straightPath, straightPathFlags, straightPathRefs, + straightPathCount, maxStraightPath, options); + if (stat != DT_IN_PROGRESS) + return stat; + } + } + + // Ignore status return value as we're just about to return anyway. + appendVertex(closestEndPos, DT_STRAIGHTPATH_END, 0, + straightPath, straightPathFlags, straightPathRefs, + straightPathCount, maxStraightPath); + + return DT_SUCCESS | ((*straightPathCount >= maxStraightPath) ? DT_BUFFER_TOO_SMALL : 0); +} + +/// @par +/// +/// This method is optimized for small delta movement and a small number of +/// polygons. If used for too great a distance, the result set will form an +/// incomplete path. +/// +/// @p resultPos will equal the @p endPos if the end is reached. +/// Otherwise the closest reachable position will be returned. +/// +/// @p resultPos is not projected onto the surface of the navigation +/// mesh. Use #getPolyHeight if this is needed. +/// +/// This method treats the end position in the same manner as +/// the #raycast method. (As a 2D point.) See that method's documentation +/// for details. +/// +/// If the @p visited array is too small to hold the entire result set, it will +/// be filled as far as possible from the start position toward the end +/// position. +/// +dtStatus dtNavMeshQuery::moveAlongSurface(dtPolyRef startRef, const float* startPos, const float* endPos, + const dtQueryFilter* filter, + float* resultPos, dtPolyRef* visited, int* visitedCount, const int maxVisitedSize) const +{ + dtAssert(m_nav); + dtAssert(m_tinyNodePool); + + if (!visitedCount) + return DT_FAILURE | DT_INVALID_PARAM; + + *visitedCount = 0; + + if (!m_nav->isValidPolyRef(startRef) || + !startPos || !dtVisfinite(startPos) || + !endPos || !dtVisfinite(endPos) || + !filter || !resultPos || !visited || + maxVisitedSize <= 0) + { + return DT_FAILURE | DT_INVALID_PARAM; + } + + dtStatus status = DT_SUCCESS; + + static const int MAX_STACK = 48; + dtNode* stack[MAX_STACK]; + int nstack = 0; + + m_tinyNodePool->clear(); + + dtNode* startNode = m_tinyNodePool->getNode(startRef); + startNode->pidx = 0; + startNode->cost = 0; + startNode->total = 0; + startNode->id = startRef; + startNode->flags = DT_NODE_CLOSED; + stack[nstack++] = startNode; + + float bestPos[3]; + float bestDist = FLT_MAX; + dtNode* bestNode = 0; + dtVcopy(bestPos, startPos); + + // Search constraints + float searchPos[3], searchRadSqr; + dtVlerp(searchPos, startPos, endPos, 0.5f); + searchRadSqr = dtSqr(dtVdist(startPos, endPos)/2.0f + 0.001f); + + float verts[DT_VERTS_PER_POLYGON*3]; + + while (nstack) + { + // Pop front. + dtNode* curNode = stack[0]; + for (int i = 0; i < nstack-1; ++i) + stack[i] = stack[i+1]; + nstack--; + + // Get poly and tile. + // The API input has been checked already, skip checking internal data. + const dtPolyRef curRef = curNode->id; + const dtMeshTile* curTile = 0; + const dtPoly* curPoly = 0; + m_nav->getTileAndPolyByRefUnsafe(curRef, &curTile, &curPoly); + + // Collect vertices. + const int nverts = curPoly->vertCount; + for (int i = 0; i < nverts; ++i) + dtVcopy(&verts[i*3], &curTile->verts[curPoly->verts[i]*3]); + + // If target is inside the poly, stop search. + if (dtPointInPolygon(endPos, verts, nverts)) + { + bestNode = curNode; + dtVcopy(bestPos, endPos); + break; + } + + // Find wall edges and find nearest point inside the walls. + for (int i = 0, j = (int)curPoly->vertCount-1; i < (int)curPoly->vertCount; j = i++) + { + // Find links to neighbours. + static const int MAX_NEIS = 8; + int nneis = 0; + dtPolyRef neis[MAX_NEIS]; + + if (curPoly->neis[j] & DT_EXT_LINK) + { + // Tile border. + for (unsigned int k = curPoly->firstLink; k != DT_NULL_LINK; k = curTile->links[k].next) + { + const dtLink* link = &curTile->links[k]; + if (link->edge == j) + { + if (link->ref != 0) + { + const dtMeshTile* neiTile = 0; + const dtPoly* neiPoly = 0; + m_nav->getTileAndPolyByRefUnsafe(link->ref, &neiTile, &neiPoly); + if (filter->passFilter(link->ref, neiTile, neiPoly)) + { + if (nneis < MAX_NEIS) + neis[nneis++] = link->ref; + } + } + } + } + } + else if (curPoly->neis[j]) + { + const unsigned int idx = (unsigned int)(curPoly->neis[j]-1); + const dtPolyRef ref = m_nav->getPolyRefBase(curTile) | idx; + if (filter->passFilter(ref, curTile, &curTile->polys[idx])) + { + // Internal edge, encode id. + neis[nneis++] = ref; + } + } + + if (!nneis) + { + // Wall edge, calc distance. + const float* vj = &verts[j*3]; + const float* vi = &verts[i*3]; + float tseg; + const float distSqr = dtDistancePtSegSqr2D(endPos, vj, vi, tseg); + if (distSqr < bestDist) + { + // Update nearest distance. + dtVlerp(bestPos, vj,vi, tseg); + bestDist = distSqr; + bestNode = curNode; + } + } + else + { + for (int k = 0; k < nneis; ++k) + { + // Skip if no node can be allocated. + dtNode* neighbourNode = m_tinyNodePool->getNode(neis[k]); + if (!neighbourNode) + continue; + // Skip if already visited. + if (neighbourNode->flags & DT_NODE_CLOSED) + continue; + + // Skip the link if it is too far from search constraint. + // TODO: Maybe should use getPortalPoints(), but this one is way faster. + const float* vj = &verts[j*3]; + const float* vi = &verts[i*3]; + float tseg; + float distSqr = dtDistancePtSegSqr2D(searchPos, vj, vi, tseg); + if (distSqr > searchRadSqr) + continue; + + // Mark as the node as visited and push to queue. + if (nstack < MAX_STACK) + { + neighbourNode->pidx = m_tinyNodePool->getNodeIdx(curNode); + neighbourNode->flags |= DT_NODE_CLOSED; + stack[nstack++] = neighbourNode; + } + } + } + } + } + + int n = 0; + if (bestNode) + { + // Reverse the path. + dtNode* prev = 0; + dtNode* node = bestNode; + do + { + dtNode* next = m_tinyNodePool->getNodeAtIdx(node->pidx); + node->pidx = m_tinyNodePool->getNodeIdx(prev); + prev = node; + node = next; + } + while (node); + + // Store result + node = prev; + do + { + visited[n++] = node->id; + if (n >= maxVisitedSize) + { + status |= DT_BUFFER_TOO_SMALL; + break; + } + node = m_tinyNodePool->getNodeAtIdx(node->pidx); + } + while (node); + } + + dtVcopy(resultPos, bestPos); + + *visitedCount = n; + + return status; +} + + +dtStatus dtNavMeshQuery::getPortalPoints(dtPolyRef from, dtPolyRef to, float* left, float* right, + unsigned char& fromType, unsigned char& toType) const +{ + dtAssert(m_nav); + + const dtMeshTile* fromTile = 0; + const dtPoly* fromPoly = 0; + if (dtStatusFailed(m_nav->getTileAndPolyByRef(from, &fromTile, &fromPoly))) + return DT_FAILURE | DT_INVALID_PARAM; + fromType = fromPoly->getType(); + + const dtMeshTile* toTile = 0; + const dtPoly* toPoly = 0; + if (dtStatusFailed(m_nav->getTileAndPolyByRef(to, &toTile, &toPoly))) + return DT_FAILURE | DT_INVALID_PARAM; + toType = toPoly->getType(); + + return getPortalPoints(from, fromPoly, fromTile, to, toPoly, toTile, left, right); +} + +// Returns portal points between two polygons. +dtStatus dtNavMeshQuery::getPortalPoints(dtPolyRef from, const dtPoly* fromPoly, const dtMeshTile* fromTile, + dtPolyRef to, const dtPoly* toPoly, const dtMeshTile* toTile, + float* left, float* right) const +{ + // Find the link that points to the 'to' polygon. + const dtLink* link = 0; + for (unsigned int i = fromPoly->firstLink; i != DT_NULL_LINK; i = fromTile->links[i].next) + { + if (fromTile->links[i].ref == to) + { + link = &fromTile->links[i]; + break; + } + } + if (!link) + return DT_FAILURE | DT_INVALID_PARAM; + + // Handle off-mesh connections. + if (fromPoly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION) + { + // Find link that points to first vertex. + for (unsigned int i = fromPoly->firstLink; i != DT_NULL_LINK; i = fromTile->links[i].next) + { + if (fromTile->links[i].ref == to) + { + const int v = fromTile->links[i].edge; + dtVcopy(left, &fromTile->verts[fromPoly->verts[v]*3]); + dtVcopy(right, &fromTile->verts[fromPoly->verts[v]*3]); + return DT_SUCCESS; + } + } + return DT_FAILURE | DT_INVALID_PARAM; + } + + if (toPoly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION) + { + for (unsigned int i = toPoly->firstLink; i != DT_NULL_LINK; i = toTile->links[i].next) + { + if (toTile->links[i].ref == from) + { + const int v = toTile->links[i].edge; + dtVcopy(left, &toTile->verts[toPoly->verts[v]*3]); + dtVcopy(right, &toTile->verts[toPoly->verts[v]*3]); + return DT_SUCCESS; + } + } + return DT_FAILURE | DT_INVALID_PARAM; + } + + // Find portal vertices. + const int v0 = fromPoly->verts[link->edge]; + const int v1 = fromPoly->verts[(link->edge+1) % (int)fromPoly->vertCount]; + dtVcopy(left, &fromTile->verts[v0*3]); + dtVcopy(right, &fromTile->verts[v1*3]); + + // If the link is at tile boundary, dtClamp the vertices to + // the link width. + if (link->side != 0xff) + { + // Unpack portal limits. + if (link->bmin != 0 || link->bmax != 255) + { + const float s = 1.0f/255.0f; + const float tmin = link->bmin*s; + const float tmax = link->bmax*s; + dtVlerp(left, &fromTile->verts[v0*3], &fromTile->verts[v1*3], tmin); + dtVlerp(right, &fromTile->verts[v0*3], &fromTile->verts[v1*3], tmax); + } + } + + return DT_SUCCESS; +} + +// Returns edge mid point between two polygons. +dtStatus dtNavMeshQuery::getEdgeMidPoint(dtPolyRef from, dtPolyRef to, float* mid) const +{ + float left[3], right[3]; + unsigned char fromType, toType; + if (dtStatusFailed(getPortalPoints(from, to, left,right, fromType, toType))) + return DT_FAILURE | DT_INVALID_PARAM; + mid[0] = (left[0]+right[0])*0.5f; + mid[1] = (left[1]+right[1])*0.5f; + mid[2] = (left[2]+right[2])*0.5f; + return DT_SUCCESS; +} + +dtStatus dtNavMeshQuery::getEdgeMidPoint(dtPolyRef from, const dtPoly* fromPoly, const dtMeshTile* fromTile, + dtPolyRef to, const dtPoly* toPoly, const dtMeshTile* toTile, + float* mid) const +{ + float left[3], right[3]; + if (dtStatusFailed(getPortalPoints(from, fromPoly, fromTile, to, toPoly, toTile, left, right))) + return DT_FAILURE | DT_INVALID_PARAM; + mid[0] = (left[0]+right[0])*0.5f; + mid[1] = (left[1]+right[1])*0.5f; + mid[2] = (left[2]+right[2])*0.5f; + return DT_SUCCESS; +} + + + +/// @par +/// +/// This method is meant to be used for quick, short distance checks. +/// +/// If the path array is too small to hold the result, it will be filled as +/// far as possible from the start postion toward the end position. +/// +/// Using the Hit Parameter (t) +/// +/// If the hit parameter is a very high value (FLT_MAX), then the ray has hit +/// the end position. In this case the path represents a valid corridor to the +/// end position and the value of @p hitNormal is undefined. +/// +/// If the hit parameter is zero, then the start position is on the wall that +/// was hit and the value of @p hitNormal is undefined. +/// +/// If 0 < t < 1.0 then the following applies: +/// +/// @code +/// distanceToHitBorder = distanceToEndPosition * t +/// hitPoint = startPos + (endPos - startPos) * t +/// @endcode +/// +/// Use Case Restriction +/// +/// The raycast ignores the y-value of the end position. (2D check.) This +/// places significant limits on how it can be used. For example: +/// +/// Consider a scene where there is a main floor with a second floor balcony +/// that hangs over the main floor. So the first floor mesh extends below the +/// balcony mesh. The start position is somewhere on the first floor. The end +/// position is on the balcony. +/// +/// The raycast will search toward the end position along the first floor mesh. +/// If it reaches the end position's xz-coordinates it will indicate FLT_MAX +/// (no wall hit), meaning it reached the end position. This is one example of why +/// this method is meant for short distance checks. +/// +dtStatus dtNavMeshQuery::raycast(dtPolyRef startRef, const float* startPos, const float* endPos, + const dtQueryFilter* filter, + float* t, float* hitNormal, dtPolyRef* path, int* pathCount, const int maxPath) const +{ + dtRaycastHit hit; + hit.path = path; + hit.maxPath = maxPath; + + dtStatus status = raycast(startRef, startPos, endPos, filter, 0, &hit); + + *t = hit.t; + if (hitNormal) + dtVcopy(hitNormal, hit.hitNormal); + if (pathCount) + *pathCount = hit.pathCount; + + return status; +} + + +/// @par +/// +/// This method is meant to be used for quick, short distance checks. +/// +/// If the path array is too small to hold the result, it will be filled as +/// far as possible from the start postion toward the end position. +/// +/// Using the Hit Parameter t of RaycastHit +/// +/// If the hit parameter is a very high value (FLT_MAX), then the ray has hit +/// the end position. In this case the path represents a valid corridor to the +/// end position and the value of @p hitNormal is undefined. +/// +/// If the hit parameter is zero, then the start position is on the wall that +/// was hit and the value of @p hitNormal is undefined. +/// +/// If 0 < t < 1.0 then the following applies: +/// +/// @code +/// distanceToHitBorder = distanceToEndPosition * t +/// hitPoint = startPos + (endPos - startPos) * t +/// @endcode +/// +/// Use Case Restriction +/// +/// The raycast ignores the y-value of the end position. (2D check.) This +/// places significant limits on how it can be used. For example: +/// +/// Consider a scene where there is a main floor with a second floor balcony +/// that hangs over the main floor. So the first floor mesh extends below the +/// balcony mesh. The start position is somewhere on the first floor. The end +/// position is on the balcony. +/// +/// The raycast will search toward the end position along the first floor mesh. +/// If it reaches the end position's xz-coordinates it will indicate FLT_MAX +/// (no wall hit), meaning it reached the end position. This is one example of why +/// this method is meant for short distance checks. +/// +dtStatus dtNavMeshQuery::raycast(dtPolyRef startRef, const float* startPos, const float* endPos, + const dtQueryFilter* filter, const unsigned int options, + dtRaycastHit* hit, dtPolyRef prevRef) const +{ + dtAssert(m_nav); + + if (!hit) + return DT_FAILURE | DT_INVALID_PARAM; + + hit->t = 0; + hit->pathCount = 0; + hit->pathCost = 0; + + // Validate input + if (!m_nav->isValidPolyRef(startRef) || + !startPos || !dtVisfinite(startPos) || + !endPos || !dtVisfinite(endPos) || + !filter || + (prevRef && !m_nav->isValidPolyRef(prevRef))) + { + return DT_FAILURE | DT_INVALID_PARAM; + } + + float dir[3], curPos[3], lastPos[3]; + float verts[DT_VERTS_PER_POLYGON*3+3]; + int n = 0; + + dtVcopy(curPos, startPos); + dtVsub(dir, endPos, startPos); + dtVset(hit->hitNormal, 0, 0, 0); + + dtStatus status = DT_SUCCESS; + + const dtMeshTile* prevTile, *tile, *nextTile; + const dtPoly* prevPoly, *poly, *nextPoly; + dtPolyRef curRef; + + // The API input has been checked already, skip checking internal data. + curRef = startRef; + tile = 0; + poly = 0; + m_nav->getTileAndPolyByRefUnsafe(curRef, &tile, &poly); + nextTile = prevTile = tile; + nextPoly = prevPoly = poly; + if (prevRef) + m_nav->getTileAndPolyByRefUnsafe(prevRef, &prevTile, &prevPoly); + + while (curRef) + { + // Cast ray against current polygon. + + // Collect vertices. + int nv = 0; + for (int i = 0; i < (int)poly->vertCount; ++i) + { + dtVcopy(&verts[nv*3], &tile->verts[poly->verts[i]*3]); + nv++; + } + + float tmin, tmax; + int segMin, segMax; + if (!dtIntersectSegmentPoly2D(startPos, endPos, verts, nv, tmin, tmax, segMin, segMax)) + { + // Could not hit the polygon, keep the old t and report hit. + hit->pathCount = n; + return status; + } + + hit->hitEdgeIndex = segMax; + + // Keep track of furthest t so far. + if (tmax > hit->t) + hit->t = tmax; + + // Store visited polygons. + if (n < hit->maxPath) + hit->path[n++] = curRef; + else + status |= DT_BUFFER_TOO_SMALL; + + // Ray end is completely inside the polygon. + if (segMax == -1) + { + hit->t = FLT_MAX; + hit->pathCount = n; + + // add the cost + if (options & DT_RAYCAST_USE_COSTS) + hit->pathCost += filter->getCost(curPos, endPos, prevRef, prevTile, prevPoly, curRef, tile, poly, curRef, tile, poly); + return status; + } + + // Follow neighbours. + dtPolyRef nextRef = 0; + + for (unsigned int i = poly->firstLink; i != DT_NULL_LINK; i = tile->links[i].next) + { + const dtLink* link = &tile->links[i]; + + // Find link which contains this edge. + if ((int)link->edge != segMax) + continue; + + // Get pointer to the next polygon. + nextTile = 0; + nextPoly = 0; + m_nav->getTileAndPolyByRefUnsafe(link->ref, &nextTile, &nextPoly); + + // Skip off-mesh connections. + if (nextPoly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION) + continue; + + // Skip links based on filter. + if (!filter->passFilter(link->ref, nextTile, nextPoly)) + continue; + + // If the link is internal, just return the ref. + if (link->side == 0xff) + { + nextRef = link->ref; + break; + } + + // If the link is at tile boundary, + + // Check if the link spans the whole edge, and accept. + if (link->bmin == 0 && link->bmax == 255) + { + nextRef = link->ref; + break; + } + + // Check for partial edge links. + const int v0 = poly->verts[link->edge]; + const int v1 = poly->verts[(link->edge+1) % poly->vertCount]; + const float* left = &tile->verts[v0*3]; + const float* right = &tile->verts[v1*3]; + + // Check that the intersection lies inside the link portal. + if (link->side == 0 || link->side == 4) + { + // Calculate link size. + const float s = 1.0f/255.0f; + float lmin = left[2] + (right[2] - left[2])*(link->bmin*s); + float lmax = left[2] + (right[2] - left[2])*(link->bmax*s); + if (lmin > lmax) dtSwap(lmin, lmax); + + // Find Z intersection. + float z = startPos[2] + (endPos[2]-startPos[2])*tmax; + if (z >= lmin && z <= lmax) + { + nextRef = link->ref; + break; + } + } + else if (link->side == 2 || link->side == 6) + { + // Calculate link size. + const float s = 1.0f/255.0f; + float lmin = left[0] + (right[0] - left[0])*(link->bmin*s); + float lmax = left[0] + (right[0] - left[0])*(link->bmax*s); + if (lmin > lmax) dtSwap(lmin, lmax); + + // Find X intersection. + float x = startPos[0] + (endPos[0]-startPos[0])*tmax; + if (x >= lmin && x <= lmax) + { + nextRef = link->ref; + break; + } + } + } + + // add the cost + if (options & DT_RAYCAST_USE_COSTS) + { + // compute the intersection point at the furthest end of the polygon + // and correct the height (since the raycast moves in 2d) + dtVcopy(lastPos, curPos); + dtVmad(curPos, startPos, dir, hit->t); + float* e1 = &verts[segMax*3]; + float* e2 = &verts[((segMax+1)%nv)*3]; + float eDir[3], diff[3]; + dtVsub(eDir, e2, e1); + dtVsub(diff, curPos, e1); + float s = dtSqr(eDir[0]) > dtSqr(eDir[2]) ? diff[0] / eDir[0] : diff[2] / eDir[2]; + curPos[1] = e1[1] + eDir[1] * s; + + hit->pathCost += filter->getCost(lastPos, curPos, prevRef, prevTile, prevPoly, curRef, tile, poly, nextRef, nextTile, nextPoly); + } + + if (!nextRef) + { + // No neighbour, we hit a wall. + + // Calculate hit normal. + const int a = segMax; + const int b = segMax+1 < nv ? segMax+1 : 0; + const float* va = &verts[a*3]; + const float* vb = &verts[b*3]; + const float dx = vb[0] - va[0]; + const float dz = vb[2] - va[2]; + hit->hitNormal[0] = dz; + hit->hitNormal[1] = 0; + hit->hitNormal[2] = -dx; + dtVnormalize(hit->hitNormal); + + hit->pathCount = n; + return status; + } + + // No hit, advance to neighbour polygon. + prevRef = curRef; + curRef = nextRef; + prevTile = tile; + tile = nextTile; + prevPoly = poly; + poly = nextPoly; + + if (status & DT_BUFFER_TOO_SMALL) + { + status |= DT_PARTIAL_RESULT; + break; + } + } + + hit->pathCount = n; + + return status; +} + +/// @par +/// +/// At least one result array must be provided. +/// +/// The order of the result set is from least to highest cost to reach the polygon. +/// +/// A common use case for this method is to perform Dijkstra searches. +/// Candidate polygons are found by searching the graph beginning at the start polygon. +/// +/// If a polygon is not found via the graph search, even if it intersects the +/// search circle, it will not be included in the result set. For example: +/// +/// polyA is the start polygon. +/// polyB shares an edge with polyA. (Is adjacent.) +/// polyC shares an edge with polyB, but not with polyA +/// Even if the search circle overlaps polyC, it will not be included in the +/// result set unless polyB is also in the set. +/// +/// The value of the center point is used as the start position for cost +/// calculations. It is not projected onto the surface of the mesh, so its +/// y-value will effect the costs. +/// +/// Intersection tests occur in 2D. All polygons and the search circle are +/// projected onto the xz-plane. So the y-value of the center point does not +/// effect intersection tests. +/// +/// If the result arrays are to small to hold the entire result set, they will be +/// filled to capacity. +/// +dtStatus dtNavMeshQuery::findPolysAroundCircle(dtPolyRef startRef, const float* centerPos, const float radius, + const dtQueryFilter* filter, + dtPolyRef* resultRef, dtPolyRef* resultParent, float* resultCost, + int* resultCount, const int maxResult) const +{ + dtAssert(m_nav); + dtAssert(m_nodePool); + dtAssert(m_openList); + + if (!resultCount) + return DT_FAILURE | DT_INVALID_PARAM; + + *resultCount = 0; + + if (!m_nav->isValidPolyRef(startRef) || + !centerPos || !dtVisfinite(centerPos) || + radius < 0 || !dtMathIsfinite(radius) || + !filter || maxResult < 0) + { + return DT_FAILURE | DT_INVALID_PARAM; + } + + m_nodePool->clear(); + m_openList->clear(); + + dtNode* startNode = m_nodePool->getNode(startRef); + dtVcopy(startNode->pos, centerPos); + startNode->pidx = 0; + startNode->cost = 0; + startNode->total = 0; + startNode->id = startRef; + startNode->flags = DT_NODE_OPEN; + m_openList->push(startNode); + + dtStatus status = DT_SUCCESS; + + int n = 0; + + const float radiusSqr = dtSqr(radius); + + while (!m_openList->empty()) + { + dtNode* bestNode = m_openList->pop(); + bestNode->flags &= ~DT_NODE_OPEN; + bestNode->flags |= DT_NODE_CLOSED; + + // Get poly and tile. + // The API input has been checked already, skip checking internal data. + const dtPolyRef bestRef = bestNode->id; + const dtMeshTile* bestTile = 0; + const dtPoly* bestPoly = 0; + m_nav->getTileAndPolyByRefUnsafe(bestRef, &bestTile, &bestPoly); + + // Get parent poly and tile. + dtPolyRef parentRef = 0; + const dtMeshTile* parentTile = 0; + const dtPoly* parentPoly = 0; + if (bestNode->pidx) + parentRef = m_nodePool->getNodeAtIdx(bestNode->pidx)->id; + if (parentRef) + m_nav->getTileAndPolyByRefUnsafe(parentRef, &parentTile, &parentPoly); + + if (n < maxResult) + { + if (resultRef) + resultRef[n] = bestRef; + if (resultParent) + resultParent[n] = parentRef; + if (resultCost) + resultCost[n] = bestNode->total; + ++n; + } + else + { + status |= DT_BUFFER_TOO_SMALL; + } + + for (unsigned int i = bestPoly->firstLink; i != DT_NULL_LINK; i = bestTile->links[i].next) + { + const dtLink* link = &bestTile->links[i]; + dtPolyRef neighbourRef = link->ref; + // Skip invalid neighbours and do not follow back to parent. + if (!neighbourRef || neighbourRef == parentRef) + continue; + + // Expand to neighbour + const dtMeshTile* neighbourTile = 0; + const dtPoly* neighbourPoly = 0; + m_nav->getTileAndPolyByRefUnsafe(neighbourRef, &neighbourTile, &neighbourPoly); + + // Do not advance if the polygon is excluded by the filter. + if (!filter->passFilter(neighbourRef, neighbourTile, neighbourPoly)) + continue; + + // Find edge and calc distance to the edge. + float va[3], vb[3]; + if (!getPortalPoints(bestRef, bestPoly, bestTile, neighbourRef, neighbourPoly, neighbourTile, va, vb)) + continue; + + // If the circle is not touching the next polygon, skip it. + float tseg; + float distSqr = dtDistancePtSegSqr2D(centerPos, va, vb, tseg); + if (distSqr > radiusSqr) + continue; + + dtNode* neighbourNode = m_nodePool->getNode(neighbourRef); + if (!neighbourNode) + { + status |= DT_OUT_OF_NODES; + continue; + } + + if (neighbourNode->flags & DT_NODE_CLOSED) + continue; + + // Cost + if (neighbourNode->flags == 0) + dtVlerp(neighbourNode->pos, va, vb, 0.5f); + + float cost = filter->getCost( + bestNode->pos, neighbourNode->pos, + parentRef, parentTile, parentPoly, + bestRef, bestTile, bestPoly, + neighbourRef, neighbourTile, neighbourPoly); + + const float total = bestNode->total + cost; + + // The node is already in open list and the new result is worse, skip. + if ((neighbourNode->flags & DT_NODE_OPEN) && total >= neighbourNode->total) + continue; + + neighbourNode->id = neighbourRef; + neighbourNode->pidx = m_nodePool->getNodeIdx(bestNode); + neighbourNode->total = total; + + if (neighbourNode->flags & DT_NODE_OPEN) + { + m_openList->modify(neighbourNode); + } + else + { + neighbourNode->flags = DT_NODE_OPEN; + m_openList->push(neighbourNode); + } + } + } + + *resultCount = n; + + return status; +} + +/// @par +/// +/// The order of the result set is from least to highest cost. +/// +/// At least one result array must be provided. +/// +/// A common use case for this method is to perform Dijkstra searches. +/// Candidate polygons are found by searching the graph beginning at the start +/// polygon. +/// +/// The same intersection test restrictions that apply to findPolysAroundCircle() +/// method apply to this method. +/// +/// The 3D centroid of the search polygon is used as the start position for cost +/// calculations. +/// +/// Intersection tests occur in 2D. All polygons are projected onto the +/// xz-plane. So the y-values of the vertices do not effect intersection tests. +/// +/// If the result arrays are is too small to hold the entire result set, they will +/// be filled to capacity. +/// +dtStatus dtNavMeshQuery::findPolysAroundShape(dtPolyRef startRef, const float* verts, const int nverts, + const dtQueryFilter* filter, + dtPolyRef* resultRef, dtPolyRef* resultParent, float* resultCost, + int* resultCount, const int maxResult) const +{ + dtAssert(m_nav); + dtAssert(m_nodePool); + dtAssert(m_openList); + + if (!resultCount) + return DT_FAILURE | DT_INVALID_PARAM; + + *resultCount = 0; + + if (!m_nav->isValidPolyRef(startRef) || + !verts || nverts < 3 || + !filter || maxResult < 0) + { + return DT_FAILURE | DT_INVALID_PARAM; + } + + // Validate input + if (!startRef || !m_nav->isValidPolyRef(startRef)) + return DT_FAILURE | DT_INVALID_PARAM; + + m_nodePool->clear(); + m_openList->clear(); + + float centerPos[3] = {0,0,0}; + for (int i = 0; i < nverts; ++i) + dtVadd(centerPos,centerPos,&verts[i*3]); + dtVscale(centerPos,centerPos,1.0f/nverts); + + dtNode* startNode = m_nodePool->getNode(startRef); + dtVcopy(startNode->pos, centerPos); + startNode->pidx = 0; + startNode->cost = 0; + startNode->total = 0; + startNode->id = startRef; + startNode->flags = DT_NODE_OPEN; + m_openList->push(startNode); + + dtStatus status = DT_SUCCESS; + + int n = 0; + + while (!m_openList->empty()) + { + dtNode* bestNode = m_openList->pop(); + bestNode->flags &= ~DT_NODE_OPEN; + bestNode->flags |= DT_NODE_CLOSED; + + // Get poly and tile. + // The API input has been checked already, skip checking internal data. + const dtPolyRef bestRef = bestNode->id; + const dtMeshTile* bestTile = 0; + const dtPoly* bestPoly = 0; + m_nav->getTileAndPolyByRefUnsafe(bestRef, &bestTile, &bestPoly); + + // Get parent poly and tile. + dtPolyRef parentRef = 0; + const dtMeshTile* parentTile = 0; + const dtPoly* parentPoly = 0; + if (bestNode->pidx) + parentRef = m_nodePool->getNodeAtIdx(bestNode->pidx)->id; + if (parentRef) + m_nav->getTileAndPolyByRefUnsafe(parentRef, &parentTile, &parentPoly); + + if (n < maxResult) + { + if (resultRef) + resultRef[n] = bestRef; + if (resultParent) + resultParent[n] = parentRef; + if (resultCost) + resultCost[n] = bestNode->total; + + ++n; + } + else + { + status |= DT_BUFFER_TOO_SMALL; + } + + for (unsigned int i = bestPoly->firstLink; i != DT_NULL_LINK; i = bestTile->links[i].next) + { + const dtLink* link = &bestTile->links[i]; + dtPolyRef neighbourRef = link->ref; + // Skip invalid neighbours and do not follow back to parent. + if (!neighbourRef || neighbourRef == parentRef) + continue; + + // Expand to neighbour + const dtMeshTile* neighbourTile = 0; + const dtPoly* neighbourPoly = 0; + m_nav->getTileAndPolyByRefUnsafe(neighbourRef, &neighbourTile, &neighbourPoly); + + // Do not advance if the polygon is excluded by the filter. + if (!filter->passFilter(neighbourRef, neighbourTile, neighbourPoly)) + continue; + + // Find edge and calc distance to the edge. + float va[3], vb[3]; + if (!getPortalPoints(bestRef, bestPoly, bestTile, neighbourRef, neighbourPoly, neighbourTile, va, vb)) + continue; + + // If the poly is not touching the edge to the next polygon, skip the connection it. + float tmin, tmax; + int segMin, segMax; + if (!dtIntersectSegmentPoly2D(va, vb, verts, nverts, tmin, tmax, segMin, segMax)) + continue; + if (tmin > 1.0f || tmax < 0.0f) + continue; + + dtNode* neighbourNode = m_nodePool->getNode(neighbourRef); + if (!neighbourNode) + { + status |= DT_OUT_OF_NODES; + continue; + } + + if (neighbourNode->flags & DT_NODE_CLOSED) + continue; + + // Cost + if (neighbourNode->flags == 0) + dtVlerp(neighbourNode->pos, va, vb, 0.5f); + + float cost = filter->getCost( + bestNode->pos, neighbourNode->pos, + parentRef, parentTile, parentPoly, + bestRef, bestTile, bestPoly, + neighbourRef, neighbourTile, neighbourPoly); + + const float total = bestNode->total + cost; + + // The node is already in open list and the new result is worse, skip. + if ((neighbourNode->flags & DT_NODE_OPEN) && total >= neighbourNode->total) + continue; + + neighbourNode->id = neighbourRef; + neighbourNode->pidx = m_nodePool->getNodeIdx(bestNode); + neighbourNode->total = total; + + if (neighbourNode->flags & DT_NODE_OPEN) + { + m_openList->modify(neighbourNode); + } + else + { + neighbourNode->flags = DT_NODE_OPEN; + m_openList->push(neighbourNode); + } + } + } + + *resultCount = n; + + return status; +} + +dtStatus dtNavMeshQuery::getPathFromDijkstraSearch(dtPolyRef endRef, dtPolyRef* path, int* pathCount, int maxPath) const +{ + if (!m_nav->isValidPolyRef(endRef) || !path || !pathCount || maxPath < 0) + return DT_FAILURE | DT_INVALID_PARAM; + + *pathCount = 0; + + dtNode* endNode; + if (m_nodePool->findNodes(endRef, &endNode, 1) != 1 || + (endNode->flags & DT_NODE_CLOSED) == 0) + return DT_FAILURE | DT_INVALID_PARAM; + + return getPathToNode(endNode, path, pathCount, maxPath); +} + +/// @par +/// +/// This method is optimized for a small search radius and small number of result +/// polygons. +/// +/// Candidate polygons are found by searching the navigation graph beginning at +/// the start polygon. +/// +/// The same intersection test restrictions that apply to the findPolysAroundCircle +/// mehtod applies to this method. +/// +/// The value of the center point is used as the start point for cost calculations. +/// It is not projected onto the surface of the mesh, so its y-value will effect +/// the costs. +/// +/// Intersection tests occur in 2D. All polygons and the search circle are +/// projected onto the xz-plane. So the y-value of the center point does not +/// effect intersection tests. +/// +/// If the result arrays are is too small to hold the entire result set, they will +/// be filled to capacity. +/// +dtStatus dtNavMeshQuery::findLocalNeighbourhood(dtPolyRef startRef, const float* centerPos, const float radius, + const dtQueryFilter* filter, + dtPolyRef* resultRef, dtPolyRef* resultParent, + int* resultCount, const int maxResult) const +{ + dtAssert(m_nav); + dtAssert(m_tinyNodePool); + + if (!resultCount) + return DT_FAILURE | DT_INVALID_PARAM; + + *resultCount = 0; + + if (!m_nav->isValidPolyRef(startRef) || + !centerPos || !dtVisfinite(centerPos) || + radius < 0 || !dtMathIsfinite(radius) || + !filter || maxResult < 0) + { + return DT_FAILURE | DT_INVALID_PARAM; + } + + static const int MAX_STACK = 48; + dtNode* stack[MAX_STACK]; + int nstack = 0; + + m_tinyNodePool->clear(); + + dtNode* startNode = m_tinyNodePool->getNode(startRef); + startNode->pidx = 0; + startNode->id = startRef; + startNode->flags = DT_NODE_CLOSED; + stack[nstack++] = startNode; + + const float radiusSqr = dtSqr(radius); + + float pa[DT_VERTS_PER_POLYGON*3]; + float pb[DT_VERTS_PER_POLYGON*3]; + + dtStatus status = DT_SUCCESS; + + int n = 0; + if (n < maxResult) + { + resultRef[n] = startNode->id; + if (resultParent) + resultParent[n] = 0; + ++n; + } + else + { + status |= DT_BUFFER_TOO_SMALL; + } + + while (nstack) + { + // Pop front. + dtNode* curNode = stack[0]; + for (int i = 0; i < nstack-1; ++i) + stack[i] = stack[i+1]; + nstack--; + + // Get poly and tile. + // The API input has been checked already, skip checking internal data. + const dtPolyRef curRef = curNode->id; + const dtMeshTile* curTile = 0; + const dtPoly* curPoly = 0; + m_nav->getTileAndPolyByRefUnsafe(curRef, &curTile, &curPoly); + + for (unsigned int i = curPoly->firstLink; i != DT_NULL_LINK; i = curTile->links[i].next) + { + const dtLink* link = &curTile->links[i]; + dtPolyRef neighbourRef = link->ref; + // Skip invalid neighbours. + if (!neighbourRef) + continue; + + // Skip if cannot alloca more nodes. + dtNode* neighbourNode = m_tinyNodePool->getNode(neighbourRef); + if (!neighbourNode) + continue; + // Skip visited. + if (neighbourNode->flags & DT_NODE_CLOSED) + continue; + + // Expand to neighbour + const dtMeshTile* neighbourTile = 0; + const dtPoly* neighbourPoly = 0; + m_nav->getTileAndPolyByRefUnsafe(neighbourRef, &neighbourTile, &neighbourPoly); + + // Skip off-mesh connections. + if (neighbourPoly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION) + continue; + + // Do not advance if the polygon is excluded by the filter. + if (!filter->passFilter(neighbourRef, neighbourTile, neighbourPoly)) + continue; + + // Find edge and calc distance to the edge. + float va[3], vb[3]; + if (!getPortalPoints(curRef, curPoly, curTile, neighbourRef, neighbourPoly, neighbourTile, va, vb)) + continue; + + // If the circle is not touching the next polygon, skip it. + float tseg; + float distSqr = dtDistancePtSegSqr2D(centerPos, va, vb, tseg); + if (distSqr > radiusSqr) + continue; + + // Mark node visited, this is done before the overlap test so that + // we will not visit the poly again if the test fails. + neighbourNode->flags |= DT_NODE_CLOSED; + neighbourNode->pidx = m_tinyNodePool->getNodeIdx(curNode); + + // Check that the polygon does not collide with existing polygons. + + // Collect vertices of the neighbour poly. + const int npa = neighbourPoly->vertCount; + for (int k = 0; k < npa; ++k) + dtVcopy(&pa[k*3], &neighbourTile->verts[neighbourPoly->verts[k]*3]); + + bool overlap = false; + for (int j = 0; j < n; ++j) + { + dtPolyRef pastRef = resultRef[j]; + + // Connected polys do not overlap. + bool connected = false; + for (unsigned int k = curPoly->firstLink; k != DT_NULL_LINK; k = curTile->links[k].next) + { + if (curTile->links[k].ref == pastRef) + { + connected = true; + break; + } + } + if (connected) + continue; + + // Potentially overlapping. + const dtMeshTile* pastTile = 0; + const dtPoly* pastPoly = 0; + m_nav->getTileAndPolyByRefUnsafe(pastRef, &pastTile, &pastPoly); + + // Get vertices and test overlap + const int npb = pastPoly->vertCount; + for (int k = 0; k < npb; ++k) + dtVcopy(&pb[k*3], &pastTile->verts[pastPoly->verts[k]*3]); + + if (dtOverlapPolyPoly2D(pa,npa, pb,npb)) + { + overlap = true; + break; + } + } + if (overlap) + continue; + + // This poly is fine, store and advance to the poly. + if (n < maxResult) + { + resultRef[n] = neighbourRef; + if (resultParent) + resultParent[n] = curRef; + ++n; + } + else + { + status |= DT_BUFFER_TOO_SMALL; + } + + if (nstack < MAX_STACK) + { + stack[nstack++] = neighbourNode; + } + } + } + + *resultCount = n; + + return status; +} + + +struct dtSegInterval +{ + dtPolyRef ref; + short tmin, tmax; +}; + +static void insertInterval(dtSegInterval* ints, int& nints, const int maxInts, + const short tmin, const short tmax, const dtPolyRef ref) +{ + if (nints+1 > maxInts) return; + // Find insertion point. + int idx = 0; + while (idx < nints) + { + if (tmax <= ints[idx].tmin) + break; + idx++; + } + // Move current results. + if (nints-idx) + memmove(ints+idx+1, ints+idx, sizeof(dtSegInterval)*(nints-idx)); + // Store + ints[idx].ref = ref; + ints[idx].tmin = tmin; + ints[idx].tmax = tmax; + nints++; +} + +/// @par +/// +/// If the @p segmentRefs parameter is provided, then all polygon segments will be returned. +/// Otherwise only the wall segments are returned. +/// +/// A segment that is normally a portal will be included in the result set as a +/// wall if the @p filter results in the neighbor polygon becoomming impassable. +/// +/// The @p segmentVerts and @p segmentRefs buffers should normally be sized for the +/// maximum segments per polygon of the source navigation mesh. +/// +dtStatus dtNavMeshQuery::getPolyWallSegments(dtPolyRef ref, const dtQueryFilter* filter, + float* segmentVerts, dtPolyRef* segmentRefs, int* segmentCount, + const int maxSegments) const +{ + dtAssert(m_nav); + + if (!segmentCount) + return DT_FAILURE | DT_INVALID_PARAM; + + *segmentCount = 0; + + const dtMeshTile* tile = 0; + const dtPoly* poly = 0; + if (dtStatusFailed(m_nav->getTileAndPolyByRef(ref, &tile, &poly))) + return DT_FAILURE | DT_INVALID_PARAM; + + if (!filter || !segmentVerts || maxSegments < 0) + return DT_FAILURE | DT_INVALID_PARAM; + + int n = 0; + static const int MAX_INTERVAL = 16; + dtSegInterval ints[MAX_INTERVAL]; + int nints; + + const bool storePortals = segmentRefs != 0; + + dtStatus status = DT_SUCCESS; + + for (int i = 0, j = (int)poly->vertCount-1; i < (int)poly->vertCount; j = i++) + { + // Skip non-solid edges. + nints = 0; + if (poly->neis[j] & DT_EXT_LINK) + { + // Tile border. + for (unsigned int k = poly->firstLink; k != DT_NULL_LINK; k = tile->links[k].next) + { + const dtLink* link = &tile->links[k]; + if (link->edge == j) + { + if (link->ref != 0) + { + const dtMeshTile* neiTile = 0; + const dtPoly* neiPoly = 0; + m_nav->getTileAndPolyByRefUnsafe(link->ref, &neiTile, &neiPoly); + if (filter->passFilter(link->ref, neiTile, neiPoly)) + { + insertInterval(ints, nints, MAX_INTERVAL, link->bmin, link->bmax, link->ref); + } + } + } + } + } + else + { + // Internal edge + dtPolyRef neiRef = 0; + if (poly->neis[j]) + { + const unsigned int idx = (unsigned int)(poly->neis[j]-1); + neiRef = m_nav->getPolyRefBase(tile) | idx; + if (!filter->passFilter(neiRef, tile, &tile->polys[idx])) + neiRef = 0; + } + + // If the edge leads to another polygon and portals are not stored, skip. + if (neiRef != 0 && !storePortals) + continue; + + if (n < maxSegments) + { + const float* vj = &tile->verts[poly->verts[j]*3]; + const float* vi = &tile->verts[poly->verts[i]*3]; + float* seg = &segmentVerts[n*6]; + dtVcopy(seg+0, vj); + dtVcopy(seg+3, vi); + if (segmentRefs) + segmentRefs[n] = neiRef; + n++; + } + else + { + status |= DT_BUFFER_TOO_SMALL; + } + + continue; + } + + // Add sentinels + insertInterval(ints, nints, MAX_INTERVAL, -1, 0, 0); + insertInterval(ints, nints, MAX_INTERVAL, 255, 256, 0); + + // Store segments. + const float* vj = &tile->verts[poly->verts[j]*3]; + const float* vi = &tile->verts[poly->verts[i]*3]; + for (int k = 1; k < nints; ++k) + { + // Portal segment. + if (storePortals && ints[k].ref) + { + const float tmin = ints[k].tmin/255.0f; + const float tmax = ints[k].tmax/255.0f; + if (n < maxSegments) + { + float* seg = &segmentVerts[n*6]; + dtVlerp(seg+0, vj,vi, tmin); + dtVlerp(seg+3, vj,vi, tmax); + if (segmentRefs) + segmentRefs[n] = ints[k].ref; + n++; + } + else + { + status |= DT_BUFFER_TOO_SMALL; + } + } + + // Wall segment. + const int imin = ints[k-1].tmax; + const int imax = ints[k].tmin; + if (imin != imax) + { + const float tmin = imin/255.0f; + const float tmax = imax/255.0f; + if (n < maxSegments) + { + float* seg = &segmentVerts[n*6]; + dtVlerp(seg+0, vj,vi, tmin); + dtVlerp(seg+3, vj,vi, tmax); + if (segmentRefs) + segmentRefs[n] = 0; + n++; + } + else + { + status |= DT_BUFFER_TOO_SMALL; + } + } + } + } + + *segmentCount = n; + + return status; +} + +/// @par +/// +/// @p hitPos is not adjusted using the height detail data. +/// +/// @p hitDist will equal the search radius if there is no wall within the +/// radius. In this case the values of @p hitPos and @p hitNormal are +/// undefined. +/// +/// The normal will become unpredicable if @p hitDist is a very small number. +/// +dtStatus dtNavMeshQuery::findDistanceToWall(dtPolyRef startRef, const float* centerPos, const float maxRadius, + const dtQueryFilter* filter, + float* hitDist, float* hitPos, float* hitNormal) const +{ + dtAssert(m_nav); + dtAssert(m_nodePool); + dtAssert(m_openList); + + // Validate input + if (!m_nav->isValidPolyRef(startRef) || + !centerPos || !dtVisfinite(centerPos) || + maxRadius < 0 || !dtMathIsfinite(maxRadius) || + !filter || !hitDist || !hitPos || !hitNormal) + { + return DT_FAILURE | DT_INVALID_PARAM; + } + + m_nodePool->clear(); + m_openList->clear(); + + dtNode* startNode = m_nodePool->getNode(startRef); + dtVcopy(startNode->pos, centerPos); + startNode->pidx = 0; + startNode->cost = 0; + startNode->total = 0; + startNode->id = startRef; + startNode->flags = DT_NODE_OPEN; + m_openList->push(startNode); + + float radiusSqr = dtSqr(maxRadius); + + dtStatus status = DT_SUCCESS; + + while (!m_openList->empty()) + { + dtNode* bestNode = m_openList->pop(); + bestNode->flags &= ~DT_NODE_OPEN; + bestNode->flags |= DT_NODE_CLOSED; + + // Get poly and tile. + // The API input has been checked already, skip checking internal data. + const dtPolyRef bestRef = bestNode->id; + const dtMeshTile* bestTile = 0; + const dtPoly* bestPoly = 0; + m_nav->getTileAndPolyByRefUnsafe(bestRef, &bestTile, &bestPoly); + + // Get parent poly and tile. + dtPolyRef parentRef = 0; + const dtMeshTile* parentTile = 0; + const dtPoly* parentPoly = 0; + if (bestNode->pidx) + parentRef = m_nodePool->getNodeAtIdx(bestNode->pidx)->id; + if (parentRef) + m_nav->getTileAndPolyByRefUnsafe(parentRef, &parentTile, &parentPoly); + + // Hit test walls. + for (int i = 0, j = (int)bestPoly->vertCount-1; i < (int)bestPoly->vertCount; j = i++) + { + // Skip non-solid edges. + if (bestPoly->neis[j] & DT_EXT_LINK) + { + // Tile border. + bool solid = true; + for (unsigned int k = bestPoly->firstLink; k != DT_NULL_LINK; k = bestTile->links[k].next) + { + const dtLink* link = &bestTile->links[k]; + if (link->edge == j) + { + if (link->ref != 0) + { + const dtMeshTile* neiTile = 0; + const dtPoly* neiPoly = 0; + m_nav->getTileAndPolyByRefUnsafe(link->ref, &neiTile, &neiPoly); + if (filter->passFilter(link->ref, neiTile, neiPoly)) + solid = false; + } + break; + } + } + if (!solid) continue; + } + else if (bestPoly->neis[j]) + { + // Internal edge + const unsigned int idx = (unsigned int)(bestPoly->neis[j]-1); + const dtPolyRef ref = m_nav->getPolyRefBase(bestTile) | idx; + if (filter->passFilter(ref, bestTile, &bestTile->polys[idx])) + continue; + } + + // Calc distance to the edge. + const float* vj = &bestTile->verts[bestPoly->verts[j]*3]; + const float* vi = &bestTile->verts[bestPoly->verts[i]*3]; + float tseg; + float distSqr = dtDistancePtSegSqr2D(centerPos, vj, vi, tseg); + + // Edge is too far, skip. + if (distSqr > radiusSqr) + continue; + + // Hit wall, update radius. + radiusSqr = distSqr; + // Calculate hit pos. + hitPos[0] = vj[0] + (vi[0] - vj[0])*tseg; + hitPos[1] = vj[1] + (vi[1] - vj[1])*tseg; + hitPos[2] = vj[2] + (vi[2] - vj[2])*tseg; + } + + for (unsigned int i = bestPoly->firstLink; i != DT_NULL_LINK; i = bestTile->links[i].next) + { + const dtLink* link = &bestTile->links[i]; + dtPolyRef neighbourRef = link->ref; + // Skip invalid neighbours and do not follow back to parent. + if (!neighbourRef || neighbourRef == parentRef) + continue; + + // Expand to neighbour. + const dtMeshTile* neighbourTile = 0; + const dtPoly* neighbourPoly = 0; + m_nav->getTileAndPolyByRefUnsafe(neighbourRef, &neighbourTile, &neighbourPoly); + + // Skip off-mesh connections. + if (neighbourPoly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION) + continue; + + // Calc distance to the edge. + const float* va = &bestTile->verts[bestPoly->verts[link->edge]*3]; + const float* vb = &bestTile->verts[bestPoly->verts[(link->edge+1) % bestPoly->vertCount]*3]; + float tseg; + float distSqr = dtDistancePtSegSqr2D(centerPos, va, vb, tseg); + + // If the circle is not touching the next polygon, skip it. + if (distSqr > radiusSqr) + continue; + + if (!filter->passFilter(neighbourRef, neighbourTile, neighbourPoly)) + continue; + + dtNode* neighbourNode = m_nodePool->getNode(neighbourRef); + if (!neighbourNode) + { + status |= DT_OUT_OF_NODES; + continue; + } + + if (neighbourNode->flags & DT_NODE_CLOSED) + continue; + + // Cost + if (neighbourNode->flags == 0) + { + getEdgeMidPoint(bestRef, bestPoly, bestTile, + neighbourRef, neighbourPoly, neighbourTile, neighbourNode->pos); + } + + const float total = bestNode->total + dtVdist(bestNode->pos, neighbourNode->pos); + + // The node is already in open list and the new result is worse, skip. + if ((neighbourNode->flags & DT_NODE_OPEN) && total >= neighbourNode->total) + continue; + + neighbourNode->id = neighbourRef; + neighbourNode->flags = (neighbourNode->flags & ~DT_NODE_CLOSED); + neighbourNode->pidx = m_nodePool->getNodeIdx(bestNode); + neighbourNode->total = total; + + if (neighbourNode->flags & DT_NODE_OPEN) + { + m_openList->modify(neighbourNode); + } + else + { + neighbourNode->flags |= DT_NODE_OPEN; + m_openList->push(neighbourNode); + } + } + } + + // Calc hit normal. + dtVsub(hitNormal, centerPos, hitPos); + dtVnormalize(hitNormal); + + *hitDist = dtMathSqrtf(radiusSqr); + + return status; +} + +bool dtNavMeshQuery::isValidPolyRef(dtPolyRef ref, const dtQueryFilter* filter) const +{ + const dtMeshTile* tile = 0; + const dtPoly* poly = 0; + dtStatus status = m_nav->getTileAndPolyByRef(ref, &tile, &poly); + // If cannot get polygon, assume it does not exists and boundary is invalid. + if (dtStatusFailed(status)) + return false; + // If cannot pass filter, assume flags has changed and boundary is invalid. + if (!filter->passFilter(ref, tile, poly)) + return false; + return true; +} + +/// @par +/// +/// The closed list is the list of polygons that were fully evaluated during +/// the last navigation graph search. (A* or Dijkstra) +/// +bool dtNavMeshQuery::isInClosedList(dtPolyRef ref) const +{ + if (!m_nodePool) return false; + + dtNode* nodes[DT_MAX_STATES_PER_NODE]; + int n= m_nodePool->findNodes(ref, nodes, DT_MAX_STATES_PER_NODE); + + for (int i=0; iflags & DT_NODE_CLOSED) + return true; + } + + return false; +} diff --git a/native/third_party/recastnavigation/Detour/Source/DetourNode.cpp b/native/third_party/recastnavigation/Detour/Source/DetourNode.cpp new file mode 100644 index 0000000..48abbba --- /dev/null +++ b/native/third_party/recastnavigation/Detour/Source/DetourNode.cpp @@ -0,0 +1,200 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#include "DetourNode.h" +#include "DetourAlloc.h" +#include "DetourAssert.h" +#include "DetourCommon.h" +#include + +#ifdef DT_POLYREF64 +// From Thomas Wang, https://gist.github.com/badboy/6267743 +inline unsigned int dtHashRef(dtPolyRef a) +{ + a = (~a) + (a << 18); // a = (a << 18) - a - 1; + a = a ^ (a >> 31); + a = a * 21; // a = (a + (a << 2)) + (a << 4); + a = a ^ (a >> 11); + a = a + (a << 6); + a = a ^ (a >> 22); + return (unsigned int)a; +} +#else +inline unsigned int dtHashRef(dtPolyRef a) +{ + a += ~(a<<15); + a ^= (a>>10); + a += (a<<3); + a ^= (a>>6); + a += ~(a<<11); + a ^= (a>>16); + return (unsigned int)a; +} +#endif + +////////////////////////////////////////////////////////////////////////////////////////// +dtNodePool::dtNodePool(int maxNodes, int hashSize) : + m_nodes(0), + m_first(0), + m_next(0), + m_maxNodes(maxNodes), + m_hashSize(hashSize), + m_nodeCount(0) +{ + dtAssert(dtNextPow2(m_hashSize) == (unsigned int)m_hashSize); + // pidx is special as 0 means "none" and 1 is the first node. For that reason + // we have 1 fewer nodes available than the number of values it can contain. + dtAssert(m_maxNodes > 0 && m_maxNodes <= DT_NULL_IDX && m_maxNodes <= (1 << DT_NODE_PARENT_BITS) - 1); + + m_nodes = (dtNode*)dtAlloc(sizeof(dtNode)*m_maxNodes, DT_ALLOC_PERM); + m_next = (dtNodeIndex*)dtAlloc(sizeof(dtNodeIndex)*m_maxNodes, DT_ALLOC_PERM); + m_first = (dtNodeIndex*)dtAlloc(sizeof(dtNodeIndex)*hashSize, DT_ALLOC_PERM); + + dtAssert(m_nodes); + dtAssert(m_next); + dtAssert(m_first); + + memset(m_first, 0xff, sizeof(dtNodeIndex)*m_hashSize); + memset(m_next, 0xff, sizeof(dtNodeIndex)*m_maxNodes); +} + +dtNodePool::~dtNodePool() +{ + dtFree(m_nodes); + dtFree(m_next); + dtFree(m_first); +} + +void dtNodePool::clear() +{ + memset(m_first, 0xff, sizeof(dtNodeIndex)*m_hashSize); + m_nodeCount = 0; +} + +unsigned int dtNodePool::findNodes(dtPolyRef id, dtNode** nodes, const int maxNodes) +{ + int n = 0; + unsigned int bucket = dtHashRef(id) & (m_hashSize-1); + dtNodeIndex i = m_first[bucket]; + while (i != DT_NULL_IDX) + { + if (m_nodes[i].id == id) + { + if (n >= maxNodes) + return n; + nodes[n++] = &m_nodes[i]; + } + i = m_next[i]; + } + + return n; +} + +dtNode* dtNodePool::findNode(dtPolyRef id, unsigned char state) +{ + unsigned int bucket = dtHashRef(id) & (m_hashSize-1); + dtNodeIndex i = m_first[bucket]; + while (i != DT_NULL_IDX) + { + if (m_nodes[i].id == id && m_nodes[i].state == state) + return &m_nodes[i]; + i = m_next[i]; + } + return 0; +} + +dtNode* dtNodePool::getNode(dtPolyRef id, unsigned char state) +{ + unsigned int bucket = dtHashRef(id) & (m_hashSize-1); + dtNodeIndex i = m_first[bucket]; + dtNode* node = 0; + while (i != DT_NULL_IDX) + { + if (m_nodes[i].id == id && m_nodes[i].state == state) + return &m_nodes[i]; + i = m_next[i]; + } + + if (m_nodeCount >= m_maxNodes) + return 0; + + i = (dtNodeIndex)m_nodeCount; + m_nodeCount++; + + // Init node + node = &m_nodes[i]; + node->pidx = 0; + node->cost = 0; + node->total = 0; + node->id = id; + node->state = state; + node->flags = 0; + + m_next[i] = m_first[bucket]; + m_first[bucket] = i; + + return node; +} + + +////////////////////////////////////////////////////////////////////////////////////////// +dtNodeQueue::dtNodeQueue(int n) : + m_heap(0), + m_capacity(n), + m_size(0) +{ + dtAssert(m_capacity > 0); + + m_heap = (dtNode**)dtAlloc(sizeof(dtNode*)*(m_capacity+1), DT_ALLOC_PERM); + dtAssert(m_heap); +} + +dtNodeQueue::~dtNodeQueue() +{ + dtFree(m_heap); +} + +void dtNodeQueue::bubbleUp(int i, dtNode* node) +{ + int parent = (i-1)/2; + // note: (index > 0) means there is a parent + while ((i > 0) && (m_heap[parent]->total > node->total)) + { + m_heap[i] = m_heap[parent]; + i = parent; + parent = (i-1)/2; + } + m_heap[i] = node; +} + +void dtNodeQueue::trickleDown(int i, dtNode* node) +{ + int child = (i*2)+1; + while (child < m_size) + { + if (((child+1) < m_size) && + (m_heap[child]->total > m_heap[child+1]->total)) + { + child++; + } + m_heap[i] = m_heap[child]; + i = child; + child = (i*2)+1; + } + bubbleUp(i, node); +} diff --git a/native/third_party/recastnavigation/License.txt b/native/third_party/recastnavigation/License.txt new file mode 100644 index 0000000..95f4bfc --- /dev/null +++ b/native/third_party/recastnavigation/License.txt @@ -0,0 +1,18 @@ +Copyright (c) 2009 Mikko Mononen memon@inside.org + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not +claim that you wrote the original software. If you use this software +in a product, an acknowledgment in the product documentation would be +appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be +misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. + diff --git a/native/third_party/recastnavigation/Recast/Include/Recast.h b/native/third_party/recastnavigation/Recast/Include/Recast.h new file mode 100644 index 0000000..30e710e --- /dev/null +++ b/native/third_party/recastnavigation/Recast/Include/Recast.h @@ -0,0 +1,1371 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#ifndef RECAST_H +#define RECAST_H + +/// The value of PI used by Recast. +static const float RC_PI = 3.14159265f; + +/// Used to ignore unused function parameters and silence any compiler warnings. +template void rcIgnoreUnused(const T&) { } + +/// Recast log categories. +/// @see rcContext +enum rcLogCategory +{ + RC_LOG_PROGRESS = 1, ///< A progress log entry. + RC_LOG_WARNING, ///< A warning log entry. + RC_LOG_ERROR ///< An error log entry. +}; + +/// Recast performance timer categories. +/// @see rcContext +enum rcTimerLabel +{ + /// The user defined total time of the build. + RC_TIMER_TOTAL, + /// A user defined build time. + RC_TIMER_TEMP, + /// The time to rasterize the triangles. (See: #rcRasterizeTriangle) + RC_TIMER_RASTERIZE_TRIANGLES, + /// The time to build the compact heightfield. (See: #rcBuildCompactHeightfield) + RC_TIMER_BUILD_COMPACTHEIGHTFIELD, + /// The total time to build the contours. (See: #rcBuildContours) + RC_TIMER_BUILD_CONTOURS, + /// The time to trace the boundaries of the contours. (See: #rcBuildContours) + RC_TIMER_BUILD_CONTOURS_TRACE, + /// The time to simplify the contours. (See: #rcBuildContours) + RC_TIMER_BUILD_CONTOURS_SIMPLIFY, + /// The time to filter ledge spans. (See: #rcFilterLedgeSpans) + RC_TIMER_FILTER_BORDER, + /// The time to filter low height spans. (See: #rcFilterWalkableLowHeightSpans) + RC_TIMER_FILTER_WALKABLE, + /// The time to apply the median filter. (See: #rcMedianFilterWalkableArea) + RC_TIMER_MEDIAN_AREA, + /// The time to filter low obstacles. (See: #rcFilterLowHangingWalkableObstacles) + RC_TIMER_FILTER_LOW_OBSTACLES, + /// The time to build the polygon mesh. (See: #rcBuildPolyMesh) + RC_TIMER_BUILD_POLYMESH, + /// The time to merge polygon meshes. (See: #rcMergePolyMeshes) + RC_TIMER_MERGE_POLYMESH, + /// The time to erode the walkable area. (See: #rcErodeWalkableArea) + RC_TIMER_ERODE_AREA, + /// The time to mark a box area. (See: #rcMarkBoxArea) + RC_TIMER_MARK_BOX_AREA, + /// The time to mark a cylinder area. (See: #rcMarkCylinderArea) + RC_TIMER_MARK_CYLINDER_AREA, + /// The time to mark a convex polygon area. (See: #rcMarkConvexPolyArea) + RC_TIMER_MARK_CONVEXPOLY_AREA, + /// The total time to build the distance field. (See: #rcBuildDistanceField) + RC_TIMER_BUILD_DISTANCEFIELD, + /// The time to build the distances of the distance field. (See: #rcBuildDistanceField) + RC_TIMER_BUILD_DISTANCEFIELD_DIST, + /// The time to blur the distance field. (See: #rcBuildDistanceField) + RC_TIMER_BUILD_DISTANCEFIELD_BLUR, + /// The total time to build the regions. (See: #rcBuildRegions, #rcBuildRegionsMonotone) + RC_TIMER_BUILD_REGIONS, + /// The total time to apply the watershed algorithm. (See: #rcBuildRegions) + RC_TIMER_BUILD_REGIONS_WATERSHED, + /// The time to expand regions while applying the watershed algorithm. (See: #rcBuildRegions) + RC_TIMER_BUILD_REGIONS_EXPAND, + /// The time to flood regions while applying the watershed algorithm. (See: #rcBuildRegions) + RC_TIMER_BUILD_REGIONS_FLOOD, + /// The time to filter out small regions. (See: #rcBuildRegions, #rcBuildRegionsMonotone) + RC_TIMER_BUILD_REGIONS_FILTER, + /// The time to build heightfield layers. (See: #rcBuildHeightfieldLayers) + RC_TIMER_BUILD_LAYERS, + /// The time to build the polygon mesh detail. (See: #rcBuildPolyMeshDetail) + RC_TIMER_BUILD_POLYMESHDETAIL, + /// The time to merge polygon mesh details. (See: #rcMergePolyMeshDetails) + RC_TIMER_MERGE_POLYMESHDETAIL, + /// The maximum number of timers. (Used for iterating timers.) + RC_MAX_TIMERS +}; + +/// Provides an interface for optional logging and performance tracking of the Recast +/// build process. +/// +/// This class does not provide logging or timer functionality on its +/// own. Both must be provided by a concrete implementation +/// by overriding the protected member functions. Also, this class does not +/// provide an interface for extracting log messages. (Only adding them.) +/// So concrete implementations must provide one. +/// +/// If no logging or timers are required, just pass an instance of this +/// class through the Recast build process. +/// +/// @ingroup recast +class rcContext +{ +public: + /// Constructor. + /// @param[in] state TRUE if the logging and performance timers should be enabled. [Default: true] + inline rcContext(bool state = true) : m_logEnabled(state), m_timerEnabled(state) {} + virtual ~rcContext() {} + + /// Enables or disables logging. + /// @param[in] state TRUE if logging should be enabled. + inline void enableLog(bool state) { m_logEnabled = state; } + + /// Clears all log entries. + inline void resetLog() { if (m_logEnabled) doResetLog(); } + + /// Logs a message. + /// + /// Example: + /// @code + /// // Where ctx is an instance of rcContext and filepath is a char array. + /// ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not load '%s'", filepath); + /// @endcode + /// + /// @param[in] category The category of the message. + /// @param[in] format The message. + void log(const rcLogCategory category, const char* format, ...); + + /// Enables or disables the performance timers. + /// @param[in] state TRUE if timers should be enabled. + inline void enableTimer(bool state) { m_timerEnabled = state; } + + /// Clears all performance timers. (Resets all to unused.) + inline void resetTimers() { if (m_timerEnabled) doResetTimers(); } + + /// Starts the specified performance timer. + /// @param label The category of the timer. + inline void startTimer(const rcTimerLabel label) { if (m_timerEnabled) doStartTimer(label); } + + /// Stops the specified performance timer. + /// @param label The category of the timer. + inline void stopTimer(const rcTimerLabel label) { if (m_timerEnabled) doStopTimer(label); } + + /// Returns the total accumulated time of the specified performance timer. + /// @param label The category of the timer. + /// @return The accumulated time of the timer, or -1 if timers are disabled or the timer has never been started. + inline int getAccumulatedTime(const rcTimerLabel label) const { return m_timerEnabled ? doGetAccumulatedTime(label) : -1; } + +protected: + /// Clears all log entries. + virtual void doResetLog(); + + /// Logs a message. + /// @param[in] category The category of the message. + /// @param[in] msg The formatted message. + /// @param[in] len The length of the formatted message. + virtual void doLog(const rcLogCategory category, const char* msg, const int len) { rcIgnoreUnused(category); rcIgnoreUnused(msg); rcIgnoreUnused(len); } + + /// Clears all timers. (Resets all to unused.) + virtual void doResetTimers() {} + + /// Starts the specified performance timer. + /// @param[in] label The category of timer. + virtual void doStartTimer(const rcTimerLabel label) { rcIgnoreUnused(label); } + + /// Stops the specified performance timer. + /// @param[in] label The category of the timer. + virtual void doStopTimer(const rcTimerLabel label) { rcIgnoreUnused(label); } + + /// Returns the total accumulated time of the specified performance timer. + /// @param[in] label The category of the timer. + /// @return The accumulated time of the timer, or -1 if timers are disabled or the timer has never been started. + virtual int doGetAccumulatedTime(const rcTimerLabel label) const { rcIgnoreUnused(label); return -1; } + + /// True if logging is enabled. + bool m_logEnabled; + + /// True if the performance timers are enabled. + bool m_timerEnabled; +}; + +/// A helper to first start a timer and then stop it when this helper goes out of scope. +/// @see rcContext +class rcScopedTimer +{ +public: + /// Constructs an instance and starts the timer. + /// @param[in] ctx The context to use. + /// @param[in] label The category of the timer. + inline rcScopedTimer(rcContext* ctx, const rcTimerLabel label) : m_ctx(ctx), m_label(label) { m_ctx->startTimer(m_label); } + inline ~rcScopedTimer() { m_ctx->stopTimer(m_label); } + +private: + // Explicitly disabled copy constructor and copy assignment operator. + rcScopedTimer(const rcScopedTimer&); + rcScopedTimer& operator=(const rcScopedTimer&); + + rcContext* const m_ctx; + const rcTimerLabel m_label; +}; + +/// Specifies a configuration to use when performing Recast builds. +/// @ingroup recast +struct rcConfig +{ + /// The width of the field along the x-axis. [Limit: >= 0] [Units: vx] + int width; + + /// The height of the field along the z-axis. [Limit: >= 0] [Units: vx] + int height; + + /// The width/height size of tile's on the xz-plane. [Limit: >= 0] [Units: vx] + int tileSize; + + /// The size of the non-navigable border around the heightfield. [Limit: >=0] [Units: vx] + int borderSize; + + /// The xz-plane cell size to use for fields. [Limit: > 0] [Units: wu] + float cs; + + /// The y-axis cell size to use for fields. [Limit: > 0] [Units: wu] + float ch; + + /// The minimum bounds of the field's AABB. [(x, y, z)] [Units: wu] + float bmin[3]; + + /// The maximum bounds of the field's AABB. [(x, y, z)] [Units: wu] + float bmax[3]; + + /// The maximum slope that is considered walkable. [Limits: 0 <= value < 90] [Units: Degrees] + float walkableSlopeAngle; + + /// Minimum floor to 'ceiling' height that will still allow the floor area to + /// be considered walkable. [Limit: >= 3] [Units: vx] + int walkableHeight; + + /// Maximum ledge height that is considered to still be traversable. [Limit: >=0] [Units: vx] + int walkableClimb; + + /// The distance to erode/shrink the walkable area of the heightfield away from + /// obstructions. [Limit: >=0] [Units: vx] + int walkableRadius; + + /// The maximum allowed length for contour edges along the border of the mesh. [Limit: >=0] [Units: vx] + int maxEdgeLen; + + /// The maximum distance a simplified contour's border edges should deviate + /// the original raw contour. [Limit: >=0] [Units: vx] + float maxSimplificationError; + + /// The minimum number of cells allowed to form isolated island areas. [Limit: >=0] [Units: vx] + int minRegionArea; + + /// Any regions with a span count smaller than this value will, if possible, + /// be merged with larger regions. [Limit: >=0] [Units: vx] + int mergeRegionArea; + + /// The maximum number of vertices allowed for polygons generated during the + /// contour to polygon conversion process. [Limit: >= 3] + int maxVertsPerPoly; + + /// Sets the sampling distance to use when generating the detail mesh. + /// (For height detail only.) [Limits: 0 or >= 0.9] [Units: wu] + float detailSampleDist; + + /// The maximum distance the detail mesh surface should deviate from heightfield + /// data. (For height detail only.) [Limit: >=0] [Units: wu] + float detailSampleMaxError; +}; + +/// Defines the number of bits allocated to rcSpan::smin and rcSpan::smax. +static const int RC_SPAN_HEIGHT_BITS = 13; +/// Defines the maximum value for rcSpan::smin and rcSpan::smax. +static const int RC_SPAN_MAX_HEIGHT = (1 << RC_SPAN_HEIGHT_BITS) - 1; + +/// The number of spans allocated per span spool. +/// @see rcSpanPool +static const int RC_SPANS_PER_POOL = 2048; + +/// Represents a span in a heightfield. +/// @see rcHeightfield +struct rcSpan +{ + unsigned int smin : RC_SPAN_HEIGHT_BITS; ///< The lower limit of the span. (Inclusive) [Limit: < #smax] + unsigned int smax : RC_SPAN_HEIGHT_BITS; ///< The upper limit of the span. (Exclusive) [Limit: <= #RC_SPAN_MAX_HEIGHT] + unsigned int area : 6; ///< The area id assigned to the span. + rcSpan* next; ///< The next span higher up in column. +}; + +/// A memory pool used for quick allocation of spans within a heightfield. +/// @see rcHeightfield +struct rcSpanPool +{ + rcSpanPool* next; ///< The next span pool. + rcSpan items[RC_SPANS_PER_POOL]; ///< Array of spans in the pool. +}; + +/// A dynamic heightfield representing obstructed space. +/// @ingroup recast +struct rcHeightfield +{ + rcHeightfield(); + ~rcHeightfield(); + + int width; ///< The width of the heightfield. (Along the x-axis in cell units.) + int height; ///< The height of the heightfield. (Along the z-axis in cell units.) + float bmin[3]; ///< The minimum bounds in world space. [(x, y, z)] + float bmax[3]; ///< The maximum bounds in world space. [(x, y, z)] + float cs; ///< The size of each cell. (On the xz-plane.) + float ch; ///< The height of each cell. (The minimum increment along the y-axis.) + rcSpan** spans; ///< Heightfield of spans (width*height). + + // memory pool for rcSpan instances. + rcSpanPool* pools; ///< Linked list of span pools. + rcSpan* freelist; ///< The next free span. + +private: + // Explicitly-disabled copy constructor and copy assignment operator. + rcHeightfield(const rcHeightfield&); + rcHeightfield& operator=(const rcHeightfield&); +}; + +/// Provides information on the content of a cell column in a compact heightfield. +struct rcCompactCell +{ + unsigned int index : 24; ///< Index to the first span in the column. + unsigned int count : 8; ///< Number of spans in the column. +}; + +/// Represents a span of unobstructed space within a compact heightfield. +struct rcCompactSpan +{ + unsigned short y; ///< The lower extent of the span. (Measured from the heightfield's base.) + unsigned short reg; ///< The id of the region the span belongs to. (Or zero if not in a region.) + unsigned int con : 24; ///< Packed neighbor connection data. + unsigned int h : 8; ///< The height of the span. (Measured from #y.) +}; + +/// A compact, static heightfield representing unobstructed space. +/// @ingroup recast +struct rcCompactHeightfield +{ + rcCompactHeightfield(); + ~rcCompactHeightfield(); + + int width; ///< The width of the heightfield. (Along the x-axis in cell units.) + int height; ///< The height of the heightfield. (Along the z-axis in cell units.) + int spanCount; ///< The number of spans in the heightfield. + int walkableHeight; ///< The walkable height used during the build of the field. (See: rcConfig::walkableHeight) + int walkableClimb; ///< The walkable climb used during the build of the field. (See: rcConfig::walkableClimb) + int borderSize; ///< The AABB border size used during the build of the field. (See: rcConfig::borderSize) + unsigned short maxDistance; ///< The maximum distance value of any span within the field. + unsigned short maxRegions; ///< The maximum region id of any span within the field. + float bmin[3]; ///< The minimum bounds in world space. [(x, y, z)] + float bmax[3]; ///< The maximum bounds in world space. [(x, y, z)] + float cs; ///< The size of each cell. (On the xz-plane.) + float ch; ///< The height of each cell. (The minimum increment along the y-axis.) + rcCompactCell* cells; ///< Array of cells. [Size: #width*#height] + rcCompactSpan* spans; ///< Array of spans. [Size: #spanCount] + unsigned short* dist; ///< Array containing border distance data. [Size: #spanCount] + unsigned char* areas; ///< Array containing area id data. [Size: #spanCount] + +private: + // Explicitly-disabled copy constructor and copy assignment operator. + rcCompactHeightfield(const rcCompactHeightfield&); + rcCompactHeightfield& operator=(const rcCompactHeightfield&); +}; + +/// Represents a heightfield layer within a layer set. +/// @see rcHeightfieldLayerSet +struct rcHeightfieldLayer +{ + float bmin[3]; ///< The minimum bounds in world space. [(x, y, z)] + float bmax[3]; ///< The maximum bounds in world space. [(x, y, z)] + float cs; ///< The size of each cell. (On the xz-plane.) + float ch; ///< The height of each cell. (The minimum increment along the y-axis.) + int width; ///< The width of the heightfield. (Along the x-axis in cell units.) + int height; ///< The height of the heightfield. (Along the z-axis in cell units.) + int minx; ///< The minimum x-bounds of usable data. + int maxx; ///< The maximum x-bounds of usable data. + int miny; ///< The minimum y-bounds of usable data. (Along the z-axis.) + int maxy; ///< The maximum y-bounds of usable data. (Along the z-axis.) + int hmin; ///< The minimum height bounds of usable data. (Along the y-axis.) + int hmax; ///< The maximum height bounds of usable data. (Along the y-axis.) + unsigned char* heights; ///< The heightfield. [Size: width * height] + unsigned char* areas; ///< Area ids. [Size: Same as #heights] + unsigned char* cons; ///< Packed neighbor connection information. [Size: Same as #heights] +}; + +/// Represents a set of heightfield layers. +/// @ingroup recast +/// @see rcAllocHeightfieldLayerSet, rcFreeHeightfieldLayerSet +struct rcHeightfieldLayerSet +{ + rcHeightfieldLayerSet(); + ~rcHeightfieldLayerSet(); + + rcHeightfieldLayer* layers; ///< The layers in the set. [Size: #nlayers] + int nlayers; ///< The number of layers in the set. + +private: + // Explicitly-disabled copy constructor and copy assignment operator. + rcHeightfieldLayerSet(const rcHeightfieldLayerSet&); + rcHeightfieldLayerSet& operator=(const rcHeightfieldLayerSet&); +}; + +/// Represents a simple, non-overlapping contour in field space. +struct rcContour +{ + int* verts; ///< Simplified contour vertex and connection data. [Size: 4 * #nverts] + int nverts; ///< The number of vertices in the simplified contour. + int* rverts; ///< Raw contour vertex and connection data. [Size: 4 * #nrverts] + int nrverts; ///< The number of vertices in the raw contour. + unsigned short reg; ///< The region id of the contour. + unsigned char area; ///< The area id of the contour. +}; + +/// Represents a group of related contours. +/// @ingroup recast +struct rcContourSet +{ + rcContourSet(); + ~rcContourSet(); + + rcContour* conts; ///< An array of the contours in the set. [Size: #nconts] + int nconts; ///< The number of contours in the set. + float bmin[3]; ///< The minimum bounds in world space. [(x, y, z)] + float bmax[3]; ///< The maximum bounds in world space. [(x, y, z)] + float cs; ///< The size of each cell. (On the xz-plane.) + float ch; ///< The height of each cell. (The minimum increment along the y-axis.) + int width; ///< The width of the set. (Along the x-axis in cell units.) + int height; ///< The height of the set. (Along the z-axis in cell units.) + int borderSize; ///< The AABB border size used to generate the source data from which the contours were derived. + float maxError; ///< The max edge error that this contour set was simplified with. + +private: + // Explicitly-disabled copy constructor and copy assignment operator. + rcContourSet(const rcContourSet&); + rcContourSet& operator=(const rcContourSet&); +}; + +/// Represents a polygon mesh suitable for use in building a navigation mesh. +/// @ingroup recast +struct rcPolyMesh +{ + rcPolyMesh(); + ~rcPolyMesh(); + + unsigned short* verts; ///< The mesh vertices. [Form: (x, y, z) * #nverts] + unsigned short* polys; ///< Polygon and neighbor data. [Length: #maxpolys * 2 * #nvp] + unsigned short* regs; ///< The region id assigned to each polygon. [Length: #maxpolys] + unsigned short* flags; ///< The user defined flags for each polygon. [Length: #maxpolys] + unsigned char* areas; ///< The area id assigned to each polygon. [Length: #maxpolys] + int nverts; ///< The number of vertices. + int npolys; ///< The number of polygons. + int maxpolys; ///< The number of allocated polygons. + int nvp; ///< The maximum number of vertices per polygon. + float bmin[3]; ///< The minimum bounds in world space. [(x, y, z)] + float bmax[3]; ///< The maximum bounds in world space. [(x, y, z)] + float cs; ///< The size of each cell. (On the xz-plane.) + float ch; ///< The height of each cell. (The minimum increment along the y-axis.) + int borderSize; ///< The AABB border size used to generate the source data from which the mesh was derived. + float maxEdgeError; ///< The max error of the polygon edges in the mesh. + +private: + // Explicitly-disabled copy constructor and copy assignment operator. + rcPolyMesh(const rcPolyMesh&); + rcPolyMesh& operator=(const rcPolyMesh&); +}; + +/// Contains triangle meshes that represent detailed height data associated +/// with the polygons in its associated polygon mesh object. +/// @ingroup recast +struct rcPolyMeshDetail +{ + rcPolyMeshDetail(); + + unsigned int* meshes; ///< The sub-mesh data. [Size: 4*#nmeshes] + float* verts; ///< The mesh vertices. [Size: 3*#nverts] + unsigned char* tris; ///< The mesh triangles. [Size: 4*#ntris] + int nmeshes; ///< The number of sub-meshes defined by #meshes. + int nverts; ///< The number of vertices in #verts. + int ntris; ///< The number of triangles in #tris. + +private: + // Explicitly-disabled copy constructor and copy assignment operator. + rcPolyMeshDetail(const rcPolyMeshDetail&); + rcPolyMeshDetail& operator=(const rcPolyMeshDetail&); +}; + +/// @name Allocation Functions +/// Functions used to allocate and de-allocate Recast objects. +/// @see rcAllocSetCustom +/// @{ + +/// Allocates a heightfield object using the Recast allocator. +/// @return A heightfield that is ready for initialization, or null on failure. +/// @ingroup recast +/// @see rcCreateHeightfield, rcFreeHeightField +rcHeightfield* rcAllocHeightfield(); + +/// Frees the specified heightfield object using the Recast allocator. +/// @param[in] heightfield A heightfield allocated using #rcAllocHeightfield +/// @ingroup recast +/// @see rcAllocHeightfield +void rcFreeHeightField(rcHeightfield* heightfield); + +/// Allocates a compact heightfield object using the Recast allocator. +/// @return A compact heightfield that is ready for initialization, or null on failure. +/// @ingroup recast +/// @see rcBuildCompactHeightfield, rcFreeCompactHeightfield +rcCompactHeightfield* rcAllocCompactHeightfield(); + +/// Frees the specified compact heightfield object using the Recast allocator. +/// @param[in] compactHeightfield A compact heightfield allocated using #rcAllocCompactHeightfield +/// @ingroup recast +/// @see rcAllocCompactHeightfield +void rcFreeCompactHeightfield(rcCompactHeightfield* compactHeightfield); + +/// Allocates a heightfield layer set using the Recast allocator. +/// @return A heightfield layer set that is ready for initialization, or null on failure. +/// @ingroup recast +/// @see rcBuildHeightfieldLayers, rcFreeHeightfieldLayerSet +rcHeightfieldLayerSet* rcAllocHeightfieldLayerSet(); + +/// Frees the specified heightfield layer set using the Recast allocator. +/// @param[in] layerSet A heightfield layer set allocated using #rcAllocHeightfieldLayerSet +/// @ingroup recast +/// @see rcAllocHeightfieldLayerSet +void rcFreeHeightfieldLayerSet(rcHeightfieldLayerSet* layerSet); + +/// Allocates a contour set object using the Recast allocator. +/// @return A contour set that is ready for initialization, or null on failure. +/// @ingroup recast +/// @see rcBuildContours, rcFreeContourSet +rcContourSet* rcAllocContourSet(); + +/// Frees the specified contour set using the Recast allocator. +/// @param[in] contourSet A contour set allocated using #rcAllocContourSet +/// @ingroup recast +/// @see rcAllocContourSet +void rcFreeContourSet(rcContourSet* contourSet); + +/// Allocates a polygon mesh object using the Recast allocator. +/// @return A polygon mesh that is ready for initialization, or null on failure. +/// @ingroup recast +/// @see rcBuildPolyMesh, rcFreePolyMesh +rcPolyMesh* rcAllocPolyMesh(); + +/// Frees the specified polygon mesh using the Recast allocator. +/// @param[in] polyMesh A polygon mesh allocated using #rcAllocPolyMesh +/// @ingroup recast +/// @see rcAllocPolyMesh +void rcFreePolyMesh(rcPolyMesh* polyMesh); + +/// Allocates a detail mesh object using the Recast allocator. +/// @return A detail mesh that is ready for initialization, or null on failure. +/// @ingroup recast +/// @see rcBuildPolyMeshDetail, rcFreePolyMeshDetail +rcPolyMeshDetail* rcAllocPolyMeshDetail(); + +/// Frees the specified detail mesh using the Recast allocator. +/// @param[in] detailMesh A detail mesh allocated using #rcAllocPolyMeshDetail +/// @ingroup recast +/// @see rcAllocPolyMeshDetail +void rcFreePolyMeshDetail(rcPolyMeshDetail* detailMesh); + +/// @} + +/// Heightfield border flag. +/// If a heightfield region ID has this bit set, then the region is a border +/// region and its spans are considered un-walkable. +/// (Used during the region and contour build process.) +/// @see rcCompactSpan::reg +static const unsigned short RC_BORDER_REG = 0x8000; + +/// Polygon touches multiple regions. +/// If a polygon has this region ID it was merged with or created +/// from polygons of different regions during the polymesh +/// build step that removes redundant border vertices. +/// (Used during the polymesh and detail polymesh build processes) +/// @see rcPolyMesh::regs +static const unsigned short RC_MULTIPLE_REGS = 0; + +/// Border vertex flag. +/// If a region ID has this bit set, then the associated element lies on +/// a tile border. If a contour vertex's region ID has this bit set, the +/// vertex will later be removed in order to match the segments and vertices +/// at tile boundaries. +/// (Used during the build process.) +/// @see rcCompactSpan::reg, #rcContour::verts, #rcContour::rverts +static const int RC_BORDER_VERTEX = 0x10000; + +/// Area border flag. +/// If a region ID has this bit set, then the associated element lies on +/// the border of an area. +/// (Used during the region and contour build process.) +/// @see rcCompactSpan::reg, #rcContour::verts, #rcContour::rverts +static const int RC_AREA_BORDER = 0x20000; + +/// Contour build flags. +/// @see rcBuildContours +enum rcBuildContoursFlags +{ + RC_CONTOUR_TESS_WALL_EDGES = 0x01, ///< Tessellate solid (impassable) edges during contour simplification. + RC_CONTOUR_TESS_AREA_EDGES = 0x02 ///< Tessellate edges between areas during contour simplification. +}; + +/// Applied to the region id field of contour vertices in order to extract the region id. +/// The region id field of a vertex may have several flags applied to it. So the +/// fields value can't be used directly. +/// @see rcContour::verts, rcContour::rverts +static const int RC_CONTOUR_REG_MASK = 0xffff; + +/// An value which indicates an invalid index within a mesh. +/// @note This does not necessarily indicate an error. +/// @see rcPolyMesh::polys +static const unsigned short RC_MESH_NULL_IDX = 0xffff; + +/// Represents the null area. +/// When a data element is given this value it is considered to no longer be +/// assigned to a usable area. (E.g. It is un-walkable.) +static const unsigned char RC_NULL_AREA = 0; + +/// The default area id used to indicate a walkable polygon. +/// This is also the maximum allowed area id, and the only non-null area id +/// recognized by some steps in the build process. +static const unsigned char RC_WALKABLE_AREA = 63; + +/// The value returned by #rcGetCon if the specified direction is not connected +/// to another span. (Has no neighbor.) +static const int RC_NOT_CONNECTED = 0x3f; + +/// @name General helper functions +/// @{ + +/// Swaps the values of the two parameters. +/// @param[in,out] a Value A +/// @param[in,out] b Value B +template inline void rcSwap(T& a, T& b) { T t = a; a = b; b = t; } + +/// Returns the minimum of two values. +/// @param[in] a Value A +/// @param[in] b Value B +/// @return The minimum of the two values. +template inline T rcMin(T a, T b) { return a < b ? a : b; } + +/// Returns the maximum of two values. +/// @param[in] a Value A +/// @param[in] b Value B +/// @return The maximum of the two values. +template inline T rcMax(T a, T b) { return a > b ? a : b; } + +/// Returns the absolute value. +/// @param[in] a The value. +/// @return The absolute value of the specified value. +template inline T rcAbs(T a) { return a < 0 ? -a : a; } + +/// Returns the square of the value. +/// @param[in] a The value. +/// @return The square of the value. +template inline T rcSqr(T a) { return a * a; } + +/// Clamps the value to the specified range. +/// @param[in] value The value to clamp. +/// @param[in] minInclusive The minimum permitted return value. +/// @param[in] maxInclusive The maximum permitted return value. +/// @return The value, clamped to the specified range. +template inline T rcClamp(T value, T minInclusive, T maxInclusive) +{ + return value < minInclusive ? minInclusive: (value > maxInclusive ? maxInclusive : value); +} + +/// Returns the square root of the value. +/// @param[in] x The value. +/// @return The square root of the vlaue. +float rcSqrt(float x); + +/// @} +/// @name Vector helper functions. +/// @{ + +/// Derives the cross product of two vectors. (@p v1 x @p v2) +/// @param[out] dest The cross product. [(x, y, z)] +/// @param[in] v1 A Vector [(x, y, z)] +/// @param[in] v2 A vector [(x, y, z)] +inline void rcVcross(float* dest, const float* v1, const float* v2) +{ + dest[0] = v1[1]*v2[2] - v1[2]*v2[1]; + dest[1] = v1[2]*v2[0] - v1[0]*v2[2]; + dest[2] = v1[0]*v2[1] - v1[1]*v2[0]; +} + +/// Derives the dot product of two vectors. (@p v1 . @p v2) +/// @param[in] v1 A Vector [(x, y, z)] +/// @param[in] v2 A vector [(x, y, z)] +/// @return The dot product. +inline float rcVdot(const float* v1, const float* v2) +{ + return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]; +} + +/// Performs a scaled vector addition. (@p v1 + (@p v2 * @p s)) +/// @param[out] dest The result vector. [(x, y, z)] +/// @param[in] v1 The base vector. [(x, y, z)] +/// @param[in] v2 The vector to scale and add to @p v1. [(x, y, z)] +/// @param[in] s The amount to scale @p v2 by before adding to @p v1. +inline void rcVmad(float* dest, const float* v1, const float* v2, const float s) +{ + dest[0] = v1[0]+v2[0]*s; + dest[1] = v1[1]+v2[1]*s; + dest[2] = v1[2]+v2[2]*s; +} + +/// Performs a vector addition. (@p v1 + @p v2) +/// @param[out] dest The result vector. [(x, y, z)] +/// @param[in] v1 The base vector. [(x, y, z)] +/// @param[in] v2 The vector to add to @p v1. [(x, y, z)] +inline void rcVadd(float* dest, const float* v1, const float* v2) +{ + dest[0] = v1[0]+v2[0]; + dest[1] = v1[1]+v2[1]; + dest[2] = v1[2]+v2[2]; +} + +/// Performs a vector subtraction. (@p v1 - @p v2) +/// @param[out] dest The result vector. [(x, y, z)] +/// @param[in] v1 The base vector. [(x, y, z)] +/// @param[in] v2 The vector to subtract from @p v1. [(x, y, z)] +inline void rcVsub(float* dest, const float* v1, const float* v2) +{ + dest[0] = v1[0]-v2[0]; + dest[1] = v1[1]-v2[1]; + dest[2] = v1[2]-v2[2]; +} + +/// Selects the minimum value of each element from the specified vectors. +/// @param[in,out] mn A vector. (Will be updated with the result.) [(x, y, z)] +/// @param[in] v A vector. [(x, y, z)] +inline void rcVmin(float* mn, const float* v) +{ + mn[0] = rcMin(mn[0], v[0]); + mn[1] = rcMin(mn[1], v[1]); + mn[2] = rcMin(mn[2], v[2]); +} + +/// Selects the maximum value of each element from the specified vectors. +/// @param[in,out] mx A vector. (Will be updated with the result.) [(x, y, z)] +/// @param[in] v A vector. [(x, y, z)] +inline void rcVmax(float* mx, const float* v) +{ + mx[0] = rcMax(mx[0], v[0]); + mx[1] = rcMax(mx[1], v[1]); + mx[2] = rcMax(mx[2], v[2]); +} + +/// Performs a vector copy. +/// @param[out] dest The result. [(x, y, z)] +/// @param[in] v The vector to copy. [(x, y, z)] +inline void rcVcopy(float* dest, const float* v) +{ + dest[0] = v[0]; + dest[1] = v[1]; + dest[2] = v[2]; +} + +/// Returns the distance between two points. +/// @param[in] v1 A point. [(x, y, z)] +/// @param[in] v2 A point. [(x, y, z)] +/// @return The distance between the two points. +inline float rcVdist(const float* v1, const float* v2) +{ + float dx = v2[0] - v1[0]; + float dy = v2[1] - v1[1]; + float dz = v2[2] - v1[2]; + return rcSqrt(dx*dx + dy*dy + dz*dz); +} + +/// Returns the square of the distance between two points. +/// @param[in] v1 A point. [(x, y, z)] +/// @param[in] v2 A point. [(x, y, z)] +/// @return The square of the distance between the two points. +inline float rcVdistSqr(const float* v1, const float* v2) +{ + float dx = v2[0] - v1[0]; + float dy = v2[1] - v1[1]; + float dz = v2[2] - v1[2]; + return dx*dx + dy*dy + dz*dz; +} + +/// Normalizes the vector. +/// @param[in,out] v The vector to normalize. [(x, y, z)] +inline void rcVnormalize(float* v) +{ + float d = 1.0f / rcSqrt(rcSqr(v[0]) + rcSqr(v[1]) + rcSqr(v[2])); + v[0] *= d; + v[1] *= d; + v[2] *= d; +} + +/// @} +/// @name Heightfield Functions +/// @see rcHeightfield +/// @{ + +/// Calculates the bounding box of an array of vertices. +/// @ingroup recast +/// @param[in] verts An array of vertices. [(x, y, z) * @p nv] +/// @param[in] numVerts The number of vertices in the @p verts array. +/// @param[out] minBounds The minimum bounds of the AABB. [(x, y, z)] [Units: wu] +/// @param[out] maxBounds The maximum bounds of the AABB. [(x, y, z)] [Units: wu] +void rcCalcBounds(const float* verts, int numVerts, float* minBounds, float* maxBounds); + +/// Calculates the grid size based on the bounding box and grid cell size. +/// @ingroup recast +/// @param[in] minBounds The minimum bounds of the AABB. [(x, y, z)] [Units: wu] +/// @param[in] maxBounds The maximum bounds of the AABB. [(x, y, z)] [Units: wu] +/// @param[in] cellSize The xz-plane cell size. [Limit: > 0] [Units: wu] +/// @param[out] sizeX The width along the x-axis. [Limit: >= 0] [Units: vx] +/// @param[out] sizeZ The height along the z-axis. [Limit: >= 0] [Units: vx] +void rcCalcGridSize(const float* minBounds, const float* maxBounds, float cellSize, int* sizeX, int* sizeZ); + +/// Initializes a new heightfield. +/// See the #rcConfig documentation for more information on the configuration parameters. +/// +/// @see rcAllocHeightfield, rcHeightfield +/// @ingroup recast +/// +/// @param[in,out] context The build context to use during the operation. +/// @param[in,out] heightfield The allocated heightfield to initialize. +/// @param[in] sizeX The width of the field along the x-axis. [Limit: >= 0] [Units: vx] +/// @param[in] sizeZ The height of the field along the z-axis. [Limit: >= 0] [Units: vx] +/// @param[in] minBounds The minimum bounds of the field's AABB. [(x, y, z)] [Units: wu] +/// @param[in] maxBounds The maximum bounds of the field's AABB. [(x, y, z)] [Units: wu] +/// @param[in] cellSize The xz-plane cell size to use for the field. [Limit: > 0] [Units: wu] +/// @param[in] cellHeight The y-axis cell size to use for field. [Limit: > 0] [Units: wu] +/// @returns True if the operation completed successfully. +bool rcCreateHeightfield(rcContext* context, rcHeightfield& heightfield, int sizeX, int sizeZ, + const float* minBounds, const float* maxBounds, + float cellSize, float cellHeight); + +/// Sets the area id of all triangles with a slope below the specified value +/// to #RC_WALKABLE_AREA. +/// +/// Only sets the area id's for the walkable triangles. Does not alter the +/// area id's for un-walkable triangles. +/// +/// See the #rcConfig documentation for more information on the configuration parameters. +/// +/// @see rcHeightfield, rcClearUnwalkableTriangles, rcRasterizeTriangles +/// +/// @ingroup recast +/// @param[in,out] context The build context to use during the operation. +/// @param[in] walkableSlopeAngle The maximum slope that is considered walkable. +/// [Limits: 0 <= value < 90] [Units: Degrees] +/// @param[in] verts The vertices. [(x, y, z) * @p nv] +/// @param[in] numVerts The number of vertices. +/// @param[in] tris The triangle vertex indices. [(vertA, vertB, vertC) * @p nt] +/// @param[in] numTris The number of triangles. +/// @param[out] triAreaIDs The triangle area ids. [Length: >= @p nt] +void rcMarkWalkableTriangles(rcContext* context, float walkableSlopeAngle, const float* verts, int numVerts, + const int* tris, int numTris, unsigned char* triAreaIDs); + +/// Sets the area id of all triangles with a slope greater than or equal to the specified value to #RC_NULL_AREA. +/// +/// Only sets the area id's for the un-walkable triangles. Does not alter the +/// area id's for walkable triangles. +/// +/// See the #rcConfig documentation for more information on the configuration parameters. +/// +/// @see rcHeightfield, rcClearUnwalkableTriangles, rcRasterizeTriangles +/// +/// @ingroup recast +/// @param[in,out] context The build context to use during the operation. +/// @param[in] walkableSlopeAngle The maximum slope that is considered walkable. +/// [Limits: 0 <= value < 90] [Units: Degrees] +/// @param[in] verts The vertices. [(x, y, z) * @p nv] +/// @param[in] numVerts The number of vertices. +/// @param[in] tris The triangle vertex indices. [(vertA, vertB, vertC) * @p nt] +/// @param[in] numTris The number of triangles. +/// @param[out] triAreaIDs The triangle area ids. [Length: >= @p nt] +void rcClearUnwalkableTriangles(rcContext* context, float walkableSlopeAngle, const float* verts, int numVerts, + const int* tris, int numTris, unsigned char* triAreaIDs); + +/// Adds a span to the specified heightfield. +/// +/// The span addition can be set to favor flags. If the span is merged to +/// another span and the new @p spanMax is within @p flagMergeThreshold units +/// from the existing span, the span flags are merged. +/// +/// @ingroup recast +/// @param[in,out] context The build context to use during the operation. +/// @param[in,out] heightfield An initialized heightfield. +/// @param[in] x The column x index where the span is to be added. +/// [Limits: 0 <= value < rcHeightfield::width] +/// @param[in] z The column z index where the span is to be added. +/// [Limits: 0 <= value < rcHeightfield::height] +/// @param[in] spanMin The minimum height of the span. [Limit: < @p spanMax] [Units: vx] +/// @param[in] spanMax The maximum height of the span. [Limit: <= #RC_SPAN_MAX_HEIGHT] [Units: vx] +/// @param[in] areaID The area id of the span. [Limit: <= #RC_WALKABLE_AREA) +/// @param[in] flagMergeThreshold The merge threshold. [Limit: >= 0] [Units: vx] +/// @returns True if the operation completed successfully. +bool rcAddSpan(rcContext* context, rcHeightfield& heightfield, + int x, int z, + unsigned short spanMin, unsigned short spanMax, + unsigned char areaID, int flagMergeThreshold); + +/// Rasterizes a single triangle into the specified heightfield. +/// +/// Calling this for each triangle in a mesh is less efficient than calling rcRasterizeTriangles +/// +/// No spans will be added if the triangle does not overlap the heightfield grid. +/// +/// @see rcHeightfield +/// @ingroup recast +/// @param[in,out] context The build context to use during the operation. +/// @param[in] v0 Triangle vertex 0 [(x, y, z)] +/// @param[in] v1 Triangle vertex 1 [(x, y, z)] +/// @param[in] v2 Triangle vertex 2 [(x, y, z)] +/// @param[in] areaID The area id of the triangle. [Limit: <= #RC_WALKABLE_AREA] +/// @param[in,out] heightfield An initialized heightfield. +/// @param[in] flagMergeThreshold The distance where the walkable flag is favored over the non-walkable flag. +/// [Limit: >= 0] [Units: vx] +/// @returns True if the operation completed successfully. +bool rcRasterizeTriangle(rcContext* context, + const float* v0, const float* v1, const float* v2, + unsigned char areaID, rcHeightfield& heightfield, int flagMergeThreshold = 1); + +/// Rasterizes an indexed triangle mesh into the specified heightfield. +/// +/// Spans will only be added for triangles that overlap the heightfield grid. +/// +/// @see rcHeightfield +/// @ingroup recast +/// @param[in,out] context The build context to use during the operation. +/// @param[in] verts The vertices. [(x, y, z) * @p nv] +/// @param[in] numVerts The number of vertices. (unused) TODO (graham): Remove in next major release +/// @param[in] tris The triangle indices. [(vertA, vertB, vertC) * @p nt] +/// @param[in] triAreaIDs The area id's of the triangles. [Limit: <= #RC_WALKABLE_AREA] [Size: @p nt] +/// @param[in] numTris The number of triangles. +/// @param[in,out] heightfield An initialized heightfield. +/// @param[in] flagMergeThreshold The distance where the walkable flag is favored over the non-walkable flag. +/// [Limit: >= 0] [Units: vx] +/// @returns True if the operation completed successfully. +bool rcRasterizeTriangles(rcContext* context, + const float* verts, int numVerts, + const int* tris, const unsigned char* triAreaIDs, int numTris, + rcHeightfield& heightfield, int flagMergeThreshold = 1); + +/// Rasterizes an indexed triangle mesh into the specified heightfield. +/// +/// Spans will only be added for triangles that overlap the heightfield grid. +/// +/// @see rcHeightfield +/// @ingroup recast +/// @param[in,out] context The build context to use during the operation. +/// @param[in] verts The vertices. [(x, y, z) * @p nv] +/// @param[in] numVerts The number of vertices. (unused) TODO (graham): Remove in next major release +/// @param[in] tris The triangle indices. [(vertA, vertB, vertC) * @p nt] +/// @param[in] triAreaIDs The area id's of the triangles. [Limit: <= #RC_WALKABLE_AREA] [Size: @p nt] +/// @param[in] numTris The number of triangles. +/// @param[in,out] heightfield An initialized heightfield. +/// @param[in] flagMergeThreshold The distance where the walkable flag is favored over the non-walkable flag. +/// [Limit: >= 0] [Units: vx] +/// @returns True if the operation completed successfully. +bool rcRasterizeTriangles(rcContext* context, + const float* verts, int numVerts, + const unsigned short* tris, const unsigned char* triAreaIDs, int numTris, + rcHeightfield& heightfield, int flagMergeThreshold = 1); + +/// Rasterizes a triangle list into the specified heightfield. +/// +/// Expects each triangle to be specified as three sequential vertices of 3 floats. +/// +/// Spans will only be added for triangles that overlap the heightfield grid. +/// +/// @see rcHeightfield +/// @ingroup recast +/// @param[in,out] context The build context to use during the operation. +/// @param[in] verts The triangle vertices. [(ax, ay, az, bx, by, bz, cx, by, cx) * @p nt] +/// @param[in] triAreaIDs The area id's of the triangles. [Limit: <= #RC_WALKABLE_AREA] [Size: @p nt] +/// @param[in] numTris The number of triangles. +/// @param[in,out] heightfield An initialized heightfield. +/// @param[in] flagMergeThreshold The distance where the walkable flag is favored over the non-walkable flag. +/// [Limit: >= 0] [Units: vx] +/// @returns True if the operation completed successfully. +bool rcRasterizeTriangles(rcContext* context, + const float* verts, const unsigned char* triAreaIDs, int numTris, + rcHeightfield& heightfield, int flagMergeThreshold = 1); + +/// Marks non-walkable spans as walkable if their maximum is within @p walkableClimb of the span below them. +/// +/// This removes small obstacles and rasterization artifacts that the agent would be able to walk over +/// such as curbs. It also allows agents to move up terraced structures like stairs. +/// +/// Obstacle spans are marked walkable if: obstacleSpan.smax - walkableSpan.smax < walkableClimb +/// +/// @warning Will override the effect of #rcFilterLedgeSpans. If both filters are used, call #rcFilterLedgeSpans only after applying this filter. +/// +/// @see rcHeightfield, rcConfig +/// +/// @ingroup recast +/// @param[in,out] context The build context to use during the operation. +/// @param[in] walkableClimb Maximum ledge height that is considered to still be traversable. +/// [Limit: >=0] [Units: vx] +/// @param[in,out] heightfield A fully built heightfield. (All spans have been added.) +void rcFilterLowHangingWalkableObstacles(rcContext* context, int walkableClimb, rcHeightfield& heightfield); + +/// Marks spans that are ledges as not-walkable. +/// +/// A ledge is a span with one or more neighbors whose maximum is further away than @p walkableClimb +/// from the current span's maximum. +/// This method removes the impact of the overestimation of conservative voxelization +/// so the resulting mesh will not have regions hanging in the air over ledges. +/// +/// A span is a ledge if: rcAbs(currentSpan.smax - neighborSpan.smax) > walkableClimb +/// +/// @see rcHeightfield, rcConfig +/// +/// @ingroup recast +/// @param[in,out] context The build context to use during the operation. +/// @param[in] walkableHeight Minimum floor to 'ceiling' height that will still allow the floor area to +/// be considered walkable. [Limit: >= 3] [Units: vx] +/// @param[in] walkableClimb Maximum ledge height that is considered to still be traversable. +/// [Limit: >=0] [Units: vx] +/// @param[in,out] heightfield A fully built heightfield. (All spans have been added.) +void rcFilterLedgeSpans(rcContext* context, int walkableHeight, int walkableClimb, rcHeightfield& heightfield); + +/// Marks walkable spans as not walkable if the clearance above the span is less than the specified walkableHeight. +/// +/// For this filter, the clearance above the span is the distance from the span's +/// maximum to the minimum of the next higher span in the same column. +/// If there is no higher span in the column, the clearance is computed as the +/// distance from the top of the span to the maximum heightfield height. +/// +/// @see rcHeightfield, rcConfig +/// @ingroup recast +/// +/// @param[in,out] context The build context to use during the operation. +/// @param[in] walkableHeight Minimum floor to 'ceiling' height that will still allow the floor area to +/// be considered walkable. [Limit: >= 3] [Units: vx] +/// @param[in,out] heightfield A fully built heightfield. (All spans have been added.) +void rcFilterWalkableLowHeightSpans(rcContext* context, int walkableHeight, rcHeightfield& heightfield); + +/// Returns the number of spans contained in the specified heightfield. +/// @ingroup recast +/// @param[in,out] context The build context to use during the operation. +/// @param[in] heightfield An initialized heightfield. +/// @returns The number of spans in the heightfield. +int rcGetHeightFieldSpanCount(rcContext* context, const rcHeightfield& heightfield); + +/// @} +/// @name Compact Heightfield Functions +/// @see rcCompactHeightfield +/// @{ + +/// Builds a compact heightfield representing open space, from a heightfield representing solid space. +/// +/// This is just the beginning of the process of fully building a compact heightfield. +/// Various filters may be applied, then the distance field and regions built. +/// E.g: #rcBuildDistanceField and #rcBuildRegions +/// +/// See the #rcConfig documentation for more information on the configuration parameters. +/// +/// @see rcAllocCompactHeightfield, rcHeightfield, rcCompactHeightfield, rcConfig +/// @ingroup recast +/// +/// @param[in,out] context The build context to use during the operation. +/// @param[in] walkableHeight Minimum floor to 'ceiling' height that will still allow the floor area +/// to be considered walkable. [Limit: >= 3] [Units: vx] +/// @param[in] walkableClimb Maximum ledge height that is considered to still be traversable. +/// [Limit: >=0] [Units: vx] +/// @param[in] heightfield The heightfield to be compacted. +/// @param[out] compactHeightfield The resulting compact heightfield. (Must be pre-allocated.) +/// @returns True if the operation completed successfully. +bool rcBuildCompactHeightfield(rcContext* context, int walkableHeight, int walkableClimb, + const rcHeightfield& heightfield, rcCompactHeightfield& compactHeightfield); + +/// Erodes the walkable area within the heightfield by the specified radius. +/// +/// Basically, any spans that are closer to a boundary or obstruction than the specified radius +/// are marked as un-walkable. +/// +/// This method is usually called immediately after the heightfield has been built. +/// +/// @see rcCompactHeightfield, rcBuildCompactHeightfield, rcConfig::walkableRadius +/// @ingroup recast +/// +/// @param[in,out] context The build context to use during the operation. +/// @param[in] erosionRadius The radius of erosion. [Limits: 0 < value < 255] [Units: vx] +/// @param[in,out] compactHeightfield The populated compact heightfield to erode. +/// @returns True if the operation completed successfully. +bool rcErodeWalkableArea(rcContext* context, int erosionRadius, rcCompactHeightfield& compactHeightfield); + +/// Applies a median filter to walkable area types (based on area id), removing noise. +/// +/// This filter is usually applied after applying area id's using functions +/// such as #rcMarkBoxArea, #rcMarkConvexPolyArea, and #rcMarkCylinderArea. +/// +/// @see rcCompactHeightfield +/// @ingroup recast +/// +/// @param[in,out] context The build context to use during the operation. +/// @param[in,out] compactHeightfield A populated compact heightfield. +/// @returns True if the operation completed successfully. +bool rcMedianFilterWalkableArea(rcContext* context, rcCompactHeightfield& compactHeightfield); + +/// Applies an area id to all spans within the specified bounding box. (AABB) +/// +/// @see rcCompactHeightfield, rcMedianFilterWalkableArea +/// @ingroup recast +/// +/// @param[in,out] context The build context to use during the operation. +/// @param[in] boxMinBounds The minimum extents of the bounding box. [(x, y, z)] [Units: wu] +/// @param[in] boxMaxBounds The maximum extents of the bounding box. [(x, y, z)] [Units: wu] +/// @param[in] areaId The area id to apply. [Limit: <= #RC_WALKABLE_AREA] +/// @param[in,out] compactHeightfield A populated compact heightfield. +void rcMarkBoxArea(rcContext* context, const float* boxMinBounds, const float* boxMaxBounds, unsigned char areaId, + rcCompactHeightfield& compactHeightfield); + +/// Applies the area id to the all spans within the specified convex polygon. +/// +/// The value of spacial parameters are in world units. +/// +/// The y-values of the polygon vertices are ignored. So the polygon is effectively +/// projected onto the xz-plane, translated to @p minY, and extruded to @p maxY. +/// +/// @see rcCompactHeightfield, rcMedianFilterWalkableArea +/// @ingroup recast +/// +/// @param[in,out] context The build context to use during the operation. +/// @param[in] verts The vertices of the polygon [For: (x, y, z) * @p numVerts] +/// @param[in] numVerts The number of vertices in the polygon. +/// @param[in] minY The height of the base of the polygon. [Units: wu] +/// @param[in] maxY The height of the top of the polygon. [Units: wu] +/// @param[in] areaId The area id to apply. [Limit: <= #RC_WALKABLE_AREA] +/// @param[in,out] compactHeightfield A populated compact heightfield. +void rcMarkConvexPolyArea(rcContext* context, const float* verts, int numVerts, + float minY, float maxY, unsigned char areaId, + rcCompactHeightfield& compactHeightfield); + +/// Expands a convex polygon along its vertex normals by the given offset amount. +/// Inserts extra vertices to bevel sharp corners. +/// +/// Helper function to offset convex polygons for rcMarkConvexPolyArea. +/// +/// @ingroup recast +/// +/// @param[in] verts The vertices of the polygon [Form: (x, y, z) * @p numVerts] +/// @param[in] numVerts The number of vertices in the polygon. +/// @param[in] offset How much to offset the polygon by. [Units: wu] +/// @param[out] outVerts The offset vertices (should hold up to 2 * @p numVerts) [Form: (x, y, z) * return value] +/// @param[in] maxOutVerts The max number of vertices that can be stored to @p outVerts. +/// @returns Number of vertices in the offset polygon or 0 if too few vertices in @p outVerts. +int rcOffsetPoly(const float* verts, int numVerts, float offset, float* outVerts, int maxOutVerts); + +/// Applies the area id to all spans within the specified y-axis-aligned cylinder. +/// +/// @see rcCompactHeightfield, rcMedianFilterWalkableArea +/// +/// @ingroup recast +/// +/// @param[in,out] context The build context to use during the operation. +/// @param[in] position The center of the base of the cylinder. [Form: (x, y, z)] [Units: wu] +/// @param[in] radius The radius of the cylinder. [Units: wu] [Limit: > 0] +/// @param[in] height The height of the cylinder. [Units: wu] [Limit: > 0] +/// @param[in] areaId The area id to apply. [Limit: <= #RC_WALKABLE_AREA] +/// @param[in,out] compactHeightfield A populated compact heightfield. +void rcMarkCylinderArea(rcContext* context, const float* position, float radius, float height, + unsigned char areaId, rcCompactHeightfield& compactHeightfield); + +/// Builds the distance field for the specified compact heightfield. +/// @ingroup recast +/// @param[in,out] ctx The build context to use during the operation. +/// @param[in,out] chf A populated compact heightfield. +/// @returns True if the operation completed successfully. +bool rcBuildDistanceField(rcContext* ctx, rcCompactHeightfield& chf); + +/// Builds region data for the heightfield using watershed partitioning. +/// @ingroup recast +/// @param[in,out] ctx The build context to use during the operation. +/// @param[in,out] chf A populated compact heightfield. +/// @param[in] borderSize The size of the non-navigable border around the heightfield. +/// [Limit: >=0] [Units: vx] +/// @param[in] minRegionArea The minimum number of cells allowed to form isolated island areas. +/// [Limit: >=0] [Units: vx]. +/// @param[in] mergeRegionArea Any regions with a span count smaller than this value will, if possible, +/// be merged with larger regions. [Limit: >=0] [Units: vx] +/// @returns True if the operation completed successfully. +bool rcBuildRegions(rcContext* ctx, rcCompactHeightfield& chf, int borderSize, int minRegionArea, int mergeRegionArea); + +/// Builds region data for the heightfield by partitioning the heightfield in non-overlapping layers. +/// @ingroup recast +/// @param[in,out] ctx The build context to use during the operation. +/// @param[in,out] chf A populated compact heightfield. +/// @param[in] borderSize The size of the non-navigable border around the heightfield. +/// [Limit: >=0] [Units: vx] +/// @param[in] minRegionArea The minimum number of cells allowed to form isolated island areas. +/// [Limit: >=0] [Units: vx]. +/// @returns True if the operation completed successfully. +bool rcBuildLayerRegions(rcContext* ctx, rcCompactHeightfield& chf, int borderSize, int minRegionArea); + +/// Builds region data for the heightfield using simple monotone partitioning. +/// @ingroup recast +/// @param[in,out] ctx The build context to use during the operation. +/// @param[in,out] chf A populated compact heightfield. +/// @param[in] borderSize The size of the non-navigable border around the heightfield. +/// [Limit: >=0] [Units: vx] +/// @param[in] minRegionArea The minimum number of cells allowed to form isolated island areas. +/// [Limit: >=0] [Units: vx]. +/// @param[in] mergeRegionArea Any regions with a span count smaller than this value will, if possible, +/// be merged with larger regions. [Limit: >=0] [Units: vx] +/// @returns True if the operation completed successfully. +bool rcBuildRegionsMonotone(rcContext* ctx, rcCompactHeightfield& chf, + int borderSize, int minRegionArea, int mergeRegionArea); + +/// Sets the neighbor connection data for the specified direction. +/// @param[in] span The span to update. +/// @param[in] direction The direction to set. [Limits: 0 <= value < 4] +/// @param[in] neighborIndex The index of the neighbor span. +inline void rcSetCon(rcCompactSpan& span, int direction, int neighborIndex) +{ + const unsigned int shift = (unsigned int)direction * 6; + const unsigned int con = span.con; + span.con = (con & ~(0x3f << shift)) | (((unsigned int)neighborIndex & 0x3f) << shift); +} + +/// Gets neighbor connection data for the specified direction. +/// @param[in] span The span to check. +/// @param[in] direction The direction to check. [Limits: 0 <= value < 4] +/// @return The neighbor connection data for the specified direction, or #RC_NOT_CONNECTED if there is no connection. +inline int rcGetCon(const rcCompactSpan& span, int direction) +{ + const unsigned int shift = (unsigned int)direction * 6; + return (span.con >> shift) & 0x3f; +} + +/// Gets the standard width (x-axis) offset for the specified direction. +/// @param[in] direction The direction. [Limits: 0 <= value < 4] +/// @return The width offset to apply to the current cell position to move in the direction. +inline int rcGetDirOffsetX(int direction) +{ + static const int offset[4] = { -1, 0, 1, 0, }; + return offset[direction & 0x03]; +} + +// TODO (graham): Rename this to rcGetDirOffsetZ +/// Gets the standard height (z-axis) offset for the specified direction. +/// @param[in] direction The direction. [Limits: 0 <= value < 4] +/// @return The height offset to apply to the current cell position to move in the direction. +inline int rcGetDirOffsetY(int direction) +{ + static const int offset[4] = { 0, 1, 0, -1 }; + return offset[direction & 0x03]; +} + +/// Gets the direction for the specified offset. One of x and y should be 0. +/// @param[in] offsetX The x offset. [Limits: -1 <= value <= 1] +/// @param[in] offsetZ The z offset. [Limits: -1 <= value <= 1] +/// @return The direction that represents the offset. +inline int rcGetDirForOffset(int offsetX, int offsetZ) +{ + static const int dirs[5] = { 3, 0, -1, 2, 1 }; + return dirs[((offsetZ + 1) << 1) + offsetX]; +} + +/// @} +/// @name Layer, Contour, Polymesh, and Detail Mesh Functions +/// @see rcHeightfieldLayer, rcContourSet, rcPolyMesh, rcPolyMeshDetail +/// @{ + +/// Builds a layer set from the specified compact heightfield. +/// @ingroup recast +/// @param[in,out] ctx The build context to use during the operation. +/// @param[in] chf A fully built compact heightfield. +/// @param[in] borderSize The size of the non-navigable border around the heightfield. [Limit: >=0] +/// [Units: vx] +/// @param[in] walkableHeight Minimum floor to 'ceiling' height that will still allow the floor area +/// to be considered walkable. [Limit: >= 3] [Units: vx] +/// @param[out] lset The resulting layer set. (Must be pre-allocated.) +/// @returns True if the operation completed successfully. +bool rcBuildHeightfieldLayers(rcContext* ctx, const rcCompactHeightfield& chf, + int borderSize, int walkableHeight, + rcHeightfieldLayerSet& lset); + +/// Builds a contour set from the region outlines in the provided compact heightfield. +/// @ingroup recast +/// @param[in,out] ctx The build context to use during the operation. +/// @param[in] chf A fully built compact heightfield. +/// @param[in] maxError The maximum distance a simplified contour's border edges should deviate +/// the original raw contour. [Limit: >=0] [Units: wu] +/// @param[in] maxEdgeLen The maximum allowed length for contour edges along the border of the mesh. +/// [Limit: >=0] [Units: vx] +/// @param[out] cset The resulting contour set. (Must be pre-allocated.) +/// @param[in] buildFlags The build flags. (See: #rcBuildContoursFlags) +/// @returns True if the operation completed successfully. +bool rcBuildContours(rcContext* ctx, const rcCompactHeightfield& chf, + float maxError, int maxEdgeLen, + rcContourSet& cset, int buildFlags = RC_CONTOUR_TESS_WALL_EDGES); + +/// Builds a polygon mesh from the provided contours. +/// @ingroup recast +/// @param[in,out] ctx The build context to use during the operation. +/// @param[in] cset A fully built contour set. +/// @param[in] nvp The maximum number of vertices allowed for polygons generated during the +/// contour to polygon conversion process. [Limit: >= 3] +/// @param[out] mesh The resulting polygon mesh. (Must be re-allocated.) +/// @returns True if the operation completed successfully. +bool rcBuildPolyMesh(rcContext* ctx, const rcContourSet& cset, const int nvp, rcPolyMesh& mesh); + +/// Merges multiple polygon meshes into a single mesh. +/// @ingroup recast +/// @param[in,out] ctx The build context to use during the operation. +/// @param[in] meshes An array of polygon meshes to merge. [Size: @p nmeshes] +/// @param[in] nmeshes The number of polygon meshes in the meshes array. +/// @param[in] mesh The resulting polygon mesh. (Must be pre-allocated.) +/// @returns True if the operation completed successfully. +bool rcMergePolyMeshes(rcContext* ctx, rcPolyMesh** meshes, const int nmeshes, rcPolyMesh& mesh); + +/// Builds a detail mesh from the provided polygon mesh. +/// @ingroup recast +/// @param[in,out] ctx The build context to use during the operation. +/// @param[in] mesh A fully built polygon mesh. +/// @param[in] chf The compact heightfield used to build the polygon mesh. +/// @param[in] sampleDist Sets the distance to use when sampling the heightfield. [Limit: >=0] [Units: wu] +/// @param[in] sampleMaxError The maximum distance the detail mesh surface should deviate from +/// heightfield data. [Limit: >=0] [Units: wu] +/// @param[out] dmesh The resulting detail mesh. (Must be pre-allocated.) +/// @returns True if the operation completed successfully. +bool rcBuildPolyMeshDetail(rcContext* ctx, const rcPolyMesh& mesh, const rcCompactHeightfield& chf, + float sampleDist, float sampleMaxError, + rcPolyMeshDetail& dmesh); + +/// Copies the poly mesh data from src to dst. +/// @ingroup recast +/// @param[in,out] ctx The build context to use during the operation. +/// @param[in] src The source mesh to copy from. +/// @param[out] dst The resulting detail mesh. (Must be pre-allocated, must be empty mesh.) +/// @returns True if the operation completed successfully. +bool rcCopyPolyMesh(rcContext* ctx, const rcPolyMesh& src, rcPolyMesh& dst); + +/// Merges multiple detail meshes into a single detail mesh. +/// @ingroup recast +/// @param[in,out] ctx The build context to use during the operation. +/// @param[in] meshes An array of detail meshes to merge. [Size: @p nmeshes] +/// @param[in] nmeshes The number of detail meshes in the meshes array. +/// @param[out] mesh The resulting detail mesh. (Must be pre-allocated.) +/// @returns True if the operation completed successfully. +bool rcMergePolyMeshDetails(rcContext* ctx, rcPolyMeshDetail** meshes, const int nmeshes, rcPolyMeshDetail& mesh); + +/// @} + +#endif // RECAST_H + +/////////////////////////////////////////////////////////////////////////// + +// Due to the large amount of detail documentation for this file, +// the content normally located at the end of the header file has been separated +// out to a file in /Docs/Extern. diff --git a/native/third_party/recastnavigation/Recast/Include/RecastAlloc.h b/native/third_party/recastnavigation/Recast/Include/RecastAlloc.h new file mode 100644 index 0000000..2ca43ec --- /dev/null +++ b/native/third_party/recastnavigation/Recast/Include/RecastAlloc.h @@ -0,0 +1,391 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#ifndef RECASTALLOC_H +#define RECASTALLOC_H + +#include "RecastAssert.h" + +#include +#include + +/// Provides hint values to the memory allocator on how long the +/// memory is expected to be used. +enum rcAllocHint +{ + RC_ALLOC_PERM, ///< Memory will persist after a function call. + RC_ALLOC_TEMP ///< Memory used temporarily within a function. +}; + +/// A memory allocation function. +/// @param[in] size The size, in bytes of memory, to allocate. +/// @param[in] hint A hint to the allocator on how long the memory is expected to be in use. +/// @return A pointer to the beginning of the allocated memory block, or null if the allocation failed. +/// @see rcAllocSetCustom +typedef void* (rcAllocFunc)(size_t size, rcAllocHint hint); + +/// A memory deallocation function. +/// @param[in] ptr A pointer to a memory block previously allocated using #rcAllocFunc. +/// @see rcAllocSetCustom +typedef void (rcFreeFunc)(void* ptr); + +/// Sets the base custom allocation functions to be used by Recast. +/// @param[in] allocFunc The memory allocation function to be used by #rcAlloc +/// @param[in] freeFunc The memory de-allocation function to be used by #rcFree +/// @see rcAlloc, rcFree +void rcAllocSetCustom(rcAllocFunc *allocFunc, rcFreeFunc *freeFunc); + +/// Allocates a memory block. +/// @param[in] size The size, in bytes of memory, to allocate. +/// @param[in] hint A hint to the allocator on how long the memory is expected to be in use. +/// @return A pointer to the beginning of the allocated memory block, or null if the allocation failed. +/// @see rcFree, rcAllocSetCustom +void* rcAlloc(size_t size, rcAllocHint hint); + +/// Deallocates a memory block. If @p ptr is NULL, this does nothing. +/// @warning This function leaves the value of @p ptr unchanged. So it still +/// points to the same (now invalid) location, and not to null. +/// @param[in] ptr A pointer to a memory block previously allocated using #rcAlloc. +/// @see rcAlloc, rcAllocSetCustom +void rcFree(void* ptr); + +/// An implementation of operator new usable for placement new. The default one is part of STL (which we don't use). +/// rcNewTag is a dummy type used to differentiate our operator from the STL one, in case users import both Recast +/// and STL. +struct rcNewTag {}; +inline void* operator new(size_t, const rcNewTag&, void* p) { return p; } +inline void operator delete(void*, const rcNewTag&, void*) {} + +/// Signed to avoid warnings when comparing to int loop indexes, and common error with comparing to zero. +/// MSVC2010 has a bug where ssize_t is unsigned (!!!). +typedef intptr_t rcSizeType; +#define RC_SIZE_MAX INTPTR_MAX + +/// Macros to hint to the compiler about the likeliest branch. Please add a benchmark that demonstrates a performance +/// improvement before introducing use cases. +#if defined(__GNUC__) || defined(__clang__) +#define rcLikely(x) __builtin_expect((x), true) +#define rcUnlikely(x) __builtin_expect((x), false) +#else +#define rcLikely(x) (x) +#define rcUnlikely(x) (x) +#endif + +/// Variable-sized storage type. Mimics the interface of std::vector with some notable differences: +/// * Uses rcAlloc()/rcFree() to handle storage. +/// * No support for a custom allocator. +/// * Uses signed size instead of size_t to avoid warnings in for loops: "for (int i = 0; i < foo.size(); i++)" +/// * Omits methods of limited utility: insert/erase, (bad performance), at (we don't use exceptions), operator=. +/// * assign() and the pre-sizing constructor follow C++11 semantics -- they don't construct a temporary if no value is provided. +/// * push_back() and resize() support adding values from the current vector. Range-based constructors and assign(begin, end) do not. +/// * No specialization for bool. +template +class rcVectorBase +{ + rcSizeType m_size; + rcSizeType m_cap; + T* m_data; + // Constructs a T at the give address with either the copy constructor or the default. + static void construct(T* p, const T& v) { ::new(rcNewTag(), (void*)p) T(v); } + static void construct(T* p) { ::new(rcNewTag(), (void*)p) T; } + static void construct_range(T* begin, T* end); + static void construct_range(T* begin, T* end, const T& value); + static void copy_range(T* dst, const T* begin, const T* end); + void destroy_range(rcSizeType begin, rcSizeType end); + // Creates an array of the given size, copies all of this vector's data into it, and returns it. + T* allocate_and_copy(rcSizeType size); + void resize_impl(rcSizeType size, const T* value); + // Requires: min_capacity > m_cap. + rcSizeType get_new_capacity(rcSizeType min_capacity); + public: + typedef rcSizeType size_type; + typedef T value_type; + + rcVectorBase() : m_size(0), m_cap(0), m_data(0) {} + rcVectorBase(const rcVectorBase& other) : m_size(0), m_cap(0), m_data(0) { assign(other.begin(), other.end()); } + explicit rcVectorBase(rcSizeType count) : m_size(0), m_cap(0), m_data(0) { resize(count); } + rcVectorBase(rcSizeType count, const T& value) : m_size(0), m_cap(0), m_data(0) { resize(count, value); } + rcVectorBase(const T* begin, const T* end) : m_size(0), m_cap(0), m_data(0) { assign(begin, end); } + ~rcVectorBase() { destroy_range(0, m_size); rcFree(m_data); } + + // Unlike in std::vector, we return a bool to indicate whether the alloc was successful. + bool reserve(rcSizeType size); + + void assign(rcSizeType count, const T& value) { clear(); resize(count, value); } + void assign(const T* begin, const T* end); + + void resize(rcSizeType size) { resize_impl(size, NULL); } + void resize(rcSizeType size, const T& value) { resize_impl(size, &value); } + // Not implemented as resize(0) because resize requires T to be default-constructible. + void clear() { destroy_range(0, m_size); m_size = 0; } + + void push_back(const T& value); + void pop_back() { rcAssert(m_size > 0); back().~T(); m_size--; } + + rcSizeType size() const { return m_size; } + rcSizeType capacity() const { return m_cap; } + bool empty() const { return size() == 0; } + + const T& operator[](rcSizeType i) const { rcAssert(i >= 0 && i < m_size); return m_data[i]; } + T& operator[](rcSizeType i) { rcAssert(i >= 0 && i < m_size); return m_data[i]; } + + const T& front() const { rcAssert(m_size); return m_data[0]; } + T& front() { rcAssert(m_size); return m_data[0]; } + const T& back() const { rcAssert(m_size); return m_data[m_size - 1]; } + T& back() { rcAssert(m_size); return m_data[m_size - 1]; } + const T* data() const { return m_data; } + T* data() { return m_data; } + + T* begin() { return m_data; } + T* end() { return m_data + m_size; } + const T* begin() const { return m_data; } + const T* end() const { return m_data + m_size; } + + void swap(rcVectorBase& other); + + // Explicitly deleted. + rcVectorBase& operator=(const rcVectorBase& other); +}; + +template +bool rcVectorBase::reserve(rcSizeType count) +{ + if (count <= m_cap) + { + return true; + } + + T* new_data = allocate_and_copy(count); + if (!new_data) + { + return false; + } + + destroy_range(0, m_size); + rcFree(m_data); + m_data = new_data; + m_cap = count; + return true; +} + +template +T* rcVectorBase::allocate_and_copy(rcSizeType size) +{ + rcAssert(RC_SIZE_MAX / static_cast(sizeof(T)) >= size); + T* new_data = static_cast(rcAlloc(sizeof(T) * size, H)); + if (new_data) + { + copy_range(new_data, m_data, m_data + m_size); + } + return new_data; +} + +template +void rcVectorBase::assign(const T* begin, const T* end) +{ + clear(); + reserve(end - begin); + m_size = end - begin; + copy_range(m_data, begin, end); +} + +template +void rcVectorBase::push_back(const T& value) +{ + // rcLikely increases performance by ~50% on BM_rcVector_PushPreallocated, + // and by ~2-5% on BM_rcVector_Push. + if (rcLikely(m_size < m_cap)) + { + construct(m_data + m_size++, value); + return; + } + + const rcSizeType new_cap = get_new_capacity(m_cap + 1); + T* data = allocate_and_copy(new_cap); + // construct between allocate and destroy+free in case value is + // in this vector. + construct(data + m_size, value); + destroy_range(0, m_size); + m_size++; + m_cap = new_cap; + rcFree(m_data); + m_data = data; +} + +template +rcSizeType rcVectorBase::get_new_capacity(rcSizeType min_capacity) +{ + rcAssert(min_capacity <= RC_SIZE_MAX); + if (rcUnlikely(m_cap >= RC_SIZE_MAX / 2)) + { + return RC_SIZE_MAX; + } + return 2 * m_cap > min_capacity ? 2 * m_cap : min_capacity; +} + +template +void rcVectorBase::resize_impl(rcSizeType size, const T* value) +{ + if (size < m_size) + { + destroy_range(size, m_size); + m_size = size; + } + else if (size > m_size) + { + if (size <= m_cap) + { + if (value) + { + construct_range(m_data + m_size, m_data + size, *value); + } + else + { + construct_range(m_data + m_size, m_data + size); + } + m_size = size; + } + else + { + const rcSizeType new_cap = get_new_capacity(size); + T* new_data = allocate_and_copy(new_cap); + // We defer deconstructing/freeing old data until after constructing + // new elements in case "value" is there. + if (value) + { + construct_range(new_data + m_size, new_data + size, *value); + } + else + { + construct_range(new_data + m_size, new_data + size); + } + destroy_range(0, m_size); + rcFree(m_data); + m_data = new_data; + m_cap = new_cap; + m_size = size; + } + } +} + +template +void rcVectorBase::swap(rcVectorBase& other) +{ + // TODO: Reorganize headers so we can use rcSwap here. + rcSizeType tmp_cap = other.m_cap; + rcSizeType tmp_size = other.m_size; + T* tmp_data = other.m_data; + + other.m_cap = m_cap; + other.m_size = m_size; + other.m_data = m_data; + + m_cap = tmp_cap; + m_size = tmp_size; + m_data = tmp_data; +} + +// static +template +void rcVectorBase::construct_range(T* begin, T* end) +{ + for (T* p = begin; p < end; p++) + { + construct(p); + } +} + +// static +template +void rcVectorBase::construct_range(T* begin, T* end, const T& value) +{ + for (T* p = begin; p < end; p++) + { + construct(p, value); + } +} + +// static +template +void rcVectorBase::copy_range(T* dst, const T* begin, const T* end) +{ + for (rcSizeType i = 0 ; i < end - begin; i++) + { + construct(dst + i, begin[i]); + } +} + +template +void rcVectorBase::destroy_range(rcSizeType begin, rcSizeType end) +{ + for (rcSizeType i = begin; i < end; i++) + { + m_data[i].~T(); + } +} + +template +class rcTempVector : public rcVectorBase +{ + typedef rcVectorBase Base; +public: + rcTempVector() : Base() {} + explicit rcTempVector(rcSizeType size) : Base(size) {} + rcTempVector(rcSizeType size, const T& value) : Base(size, value) {} + rcTempVector(const rcTempVector& other) : Base(other) {} + rcTempVector(const T* begin, const T* end) : Base(begin, end) {} +}; + +template +class rcPermVector : public rcVectorBase +{ + typedef rcVectorBase Base; +public: + rcPermVector() : Base() {} + explicit rcPermVector(rcSizeType size) : Base(size) {} + rcPermVector(rcSizeType size, const T& value) : Base(size, value) {} + rcPermVector(const rcPermVector& other) : Base(other) {} + rcPermVector(const T* begin, const T* end) : Base(begin, end) {} +}; + +/// A simple helper class used to delete an array when it goes out of scope. +/// @note This class is rarely if ever used by the end user. +template class rcScopedDelete +{ + T* ptr; +public: + + /// Constructs an instance with a null pointer. + inline rcScopedDelete() : ptr(0) {} + + /// Constructs an instance with the specified pointer. + /// @param[in] p An pointer to an allocated array. + inline rcScopedDelete(T* p) : ptr(p) {} + inline ~rcScopedDelete() { rcFree(ptr); } + + /// The root array pointer. + /// @return The root array pointer. + inline operator T*() { return ptr; } + +private: + // Explicitly disabled copy constructor and copy assignment operator. + rcScopedDelete(const rcScopedDelete&); + rcScopedDelete& operator=(const rcScopedDelete&); +}; + +#endif \ No newline at end of file diff --git a/native/third_party/recastnavigation/Recast/Include/RecastAssert.h b/native/third_party/recastnavigation/Recast/Include/RecastAssert.h new file mode 100644 index 0000000..7527cff --- /dev/null +++ b/native/third_party/recastnavigation/Recast/Include/RecastAssert.h @@ -0,0 +1,49 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#ifndef RECASTASSERT_H +#define RECASTASSERT_H + +/// An assertion failure callback function. +/// @param[in] expression Asserted expression. +/// @param[in] file Filename of the failed assertion. +/// @param[in] line Line number of the failed assertion. +/// @see rcAssertFailSetCustom +typedef void (rcAssertFailFunc)(const char* expression, const char* file, int line); + +/// Sets the base custom assertion failure callback function to be used by Recast. +/// @param[in] assertFailFunc The function to be used in case of failure of #dtAssert +void rcAssertFailSetCustom(rcAssertFailFunc* assertFailFunc); + +/// Gets the base custom assertion failure function to be used by Recast. +rcAssertFailFunc* rcAssertFailGetCustom(); + +#ifdef RC_DISABLE_ASSERTS +// From https://web.archive.org/web/20210117002833/http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/ +# define rcAssert(x) do { (void)sizeof(x); } while ((void)(__LINE__==-1), false) +#else +# include +# define rcAssert(expression) \ + { \ + rcAssertFailFunc* failFunc = rcAssertFailGetCustom(); \ + if (failFunc == NULL) { assert(expression); } \ + else if (!(expression)) { (*failFunc)(#expression, __FILE__, __LINE__); } \ + } +#endif // !defined(RC_DISABLE_ASSERTS) + +#endif // RECASTASSERT_H diff --git a/native/third_party/recastnavigation/Recast/Source/Recast.cpp b/native/third_party/recastnavigation/Recast/Source/Recast.cpp new file mode 100644 index 0000000..d75a9f5 --- /dev/null +++ b/native/third_party/recastnavigation/Recast/Source/Recast.cpp @@ -0,0 +1,542 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#include "Recast.h" +#include "RecastAlloc.h" +#include "RecastAssert.h" + +#include +#include +#include +#include + +namespace +{ +/// Allocates and constructs an object of the given type, returning a pointer. +/// @param[in] allocLifetime Allocation lifetime hint +template +T* rcNew(const rcAllocHint allocLifetime) +{ + T* ptr = (T*)rcAlloc(sizeof(T), allocLifetime); + ::new(rcNewTag(), (void*)ptr) T(); + return ptr; +} + +/// Destroys and frees an object allocated with rcNew. +/// @param[in] ptr The object pointer to delete. +template +void rcDelete(T* ptr) +{ + if (ptr) + { + ptr->~T(); + rcFree((void*)ptr); + } +} +} // anonymous namespace + +float rcSqrt(float x) +{ + return sqrtf(x); +} + +void rcContext::log(const rcLogCategory category, const char* format, ...) +{ + if (!m_logEnabled) + { + return; + } + static const int MSG_SIZE = 512; + char msg[MSG_SIZE]; + va_list argList; + va_start(argList, format); + int len = vsnprintf(msg, MSG_SIZE, format, argList); + if (len >= MSG_SIZE) + { + len = MSG_SIZE - 1; + msg[MSG_SIZE - 1] = '\0'; + + const char* errorMessage = "Log message was truncated"; + doLog(RC_LOG_ERROR, errorMessage, (int)strlen(errorMessage)); + } + va_end(argList); + doLog(category, msg, len); +} + +void rcContext::doResetLog() +{ + // Defined out of line to fix the weak v-tables warning +} + +rcHeightfield* rcAllocHeightfield() +{ + return rcNew(RC_ALLOC_PERM); +} + +void rcFreeHeightField(rcHeightfield* heightfield) +{ + rcDelete(heightfield); +} + +rcHeightfield::rcHeightfield() +: width() +, height() +, bmin() +, bmax() +, cs() +, ch() +, spans() +, pools() +, freelist() +{ +} + +rcHeightfield::~rcHeightfield() +{ + // Delete span array. + rcFree(spans); + // Delete span pools. + while (pools) + { + rcSpanPool* next = pools->next; + rcFree(pools); + pools = next; + } +} + +rcCompactHeightfield* rcAllocCompactHeightfield() +{ + return rcNew(RC_ALLOC_PERM); +} + +void rcFreeCompactHeightfield(rcCompactHeightfield* compactHeightfield) +{ + rcDelete(compactHeightfield); +} + +rcCompactHeightfield::rcCompactHeightfield() +: width() +, height() +, spanCount() +, walkableHeight() +, walkableClimb() +, borderSize() +, maxDistance() +, maxRegions() +, bmin() +, bmax() +, cs() +, ch() +, cells() +, spans() +, dist() +, areas() +{ +} + +rcCompactHeightfield::~rcCompactHeightfield() +{ + rcFree(cells); + rcFree(spans); + rcFree(dist); + rcFree(areas); +} + +rcHeightfieldLayerSet* rcAllocHeightfieldLayerSet() +{ + return rcNew(RC_ALLOC_PERM); +} + +void rcFreeHeightfieldLayerSet(rcHeightfieldLayerSet* layerSet) +{ + rcDelete(layerSet); +} + +rcHeightfieldLayerSet::rcHeightfieldLayerSet() +: layers() +, nlayers() +{ +} + +rcHeightfieldLayerSet::~rcHeightfieldLayerSet() +{ + for (int i = 0; i < nlayers; ++i) + { + rcFree(layers[i].heights); + rcFree(layers[i].areas); + rcFree(layers[i].cons); + } + rcFree(layers); +} + + +rcContourSet* rcAllocContourSet() +{ + return rcNew(RC_ALLOC_PERM); +} + +void rcFreeContourSet(rcContourSet* contourSet) +{ + rcDelete(contourSet); +} + +rcContourSet::rcContourSet() +: conts() +, nconts() +, bmin() +, bmax() +, cs() +, ch() +, width() +, height() +, borderSize() +, maxError() +{ +} + +rcContourSet::~rcContourSet() +{ + for (int i = 0; i < nconts; ++i) + { + rcFree(conts[i].verts); + rcFree(conts[i].rverts); + } + rcFree(conts); +} + +rcPolyMesh* rcAllocPolyMesh() +{ + return rcNew(RC_ALLOC_PERM); +} + +void rcFreePolyMesh(rcPolyMesh* polyMesh) +{ + rcDelete(polyMesh); +} + +rcPolyMesh::rcPolyMesh() +: verts() +, polys() +, regs() +, flags() +, areas() +, nverts() +, npolys() +, maxpolys() +, nvp() +, bmin() +, bmax() +, cs() +, ch() +, borderSize() +, maxEdgeError() +{ +} + +rcPolyMesh::~rcPolyMesh() +{ + rcFree(verts); + rcFree(polys); + rcFree(regs); + rcFree(flags); + rcFree(areas); +} + +rcPolyMeshDetail* rcAllocPolyMeshDetail() +{ + return rcNew(RC_ALLOC_PERM); +} + +void rcFreePolyMeshDetail(rcPolyMeshDetail* detailMesh) +{ + if (detailMesh == NULL) + { + return; + } + rcFree(detailMesh->meshes); + rcFree(detailMesh->verts); + rcFree(detailMesh->tris); + rcFree(detailMesh); +} + +rcPolyMeshDetail::rcPolyMeshDetail() +: meshes() +, verts() +, tris() +, nmeshes() +, nverts() +, ntris() +{ +} + +void rcCalcBounds(const float* verts, int numVerts, float* minBounds, float* maxBounds) +{ + // Calculate bounding box. + rcVcopy(minBounds, verts); + rcVcopy(maxBounds, verts); + for (int i = 1; i < numVerts; ++i) + { + const float* v = &verts[i * 3]; + rcVmin(minBounds, v); + rcVmax(maxBounds, v); + } +} + +void rcCalcGridSize(const float* minBounds, const float* maxBounds, const float cellSize, int* sizeX, int* sizeZ) +{ + *sizeX = (int)((maxBounds[0] - minBounds[0]) / cellSize + 0.5f); + *sizeZ = (int)((maxBounds[2] - minBounds[2]) / cellSize + 0.5f); +} + +bool rcCreateHeightfield(rcContext* context, rcHeightfield& heightfield, int sizeX, int sizeZ, + const float* minBounds, const float* maxBounds, + float cellSize, float cellHeight) +{ + rcIgnoreUnused(context); + + heightfield.width = sizeX; + heightfield.height = sizeZ; + rcVcopy(heightfield.bmin, minBounds); + rcVcopy(heightfield.bmax, maxBounds); + heightfield.cs = cellSize; + heightfield.ch = cellHeight; + heightfield.spans = (rcSpan**)rcAlloc(sizeof(rcSpan*) * heightfield.width * heightfield.height, RC_ALLOC_PERM); + if (!heightfield.spans) + { + return false; + } + memset(heightfield.spans, 0, sizeof(rcSpan*) * heightfield.width * heightfield.height); + return true; +} + +static void calcTriNormal(const float* v0, const float* v1, const float* v2, float* faceNormal) +{ + float e0[3], e1[3]; + rcVsub(e0, v1, v0); + rcVsub(e1, v2, v0); + rcVcross(faceNormal, e0, e1); + rcVnormalize(faceNormal); +} + +void rcMarkWalkableTriangles(rcContext* context, const float walkableSlopeAngle, + const float* verts, const int numVerts, + const int* tris, const int numTris, + unsigned char* triAreaIDs) +{ + rcIgnoreUnused(context); + rcIgnoreUnused(numVerts); + + const float walkableThr = cosf(walkableSlopeAngle / 180.0f * RC_PI); + + float norm[3]; + + for (int i = 0; i < numTris; ++i) + { + const int* tri = &tris[i * 3]; + calcTriNormal(&verts[tri[0] * 3], &verts[tri[1] * 3], &verts[tri[2] * 3], norm); + // Check if the face is walkable. + if (norm[1] > walkableThr) + { + triAreaIDs[i] = RC_WALKABLE_AREA; + } + } +} + +void rcClearUnwalkableTriangles(rcContext* context, const float walkableSlopeAngle, + const float* verts, int numVerts, + const int* tris, int numTris, + unsigned char* triAreaIDs) +{ + rcIgnoreUnused(context); + rcIgnoreUnused(numVerts); + + // The minimum Y value for a face normal of a triangle with a walkable slope. + const float walkableLimitY = cosf(walkableSlopeAngle / 180.0f * RC_PI); + + float faceNormal[3]; + for (int i = 0; i < numTris; ++i) + { + const int* tri = &tris[i * 3]; + calcTriNormal(&verts[tri[0] * 3], &verts[tri[1] * 3], &verts[tri[2] * 3], faceNormal); + // Check if the face is walkable. + if (faceNormal[1] <= walkableLimitY) + { + triAreaIDs[i] = RC_NULL_AREA; + } + } +} + +int rcGetHeightFieldSpanCount(rcContext* context, const rcHeightfield& heightfield) +{ + rcIgnoreUnused(context); + + const int numCols = heightfield.width * heightfield.height; + int spanCount = 0; + for (int columnIndex = 0; columnIndex < numCols; ++columnIndex) + { + for (rcSpan* span = heightfield.spans[columnIndex]; span != NULL; span = span->next) + { + if (span->area != RC_NULL_AREA) + { + spanCount++; + } + } + } + return spanCount; +} + +bool rcBuildCompactHeightfield(rcContext* context, const int walkableHeight, const int walkableClimb, + const rcHeightfield& heightfield, rcCompactHeightfield& compactHeightfield) +{ + rcAssert(context); + + rcScopedTimer timer(context, RC_TIMER_BUILD_COMPACTHEIGHTFIELD); + + const int xSize = heightfield.width; + const int zSize = heightfield.height; + const int spanCount = rcGetHeightFieldSpanCount(context, heightfield); + + // Fill in header. + compactHeightfield.width = xSize; + compactHeightfield.height = zSize; + compactHeightfield.spanCount = spanCount; + compactHeightfield.walkableHeight = walkableHeight; + compactHeightfield.walkableClimb = walkableClimb; + compactHeightfield.maxRegions = 0; + rcVcopy(compactHeightfield.bmin, heightfield.bmin); + rcVcopy(compactHeightfield.bmax, heightfield.bmax); + compactHeightfield.bmax[1] += walkableHeight * heightfield.ch; + compactHeightfield.cs = heightfield.cs; + compactHeightfield.ch = heightfield.ch; + compactHeightfield.cells = (rcCompactCell*)rcAlloc(sizeof(rcCompactCell) * xSize * zSize, RC_ALLOC_PERM); + if (!compactHeightfield.cells) + { + context->log(RC_LOG_ERROR, "rcBuildCompactHeightfield: Out of memory 'chf.cells' (%d)", xSize * zSize); + return false; + } + memset(compactHeightfield.cells, 0, sizeof(rcCompactCell) * xSize * zSize); + compactHeightfield.spans = (rcCompactSpan*)rcAlloc(sizeof(rcCompactSpan) * spanCount, RC_ALLOC_PERM); + if (!compactHeightfield.spans) + { + context->log(RC_LOG_ERROR, "rcBuildCompactHeightfield: Out of memory 'chf.spans' (%d)", spanCount); + return false; + } + memset(compactHeightfield.spans, 0, sizeof(rcCompactSpan) * spanCount); + compactHeightfield.areas = (unsigned char*)rcAlloc(sizeof(unsigned char) * spanCount, RC_ALLOC_PERM); + if (!compactHeightfield.areas) + { + context->log(RC_LOG_ERROR, "rcBuildCompactHeightfield: Out of memory 'chf.areas' (%d)", spanCount); + return false; + } + memset(compactHeightfield.areas, RC_NULL_AREA, sizeof(unsigned char) * spanCount); + + const int MAX_HEIGHT = 0xffff; + + // Fill in cells and spans. + int currentCellIndex = 0; + const int numColumns = xSize * zSize; + for (int columnIndex = 0; columnIndex < numColumns; ++columnIndex) + { + const rcSpan* span = heightfield.spans[columnIndex]; + + // If there are no spans at this cell, just leave the data to index=0, count=0. + if (span == NULL) + { + continue; + } + + rcCompactCell& cell = compactHeightfield.cells[columnIndex]; + cell.index = currentCellIndex; + cell.count = 0; + + for (; span != NULL; span = span->next) + { + if (span->area != RC_NULL_AREA) + { + const int bot = (int)span->smax; + const int top = span->next ? (int)span->next->smin : MAX_HEIGHT; + compactHeightfield.spans[currentCellIndex].y = (unsigned short)rcClamp(bot, 0, 0xffff); + compactHeightfield.spans[currentCellIndex].h = (unsigned char)rcClamp(top - bot, 0, 0xff); + compactHeightfield.areas[currentCellIndex] = span->area; + currentCellIndex++; + cell.count++; + } + } + } + + // Find neighbour connections. + const int MAX_LAYERS = RC_NOT_CONNECTED - 1; + int maxLayerIndex = 0; + const int zStride = xSize; // for readability + for (int z = 0; z < zSize; ++z) + { + for (int x = 0; x < xSize; ++x) + { + const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride]; + for (int i = (int)cell.index, ni = (int)(cell.index + cell.count); i < ni; ++i) + { + rcCompactSpan& span = compactHeightfield.spans[i]; + + for (int dir = 0; dir < 4; ++dir) + { + rcSetCon(span, dir, RC_NOT_CONNECTED); + const int neighborX = x + rcGetDirOffsetX(dir); + const int neighborZ = z + rcGetDirOffsetY(dir); + // First check that the neighbour cell is in bounds. + if (neighborX < 0 || neighborZ < 0 || neighborX >= xSize || neighborZ >= zSize) + { + continue; + } + + // Iterate over all neighbour spans and check if any of the is + // accessible from current cell. + const rcCompactCell& neighborCell = compactHeightfield.cells[neighborX + neighborZ * zStride]; + for (int k = (int)neighborCell.index, nk = (int)(neighborCell.index + neighborCell.count); k < nk; ++k) + { + const rcCompactSpan& neighborSpan = compactHeightfield.spans[k]; + const int bot = rcMax(span.y, neighborSpan.y); + const int top = rcMin(span.y + span.h, neighborSpan.y + neighborSpan.h); + + // Check that the gap between the spans is walkable, + // and that the climb height between the gaps is not too high. + if ((top - bot) >= walkableHeight && rcAbs((int)neighborSpan.y - (int)span.y) <= walkableClimb) + { + // Mark direction as walkable. + const int layerIndex = k - (int)neighborCell.index; + if (layerIndex < 0 || layerIndex > MAX_LAYERS) + { + maxLayerIndex = rcMax(maxLayerIndex, layerIndex); + continue; + } + rcSetCon(span, dir, layerIndex); + break; + } + } + } + } + } + } + + if (maxLayerIndex > MAX_LAYERS) + { + context->log(RC_LOG_ERROR, "rcBuildCompactHeightfield: Heightfield has too many layers %d (max: %d)", + maxLayerIndex, MAX_LAYERS); + } + + return true; +} diff --git a/native/third_party/recastnavigation/Recast/Source/RecastAlloc.cpp b/native/third_party/recastnavigation/Recast/Source/RecastAlloc.cpp new file mode 100644 index 0000000..e919daf --- /dev/null +++ b/native/third_party/recastnavigation/Recast/Source/RecastAlloc.cpp @@ -0,0 +1,51 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#include "RecastAlloc.h" + +static void* rcAllocDefault(size_t size, rcAllocHint) +{ + return malloc(size); +} + +static void rcFreeDefault(void *ptr) +{ + free(ptr); +} + +static rcAllocFunc* sRecastAllocFunc = rcAllocDefault; +static rcFreeFunc* sRecastFreeFunc = rcFreeDefault; + +void rcAllocSetCustom(rcAllocFunc* allocFunc, rcFreeFunc* freeFunc) +{ + sRecastAllocFunc = allocFunc ? allocFunc : rcAllocDefault; + sRecastFreeFunc = freeFunc ? freeFunc : rcFreeDefault; +} + +void* rcAlloc(size_t size, rcAllocHint hint) +{ + return sRecastAllocFunc(size, hint); +} + +void rcFree(void* ptr) +{ + if (ptr != NULL) + { + sRecastFreeFunc(ptr); + } +} diff --git a/native/third_party/recastnavigation/Recast/Source/RecastArea.cpp b/native/third_party/recastnavigation/Recast/Source/RecastArea.cpp new file mode 100644 index 0000000..7a7091c --- /dev/null +++ b/native/third_party/recastnavigation/Recast/Source/RecastArea.cpp @@ -0,0 +1,717 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#include "Recast.h" +#include "RecastAlloc.h" +#include "RecastAssert.h" + +#include // for memcpy and memset + +/// Sorts the given data in-place using insertion sort. +/// +/// @param data The data to sort +/// @param dataLength The number of elements in @p data +static void insertSort(unsigned char* data, const int dataLength) +{ + for (int valueIndex = 1; valueIndex < dataLength; valueIndex++) + { + const unsigned char value = data[valueIndex]; + int insertionIndex; + for (insertionIndex = valueIndex - 1; insertionIndex >= 0 && data[insertionIndex] > value; insertionIndex--) + { + // Shift over values + data[insertionIndex + 1] = data[insertionIndex]; + } + + // Insert the value in sorted order. + data[insertionIndex + 1] = value; + } +} + +// TODO (graham): This is duplicated in the ConvexVolumeTool in RecastDemo +/// Checks if a point is contained within a polygon +/// +/// @param[in] numVerts Number of vertices in the polygon +/// @param[in] verts The polygon vertices +/// @param[in] point The point to check +/// @returns true if the point lies within the polygon, false otherwise. +static bool pointInPoly(int numVerts, const float* verts, const float* point) +{ + bool inPoly = false; + for (int i = 0, j = numVerts - 1; i < numVerts; j = i++) + { + const float* vi = &verts[i * 3]; + const float* vj = &verts[j * 3]; + + if ((vi[2] > point[2]) == (vj[2] > point[2])) + { + continue; + } + + if (point[0] >= (vj[0] - vi[0]) * (point[2] - vi[2]) / (vj[2] - vi[2]) + vi[0]) + { + continue; + } + inPoly = !inPoly; + } + return inPoly; +} + +bool rcErodeWalkableArea(rcContext* context, const int erosionRadius, rcCompactHeightfield& compactHeightfield) +{ + rcAssert(context != NULL); + + const int xSize = compactHeightfield.width; + const int zSize = compactHeightfield.height; + const int& zStride = xSize; // For readability + + rcScopedTimer timer(context, RC_TIMER_ERODE_AREA); + + unsigned char* distanceToBoundary = (unsigned char*)rcAlloc(sizeof(unsigned char) * compactHeightfield.spanCount, + RC_ALLOC_TEMP); + if (!distanceToBoundary) + { + context->log(RC_LOG_ERROR, "erodeWalkableArea: Out of memory 'dist' (%d).", compactHeightfield.spanCount); + return false; + } + memset(distanceToBoundary, 0xff, sizeof(unsigned char) * compactHeightfield.spanCount); + + // Mark boundary cells. + for (int z = 0; z < zSize; ++z) + { + for (int x = 0; x < xSize; ++x) + { + const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride]; + for (int spanIndex = (int)cell.index, maxSpanIndex = (int)(cell.index + cell.count); spanIndex < maxSpanIndex; ++spanIndex) + { + if (compactHeightfield.areas[spanIndex] == RC_NULL_AREA) + { + distanceToBoundary[spanIndex] = 0; + continue; + } + const rcCompactSpan& span = compactHeightfield.spans[spanIndex]; + + // Check that there is a non-null adjacent span in each of the 4 cardinal directions. + int neighborCount = 0; + for (int direction = 0; direction < 4; ++direction) + { + const int neighborConnection = rcGetCon(span, direction); + if (neighborConnection == RC_NOT_CONNECTED) + { + break; + } + + const int neighborX = x + rcGetDirOffsetX(direction); + const int neighborZ = z + rcGetDirOffsetY(direction); + const int neighborSpanIndex = (int)compactHeightfield.cells[neighborX + neighborZ * zStride].index + neighborConnection; + + if (compactHeightfield.areas[neighborSpanIndex] == RC_NULL_AREA) + { + break; + } + neighborCount++; + } + + // At least one missing neighbour, so this is a boundary cell. + if (neighborCount != 4) + { + distanceToBoundary[spanIndex] = 0; + } + } + } + } + + unsigned char newDistance; + + // Pass 1 + for (int z = 0; z < zSize; ++z) + { + for (int x = 0; x < xSize; ++x) + { + const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride]; + const int maxSpanIndex = (int)(cell.index + cell.count); + for (int spanIndex = (int)cell.index; spanIndex < maxSpanIndex; ++spanIndex) + { + const rcCompactSpan& span = compactHeightfield.spans[spanIndex]; + + if (rcGetCon(span, 0) != RC_NOT_CONNECTED) + { + // (-1,0) + const int aX = x + rcGetDirOffsetX(0); + const int aY = z + rcGetDirOffsetY(0); + const int aIndex = (int)compactHeightfield.cells[aX + aY * xSize].index + rcGetCon(span, 0); + const rcCompactSpan& aSpan = compactHeightfield.spans[aIndex]; + newDistance = (unsigned char)rcMin((int)distanceToBoundary[aIndex] + 2, 255); + if (newDistance < distanceToBoundary[spanIndex]) + { + distanceToBoundary[spanIndex] = newDistance; + } + + // (-1,-1) + if (rcGetCon(aSpan, 3) != RC_NOT_CONNECTED) + { + const int bX = aX + rcGetDirOffsetX(3); + const int bY = aY + rcGetDirOffsetY(3); + const int bIndex = (int)compactHeightfield.cells[bX + bY * xSize].index + rcGetCon(aSpan, 3); + newDistance = (unsigned char)rcMin((int)distanceToBoundary[bIndex] + 3, 255); + if (newDistance < distanceToBoundary[spanIndex]) + { + distanceToBoundary[spanIndex] = newDistance; + } + } + } + if (rcGetCon(span, 3) != RC_NOT_CONNECTED) + { + // (0,-1) + const int aX = x + rcGetDirOffsetX(3); + const int aY = z + rcGetDirOffsetY(3); + const int aIndex = (int)compactHeightfield.cells[aX + aY * xSize].index + rcGetCon(span, 3); + const rcCompactSpan& aSpan = compactHeightfield.spans[aIndex]; + newDistance = (unsigned char)rcMin((int)distanceToBoundary[aIndex] + 2, 255); + if (newDistance < distanceToBoundary[spanIndex]) + { + distanceToBoundary[spanIndex] = newDistance; + } + + // (1,-1) + if (rcGetCon(aSpan, 2) != RC_NOT_CONNECTED) + { + const int bX = aX + rcGetDirOffsetX(2); + const int bY = aY + rcGetDirOffsetY(2); + const int bIndex = (int)compactHeightfield.cells[bX + bY * xSize].index + rcGetCon(aSpan, 2); + newDistance = (unsigned char)rcMin((int)distanceToBoundary[bIndex] + 3, 255); + if (newDistance < distanceToBoundary[spanIndex]) + { + distanceToBoundary[spanIndex] = newDistance; + } + } + } + } + } + } + + // Pass 2 + for (int z = zSize - 1; z >= 0; --z) + { + for (int x = xSize - 1; x >= 0; --x) + { + const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride]; + const int maxSpanIndex = (int)(cell.index + cell.count); + for (int spanIndex = (int)cell.index; spanIndex < maxSpanIndex; ++spanIndex) + { + const rcCompactSpan& span = compactHeightfield.spans[spanIndex]; + + if (rcGetCon(span, 2) != RC_NOT_CONNECTED) + { + // (1,0) + const int aX = x + rcGetDirOffsetX(2); + const int aY = z + rcGetDirOffsetY(2); + const int aIndex = (int)compactHeightfield.cells[aX + aY * xSize].index + rcGetCon(span, 2); + const rcCompactSpan& aSpan = compactHeightfield.spans[aIndex]; + newDistance = (unsigned char)rcMin((int)distanceToBoundary[aIndex] + 2, 255); + if (newDistance < distanceToBoundary[spanIndex]) + { + distanceToBoundary[spanIndex] = newDistance; + } + + // (1,1) + if (rcGetCon(aSpan, 1) != RC_NOT_CONNECTED) + { + const int bX = aX + rcGetDirOffsetX(1); + const int bY = aY + rcGetDirOffsetY(1); + const int bIndex = (int)compactHeightfield.cells[bX + bY * xSize].index + rcGetCon(aSpan, 1); + newDistance = (unsigned char)rcMin((int)distanceToBoundary[bIndex] + 3, 255); + if (newDistance < distanceToBoundary[spanIndex]) + { + distanceToBoundary[spanIndex] = newDistance; + } + } + } + if (rcGetCon(span, 1) != RC_NOT_CONNECTED) + { + // (0,1) + const int aX = x + rcGetDirOffsetX(1); + const int aY = z + rcGetDirOffsetY(1); + const int aIndex = (int)compactHeightfield.cells[aX + aY * xSize].index + rcGetCon(span, 1); + const rcCompactSpan& aSpan = compactHeightfield.spans[aIndex]; + newDistance = (unsigned char)rcMin((int)distanceToBoundary[aIndex] + 2, 255); + if (newDistance < distanceToBoundary[spanIndex]) + { + distanceToBoundary[spanIndex] = newDistance; + } + + // (-1,1) + if (rcGetCon(aSpan, 0) != RC_NOT_CONNECTED) + { + const int bX = aX + rcGetDirOffsetX(0); + const int bY = aY + rcGetDirOffsetY(0); + const int bIndex = (int)compactHeightfield.cells[bX + bY * xSize].index + rcGetCon(aSpan, 0); + newDistance = (unsigned char)rcMin((int)distanceToBoundary[bIndex] + 3, 255); + if (newDistance < distanceToBoundary[spanIndex]) + { + distanceToBoundary[spanIndex] = newDistance; + } + } + } + } + } + } + + const unsigned char minBoundaryDistance = (unsigned char)(erosionRadius * 2); + for (int spanIndex = 0; spanIndex < compactHeightfield.spanCount; ++spanIndex) + { + if (distanceToBoundary[spanIndex] < minBoundaryDistance) + { + compactHeightfield.areas[spanIndex] = RC_NULL_AREA; + } + } + + rcFree(distanceToBoundary); + + return true; +} + +bool rcMedianFilterWalkableArea(rcContext* context, rcCompactHeightfield& compactHeightfield) +{ + rcAssert(context); + + const int xSize = compactHeightfield.width; + const int zSize = compactHeightfield.height; + const int zStride = xSize; // For readability + + rcScopedTimer timer(context, RC_TIMER_MEDIAN_AREA); + + unsigned char* areas = (unsigned char*)rcAlloc(sizeof(unsigned char) * compactHeightfield.spanCount, RC_ALLOC_TEMP); + if (!areas) + { + context->log(RC_LOG_ERROR, "medianFilterWalkableArea: Out of memory 'areas' (%d).", + compactHeightfield.spanCount); + return false; + } + memset(areas, 0xff, sizeof(unsigned char) * compactHeightfield.spanCount); + + for (int z = 0; z < zSize; ++z) + { + for (int x = 0; x < xSize; ++x) + { + const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride]; + const int maxSpanIndex = (int)(cell.index + cell.count); + for (int spanIndex = (int)cell.index; spanIndex < maxSpanIndex; ++spanIndex) + { + const rcCompactSpan& span = compactHeightfield.spans[spanIndex]; + if (compactHeightfield.areas[spanIndex] == RC_NULL_AREA) + { + areas[spanIndex] = compactHeightfield.areas[spanIndex]; + continue; + } + + unsigned char neighborAreas[9]; + for (int neighborIndex = 0; neighborIndex < 9; ++neighborIndex) + { + neighborAreas[neighborIndex] = compactHeightfield.areas[spanIndex]; + } + + for (int dir = 0; dir < 4; ++dir) + { + if (rcGetCon(span, dir) == RC_NOT_CONNECTED) + { + continue; + } + + const int aX = x + rcGetDirOffsetX(dir); + const int aZ = z + rcGetDirOffsetY(dir); + const int aIndex = (int)compactHeightfield.cells[aX + aZ * zStride].index + rcGetCon(span, dir); + if (compactHeightfield.areas[aIndex] != RC_NULL_AREA) + { + neighborAreas[dir * 2 + 0] = compactHeightfield.areas[aIndex]; + } + + const rcCompactSpan& aSpan = compactHeightfield.spans[aIndex]; + const int dir2 = (dir + 1) & 0x3; + const int neighborConnection2 = rcGetCon(aSpan, dir2); + if (neighborConnection2 != RC_NOT_CONNECTED) + { + const int bX = aX + rcGetDirOffsetX(dir2); + const int bZ = aZ + rcGetDirOffsetY(dir2); + const int bIndex = (int)compactHeightfield.cells[bX + bZ * zStride].index + neighborConnection2; + if (compactHeightfield.areas[bIndex] != RC_NULL_AREA) + { + neighborAreas[dir * 2 + 1] = compactHeightfield.areas[bIndex]; + } + } + } + insertSort(neighborAreas, 9); + areas[spanIndex] = neighborAreas[4]; + } + } + } + + memcpy(compactHeightfield.areas, areas, sizeof(unsigned char) * compactHeightfield.spanCount); + + rcFree(areas); + + return true; +} + +void rcMarkBoxArea(rcContext* context, const float* boxMinBounds, const float* boxMaxBounds, unsigned char areaId, + rcCompactHeightfield& compactHeightfield) +{ + rcAssert(context); + + rcScopedTimer timer(context, RC_TIMER_MARK_BOX_AREA); + + const int xSize = compactHeightfield.width; + const int zSize = compactHeightfield.height; + const int zStride = xSize; // For readability + + // Find the footprint of the box area in grid cell coordinates. + int minX = (int)((boxMinBounds[0] - compactHeightfield.bmin[0]) / compactHeightfield.cs); + int minY = (int)((boxMinBounds[1] - compactHeightfield.bmin[1]) / compactHeightfield.ch); + int minZ = (int)((boxMinBounds[2] - compactHeightfield.bmin[2]) / compactHeightfield.cs); + int maxX = (int)((boxMaxBounds[0] - compactHeightfield.bmin[0]) / compactHeightfield.cs); + int maxY = (int)((boxMaxBounds[1] - compactHeightfield.bmin[1]) / compactHeightfield.ch); + int maxZ = (int)((boxMaxBounds[2] - compactHeightfield.bmin[2]) / compactHeightfield.cs); + + // Early-out if the box is outside the bounds of the grid. + if (maxX < 0) { return; } + if (minX >= xSize) { return; } + if (maxZ < 0) { return; } + if (minZ >= zSize) { return; } + + // Clamp relevant bound coordinates to the grid. + if (minX < 0) { minX = 0; } + if (maxX >= xSize) { maxX = xSize - 1; } + if (minZ < 0) { minZ = 0; } + if (maxZ >= zSize) { maxZ = zSize - 1; } + + // Mark relevant cells. + for (int z = minZ; z <= maxZ; ++z) + { + for (int x = minX; x <= maxX; ++x) + { + const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride]; + const int maxSpanIndex = (int)(cell.index + cell.count); + for (int spanIndex = (int)cell.index; spanIndex < maxSpanIndex; ++spanIndex) + { + rcCompactSpan& span = compactHeightfield.spans[spanIndex]; + + // Skip if the span is outside the box extents. + if ((int)span.y < minY || (int)span.y > maxY) + { + continue; + } + + // Skip if the span has been removed. + if (compactHeightfield.areas[spanIndex] == RC_NULL_AREA) + { + continue; + } + + // Mark the span. + compactHeightfield.areas[spanIndex] = areaId; + } + } + } +} + +void rcMarkConvexPolyArea(rcContext* context, const float* verts, const int numVerts, + const float minY, const float maxY, unsigned char areaId, + rcCompactHeightfield& compactHeightfield) +{ + rcAssert(context); + + rcScopedTimer timer(context, RC_TIMER_MARK_CONVEXPOLY_AREA); + + const int xSize = compactHeightfield.width; + const int zSize = compactHeightfield.height; + const int zStride = xSize; // For readability + + // Compute the bounding box of the polygon + float bmin[3]; + float bmax[3]; + rcVcopy(bmin, verts); + rcVcopy(bmax, verts); + for (int i = 1; i < numVerts; ++i) + { + rcVmin(bmin, &verts[i * 3]); + rcVmax(bmax, &verts[i * 3]); + } + bmin[1] = minY; + bmax[1] = maxY; + + // Compute the grid footprint of the polygon + int minx = (int)((bmin[0] - compactHeightfield.bmin[0]) / compactHeightfield.cs); + int miny = (int)((bmin[1] - compactHeightfield.bmin[1]) / compactHeightfield.ch); + int minz = (int)((bmin[2] - compactHeightfield.bmin[2]) / compactHeightfield.cs); + int maxx = (int)((bmax[0] - compactHeightfield.bmin[0]) / compactHeightfield.cs); + int maxy = (int)((bmax[1] - compactHeightfield.bmin[1]) / compactHeightfield.ch); + int maxz = (int)((bmax[2] - compactHeightfield.bmin[2]) / compactHeightfield.cs); + + // Early-out if the polygon lies entirely outside the grid. + if (maxx < 0) { return; } + if (minx >= xSize) { return; } + if (maxz < 0) { return; } + if (minz >= zSize) { return; } + + // Clamp the polygon footprint to the grid + if (minx < 0) { minx = 0; } + if (maxx >= xSize) { maxx = xSize - 1; } + if (minz < 0) { minz = 0; } + if (maxz >= zSize) { maxz = zSize - 1; } + + // TODO: Optimize. + for (int z = minz; z <= maxz; ++z) + { + for (int x = minx; x <= maxx; ++x) + { + const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride]; + const int maxSpanIndex = (int)(cell.index + cell.count); + for (int spanIndex = (int)cell.index; spanIndex < maxSpanIndex; ++spanIndex) + { + rcCompactSpan& span = compactHeightfield.spans[spanIndex]; + + // Skip if span is removed. + if (compactHeightfield.areas[spanIndex] == RC_NULL_AREA) + { + continue; + } + + // Skip if y extents don't overlap. + if ((int)span.y < miny || (int)span.y > maxy) + { + continue; + } + + const float point[] = { + compactHeightfield.bmin[0] + ((float)x + 0.5f) * compactHeightfield.cs, + 0, + compactHeightfield.bmin[2] + ((float)z + 0.5f) * compactHeightfield.cs + }; + + if (pointInPoly(numVerts, verts, point)) + { + compactHeightfield.areas[spanIndex] = areaId; + } + } + } + } +} + +static const float EPSILON = 1e-6f; + +/// Normalizes the vector if the length is greater than zero. +/// If the magnitude is zero, the vector is unchanged. +/// @param[in,out] v The vector to normalize. [(x, y, z)] +static void rcVsafeNormalize(float* v) +{ + const float sqMag = rcSqr(v[0]) + rcSqr(v[1]) + rcSqr(v[2]); + if (sqMag > EPSILON) + { + const float inverseMag = 1.0f / rcSqrt(sqMag); + v[0] *= inverseMag; + v[1] *= inverseMag; + v[2] *= inverseMag; + } +} + +int rcOffsetPoly(const float* verts, const int numVerts, const float offset, float* outVerts, const int maxOutVerts) +{ + // Defines the limit at which a miter becomes a bevel. + // Similar in behavior to https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-miterlimit + const float MITER_LIMIT = 1.20f; + + int numOutVerts = 0; + + for (int vertIndex = 0; vertIndex < numVerts; vertIndex++) + { + // Grab three vertices of the polygon. + const int vertIndexA = (vertIndex + numVerts - 1) % numVerts; + const int vertIndexB = vertIndex; + const int vertIndexC = (vertIndex + 1) % numVerts; + const float* vertA = &verts[vertIndexA * 3]; + const float* vertB = &verts[vertIndexB * 3]; + const float* vertC = &verts[vertIndexC * 3]; + + // From A to B on the x/z plane + float prevSegmentDir[3]; + rcVsub(prevSegmentDir, vertB, vertA); + prevSegmentDir[1] = 0; // Squash onto x/z plane + rcVsafeNormalize(prevSegmentDir); + + // From B to C on the x/z plane + float currSegmentDir[3]; + rcVsub(currSegmentDir, vertC, vertB); + currSegmentDir[1] = 0; // Squash onto x/z plane + rcVsafeNormalize(currSegmentDir); + + // The y component of the cross product of the two normalized segment directions. + // The X and Z components of the cross product are both zero because the two + // segment direction vectors fall within the x/z plane. + float cross = currSegmentDir[0] * prevSegmentDir[2] - prevSegmentDir[0] * currSegmentDir[2]; + + // CCW perpendicular vector to AB. The segment normal. + const float prevSegmentNormX = -prevSegmentDir[2]; + const float prevSegmentNormZ = prevSegmentDir[0]; + + // CCW perpendicular vector to BC. The segment normal. + const float currSegmentNormX = -currSegmentDir[2]; + const float currSegmentNormZ = currSegmentDir[0]; + + // Average the two segment normals to get the proportional miter offset for B. + // This isn't normalized because it's defining the distance and direction the corner will need to be + // adjusted proportionally to the edge offsets to properly miter the adjoining edges. + float cornerMiterX = (prevSegmentNormX + currSegmentNormX) * 0.5f; + float cornerMiterZ = (prevSegmentNormZ + currSegmentNormZ) * 0.5f; + const float cornerMiterSqMag = rcSqr(cornerMiterX) + rcSqr(cornerMiterZ); + + // If the magnitude of the segment normal average is less than about .69444, + // the corner is an acute enough angle that the result should be beveled. + const bool bevel = cornerMiterSqMag * MITER_LIMIT * MITER_LIMIT < 1.0f; + + // Scale the corner miter so it's proportional to how much the corner should be offset compared to the edges. + if (cornerMiterSqMag > EPSILON) + { + const float scale = 1.0f / cornerMiterSqMag; + cornerMiterX *= scale; + cornerMiterZ *= scale; + } + + if (bevel && cross < 0.0f) // If the corner is convex and an acute enough angle, generate a bevel. + { + if (numOutVerts + 2 > maxOutVerts) + { + return 0; + } + + // Generate two bevel vertices at a distances from B proportional to the angle between the two segments. + // Move each bevel vertex out proportional to the given offset. + float d = (1.0f - (prevSegmentDir[0] * currSegmentDir[0] + prevSegmentDir[2] * currSegmentDir[2])) * 0.5f; + + outVerts[numOutVerts * 3 + 0] = vertB[0] + (-prevSegmentNormX + prevSegmentDir[0] * d) * offset; + outVerts[numOutVerts * 3 + 1] = vertB[1]; + outVerts[numOutVerts * 3 + 2] = vertB[2] + (-prevSegmentNormZ + prevSegmentDir[2] * d) * offset; + numOutVerts++; + + outVerts[numOutVerts * 3 + 0] = vertB[0] + (-currSegmentNormX - currSegmentDir[0] * d) * offset; + outVerts[numOutVerts * 3 + 1] = vertB[1]; + outVerts[numOutVerts * 3 + 2] = vertB[2] + (-currSegmentNormZ - currSegmentDir[2] * d) * offset; + numOutVerts++; + } + else + { + if (numOutVerts + 1 > maxOutVerts) + { + return 0; + } + + // Move B along the miter direction by the specified offset. + outVerts[numOutVerts * 3 + 0] = vertB[0] - cornerMiterX * offset; + outVerts[numOutVerts * 3 + 1] = vertB[1]; + outVerts[numOutVerts * 3 + 2] = vertB[2] - cornerMiterZ * offset; + numOutVerts++; + } + } + + return numOutVerts; +} + +void rcMarkCylinderArea(rcContext* context, const float* position, const float radius, const float height, + unsigned char areaId, rcCompactHeightfield& compactHeightfield) +{ + rcAssert(context); + + rcScopedTimer timer(context, RC_TIMER_MARK_CYLINDER_AREA); + + const int xSize = compactHeightfield.width; + const int zSize = compactHeightfield.height; + const int zStride = xSize; // For readability + + // Compute the bounding box of the cylinder + const float cylinderBBMin[] = + { + position[0] - radius, + position[1], + position[2] - radius + }; + const float cylinderBBMax[] = + { + position[0] + radius, + position[1] + height, + position[2] + radius + }; + + // Compute the grid footprint of the cylinder + int minx = (int)((cylinderBBMin[0] - compactHeightfield.bmin[0]) / compactHeightfield.cs); + int miny = (int)((cylinderBBMin[1] - compactHeightfield.bmin[1]) / compactHeightfield.ch); + int minz = (int)((cylinderBBMin[2] - compactHeightfield.bmin[2]) / compactHeightfield.cs); + int maxx = (int)((cylinderBBMax[0] - compactHeightfield.bmin[0]) / compactHeightfield.cs); + int maxy = (int)((cylinderBBMax[1] - compactHeightfield.bmin[1]) / compactHeightfield.ch); + int maxz = (int)((cylinderBBMax[2] - compactHeightfield.bmin[2]) / compactHeightfield.cs); + + // Early-out if the cylinder is completely outside the grid bounds. + if (maxx < 0) { return; } + if (minx >= xSize) { return; } + if (maxz < 0) { return; } + if (minz >= zSize) { return; } + + // Clamp the cylinder bounds to the grid. + if (minx < 0) { minx = 0; } + if (maxx >= xSize) { maxx = xSize - 1; } + if (minz < 0) { minz = 0; } + if (maxz >= zSize) { maxz = zSize - 1; } + + const float radiusSq = radius * radius; + + for (int z = minz; z <= maxz; ++z) + { + for (int x = minx; x <= maxx; ++x) + { + const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride]; + const int maxSpanIndex = (int)(cell.index + cell.count); + + const float cellX = compactHeightfield.bmin[0] + ((float)x + 0.5f) * compactHeightfield.cs; + const float cellZ = compactHeightfield.bmin[2] + ((float)z + 0.5f) * compactHeightfield.cs; + const float deltaX = cellX - position[0]; + const float deltaZ = cellZ - position[2]; + + // Skip this column if it's too far from the center point of the cylinder. + if (rcSqr(deltaX) + rcSqr(deltaZ) >= radiusSq) + { + continue; + } + + // Mark all overlapping spans + for (int spanIndex = (int)cell.index; spanIndex < maxSpanIndex; ++spanIndex) + { + rcCompactSpan& span = compactHeightfield.spans[spanIndex]; + + // Skip if span is removed. + if (compactHeightfield.areas[spanIndex] == RC_NULL_AREA) + { + continue; + } + + // Mark if y extents overlap. + if ((int)span.y >= miny && (int)span.y <= maxy) + { + compactHeightfield.areas[spanIndex] = areaId; + } + } + } + } +} diff --git a/native/third_party/recastnavigation/Recast/Source/RecastAssert.cpp b/native/third_party/recastnavigation/Recast/Source/RecastAssert.cpp new file mode 100644 index 0000000..08a05a6 --- /dev/null +++ b/native/third_party/recastnavigation/Recast/Source/RecastAssert.cpp @@ -0,0 +1,31 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#include "RecastAssert.h" + +static rcAssertFailFunc* sRecastAssertFailFunc = 0; + +void rcAssertFailSetCustom(rcAssertFailFunc* assertFailFunc) +{ + sRecastAssertFailFunc = assertFailFunc; +} + +rcAssertFailFunc* rcAssertFailGetCustom() +{ + return sRecastAssertFailFunc; +} \ No newline at end of file diff --git a/native/third_party/recastnavigation/Recast/Source/RecastContour.cpp b/native/third_party/recastnavigation/Recast/Source/RecastContour.cpp new file mode 100644 index 0000000..ce50c78 --- /dev/null +++ b/native/third_party/recastnavigation/Recast/Source/RecastContour.cpp @@ -0,0 +1,1095 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#include +#include +#include +#include +#include "Recast.h" +#include "RecastAlloc.h" +#include "RecastAssert.h" + + +static int getCornerHeight(int x, int y, int i, int dir, + const rcCompactHeightfield& chf, + bool& isBorderVertex) +{ + const rcCompactSpan& s = chf.spans[i]; + int ch = (int)s.y; + int dirp = (dir+1) & 0x3; + + unsigned int regs[4] = {0,0,0,0}; + + // Combine region and area codes in order to prevent + // border vertices which are in between two areas to be removed. + regs[0] = chf.spans[i].reg | (chf.areas[i] << 16); + + if (rcGetCon(s, dir) != RC_NOT_CONNECTED) + { + const int ax = x + rcGetDirOffsetX(dir); + const int ay = y + rcGetDirOffsetY(dir); + const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(s, dir); + const rcCompactSpan& as = chf.spans[ai]; + ch = rcMax(ch, (int)as.y); + regs[1] = chf.spans[ai].reg | (chf.areas[ai] << 16); + if (rcGetCon(as, dirp) != RC_NOT_CONNECTED) + { + const int ax2 = ax + rcGetDirOffsetX(dirp); + const int ay2 = ay + rcGetDirOffsetY(dirp); + const int ai2 = (int)chf.cells[ax2+ay2*chf.width].index + rcGetCon(as, dirp); + const rcCompactSpan& as2 = chf.spans[ai2]; + ch = rcMax(ch, (int)as2.y); + regs[2] = chf.spans[ai2].reg | (chf.areas[ai2] << 16); + } + } + if (rcGetCon(s, dirp) != RC_NOT_CONNECTED) + { + const int ax = x + rcGetDirOffsetX(dirp); + const int ay = y + rcGetDirOffsetY(dirp); + const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(s, dirp); + const rcCompactSpan& as = chf.spans[ai]; + ch = rcMax(ch, (int)as.y); + regs[3] = chf.spans[ai].reg | (chf.areas[ai] << 16); + if (rcGetCon(as, dir) != RC_NOT_CONNECTED) + { + const int ax2 = ax + rcGetDirOffsetX(dir); + const int ay2 = ay + rcGetDirOffsetY(dir); + const int ai2 = (int)chf.cells[ax2+ay2*chf.width].index + rcGetCon(as, dir); + const rcCompactSpan& as2 = chf.spans[ai2]; + ch = rcMax(ch, (int)as2.y); + regs[2] = chf.spans[ai2].reg | (chf.areas[ai2] << 16); + } + } + + // Check if the vertex is special edge vertex, these vertices will be removed later. + for (int j = 0; j < 4; ++j) + { + const int a = j; + const int b = (j+1) & 0x3; + const int c = (j+2) & 0x3; + const int d = (j+3) & 0x3; + + // The vertex is a border vertex there are two same exterior cells in a row, + // followed by two interior cells and none of the regions are out of bounds. + const bool twoSameExts = (regs[a] & regs[b] & RC_BORDER_REG) != 0 && regs[a] == regs[b]; + const bool twoInts = ((regs[c] | regs[d]) & RC_BORDER_REG) == 0; + const bool intsSameArea = (regs[c]>>16) == (regs[d]>>16); + const bool noZeros = regs[a] != 0 && regs[b] != 0 && regs[c] != 0 && regs[d] != 0; + if (twoSameExts && twoInts && intsSameArea && noZeros) + { + isBorderVertex = true; + break; + } + } + + return ch; +} + +static void walkContour(int x, int y, int i, + const rcCompactHeightfield& chf, + unsigned char* flags, rcTempVector& points) +{ + // Choose the first non-connected edge + unsigned char dir = 0; + while ((flags[i] & (1 << dir)) == 0) + dir++; + + unsigned char startDir = dir; + int starti = i; + + const unsigned char area = chf.areas[i]; + + int iter = 0; + while (++iter < 40000) + { + if (flags[i] & (1 << dir)) + { + // Choose the edge corner + bool isBorderVertex = false; + bool isAreaBorder = false; + int px = x; + int py = getCornerHeight(x, y, i, dir, chf, isBorderVertex); + int pz = y; + switch(dir) + { + case 0: pz++; break; + case 1: px++; pz++; break; + case 2: px++; break; + } + int r = 0; + const rcCompactSpan& s = chf.spans[i]; + if (rcGetCon(s, dir) != RC_NOT_CONNECTED) + { + const int ax = x + rcGetDirOffsetX(dir); + const int ay = y + rcGetDirOffsetY(dir); + const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(s, dir); + r = (int)chf.spans[ai].reg; + if (area != chf.areas[ai]) + isAreaBorder = true; + } + if (isBorderVertex) + r |= RC_BORDER_VERTEX; + if (isAreaBorder) + r |= RC_AREA_BORDER; + points.push_back(px); + points.push_back(py); + points.push_back(pz); + points.push_back(r); + + flags[i] &= ~(1 << dir); // Remove visited edges + dir = (dir+1) & 0x3; // Rotate CW + } + else + { + int ni = -1; + const int nx = x + rcGetDirOffsetX(dir); + const int ny = y + rcGetDirOffsetY(dir); + const rcCompactSpan& s = chf.spans[i]; + if (rcGetCon(s, dir) != RC_NOT_CONNECTED) + { + const rcCompactCell& nc = chf.cells[nx+ny*chf.width]; + ni = (int)nc.index + rcGetCon(s, dir); + } + if (ni == -1) + { + // Should not happen. + return; + } + x = nx; + y = ny; + i = ni; + dir = (dir+3) & 0x3; // Rotate CCW + } + + if (starti == i && startDir == dir) + { + break; + } + } +} + +static float distancePtSeg(const int x, const int z, + const int px, const int pz, + const int qx, const int qz) +{ + float pqx = (float)(qx - px); + float pqz = (float)(qz - pz); + float dx = (float)(x - px); + float dz = (float)(z - pz); + float d = pqx*pqx + pqz*pqz; + float t = pqx*dx + pqz*dz; + if (d > 0) + t /= d; + if (t < 0) + t = 0; + else if (t > 1) + t = 1; + + dx = px + t*pqx - x; + dz = pz + t*pqz - z; + + return dx*dx + dz*dz; +} + +static void simplifyContour(rcTempVector& points, rcTempVector& simplified, + const float maxError, const int maxEdgeLen, const int buildFlags) +{ + // Add initial points. + bool hasConnections = false; + for (int i = 0; i < points.size(); i += 4) + { + if ((points[i+3] & RC_CONTOUR_REG_MASK) != 0) + { + hasConnections = true; + break; + } + } + + if (hasConnections) + { + // The contour has some portals to other regions. + // Add a new point to every location where the region changes. + for (int i = 0, ni = static_cast(points.size()) / 4; i < ni; ++i) + { + int ii = (i+1) % ni; + const bool differentRegs = (points[i*4+3] & RC_CONTOUR_REG_MASK) != (points[ii*4+3] & RC_CONTOUR_REG_MASK); + const bool areaBorders = (points[i*4+3] & RC_AREA_BORDER) != (points[ii*4+3] & RC_AREA_BORDER); + if (differentRegs || areaBorders) + { + simplified.push_back(points[i*4+0]); + simplified.push_back(points[i*4+1]); + simplified.push_back(points[i*4+2]); + simplified.push_back(i); + } + } + } + + if (simplified.size() == 0) + { + // If there is no connections at all, + // create some initial points for the simplification process. + // Find lower-left and upper-right vertices of the contour. + int llx = points[0]; + int lly = points[1]; + int llz = points[2]; + int lli = 0; + int urx = points[0]; + int ury = points[1]; + int urz = points[2]; + int uri = 0; + for (int i = 0; i < points.size(); i += 4) + { + int x = points[i+0]; + int y = points[i+1]; + int z = points[i+2]; + if (x < llx || (x == llx && z < llz)) + { + llx = x; + lly = y; + llz = z; + lli = i/4; + } + if (x > urx || (x == urx && z > urz)) + { + urx = x; + ury = y; + urz = z; + uri = i/4; + } + } + simplified.push_back(llx); + simplified.push_back(lly); + simplified.push_back(llz); + simplified.push_back(lli); + + simplified.push_back(urx); + simplified.push_back(ury); + simplified.push_back(urz); + simplified.push_back(uri); + } + + // Add points until all raw points are within + // error tolerance to the simplified shape. + const int pn = static_cast(points.size()) / 4; + for (int i = 0; i < simplified.size()/4; ) + { + int ii = (i+1) % (simplified.size()/4); + + int ax = simplified[i*4+0]; + int az = simplified[i*4+2]; + int ai = simplified[i*4+3]; + + int bx = simplified[ii*4+0]; + int bz = simplified[ii*4+2]; + int bi = simplified[ii*4+3]; + + // Find maximum deviation from the segment. + float maxd = 0; + int maxi = -1; + int ci, cinc, endi; + + // Traverse the segment in lexilogical order so that the + // max deviation is calculated similarly when traversing + // opposite segments. + if (bx > ax || (bx == ax && bz > az)) + { + cinc = 1; + ci = (ai+cinc) % pn; + endi = bi; + } + else + { + cinc = pn-1; + ci = (bi+cinc) % pn; + endi = ai; + rcSwap(ax, bx); + rcSwap(az, bz); + } + + // Tessellate only outer edges or edges between areas. + if ((points[ci*4+3] & RC_CONTOUR_REG_MASK) == 0 || + (points[ci*4+3] & RC_AREA_BORDER)) + { + while (ci != endi) + { + float d = distancePtSeg(points[ci*4+0], points[ci*4+2], ax, az, bx, bz); + if (d > maxd) + { + maxd = d; + maxi = ci; + } + ci = (ci+cinc) % pn; + } + } + + + // If the max deviation is larger than accepted error, + // add new point, else continue to next segment. + if (maxi != -1 && maxd > (maxError*maxError)) + { + // Add space for the new point. + simplified.resize(simplified.size()+4); + const int n = static_cast(simplified.size()) / 4; + for (int j = n-1; j > i; --j) + { + simplified[j*4+0] = simplified[(j-1)*4+0]; + simplified[j*4+1] = simplified[(j-1)*4+1]; + simplified[j*4+2] = simplified[(j-1)*4+2]; + simplified[j*4+3] = simplified[(j-1)*4+3]; + } + // Add the point. + simplified[(i+1)*4+0] = points[maxi*4+0]; + simplified[(i+1)*4+1] = points[maxi*4+1]; + simplified[(i+1)*4+2] = points[maxi*4+2]; + simplified[(i+1)*4+3] = maxi; + } + else + { + ++i; + } + } + + // Split too long edges. + if (maxEdgeLen > 0 && (buildFlags & (RC_CONTOUR_TESS_WALL_EDGES|RC_CONTOUR_TESS_AREA_EDGES)) != 0) + { + for (int i = 0; i < simplified.size()/4; ) + { + const int ii = (i+1) % (simplified.size()/4); + + const int ax = simplified[i*4+0]; + const int az = simplified[i*4+2]; + const int ai = simplified[i*4+3]; + + const int bx = simplified[ii*4+0]; + const int bz = simplified[ii*4+2]; + const int bi = simplified[ii*4+3]; + + // Find maximum deviation from the segment. + int maxi = -1; + int ci = (ai+1) % pn; + + // Tessellate only outer edges or edges between areas. + bool tess = false; + // Wall edges. + if ((buildFlags & RC_CONTOUR_TESS_WALL_EDGES) && (points[ci*4+3] & RC_CONTOUR_REG_MASK) == 0) + tess = true; + // Edges between areas. + if ((buildFlags & RC_CONTOUR_TESS_AREA_EDGES) && (points[ci*4+3] & RC_AREA_BORDER)) + tess = true; + + if (tess) + { + int dx = bx - ax; + int dz = bz - az; + if (dx*dx + dz*dz > maxEdgeLen*maxEdgeLen) + { + // Round based on the segments in lexilogical order so that the + // max tesselation is consistent regardless in which direction + // segments are traversed. + const int n = bi < ai ? (bi+pn - ai) : (bi - ai); + if (n > 1) + { + if (bx > ax || (bx == ax && bz > az)) + maxi = (ai + n/2) % pn; + else + maxi = (ai + (n+1)/2) % pn; + } + } + } + + // If the max deviation is larger than accepted error, + // add new point, else continue to next segment. + if (maxi != -1) + { + // Add space for the new point. + simplified.resize(simplified.size()+4); + const int n = static_cast(simplified.size()) / 4; + for (int j = n-1; j > i; --j) + { + simplified[j*4+0] = simplified[(j-1)*4+0]; + simplified[j*4+1] = simplified[(j-1)*4+1]; + simplified[j*4+2] = simplified[(j-1)*4+2]; + simplified[j*4+3] = simplified[(j-1)*4+3]; + } + // Add the point. + simplified[(i+1)*4+0] = points[maxi*4+0]; + simplified[(i+1)*4+1] = points[maxi*4+1]; + simplified[(i+1)*4+2] = points[maxi*4+2]; + simplified[(i+1)*4+3] = maxi; + } + else + { + ++i; + } + } + } + + for (int i = 0; i < simplified.size()/4; ++i) + { + // The edge vertex flag is take from the current raw point, + // and the neighbour region is take from the next raw point. + const int ai = (simplified[i*4+3]+1) % pn; + const int bi = simplified[i*4+3]; + simplified[i*4+3] = (points[ai*4+3] & (RC_CONTOUR_REG_MASK|RC_AREA_BORDER)) | (points[bi*4+3] & RC_BORDER_VERTEX); + } + +} + +static int calcAreaOfPolygon2D(const int* verts, const int nverts) +{ + int area = 0; + for (int i = 0, j = nverts-1; i < nverts; j=i++) + { + const int* vi = &verts[i*4]; + const int* vj = &verts[j*4]; + area += vi[0] * vj[2] - vj[0] * vi[2]; + } + return (area+1) / 2; +} + +// TODO: these are the same as in RecastMesh.cpp, consider using the same. +// Last time I checked the if version got compiled using cmov, which was a lot faster than module (with idiv). +inline int prev(int i, int n) { return i-1 >= 0 ? i-1 : n-1; } +inline int next(int i, int n) { return i+1 < n ? i+1 : 0; } + +inline int area2(const int* a, const int* b, const int* c) +{ + return (b[0] - a[0]) * (c[2] - a[2]) - (c[0] - a[0]) * (b[2] - a[2]); +} + +// Returns true iff c is strictly to the left of the directed +// line through a to b. +inline bool left(const int* a, const int* b, const int* c) +{ + return area2(a, b, c) < 0; +} + +inline bool leftOn(const int* a, const int* b, const int* c) +{ + return area2(a, b, c) <= 0; +} + +inline bool collinear(const int* a, const int* b, const int* c) +{ + return area2(a, b, c) == 0; +} + +// Returns true iff ab properly intersects cd: they share +// a point interior to both segments. The properness of the +// intersection is ensured by using strict leftness. +static bool intersectProp(const int* a, const int* b, const int* c, const int* d) +{ + // Eliminate improper cases. + if (collinear(a,b,c) || collinear(a,b,d) || + collinear(c,d,a) || collinear(c,d,b)) + return false; + + return (left(a,b,c) ^ left(a,b,d)) && (left(c,d,a) ^ left(c,d,b)); +} + +// Returns T iff (a,b,c) are collinear and point c lies +// on the closed segment ab. +static bool between(const int* a, const int* b, const int* c) +{ + if (!collinear(a, b, c)) + return false; + // If ab not vertical, check betweenness on x; else on y. + if (a[0] != b[0]) + return ((a[0] <= c[0]) && (c[0] <= b[0])) || ((a[0] >= c[0]) && (c[0] >= b[0])); + else + return ((a[2] <= c[2]) && (c[2] <= b[2])) || ((a[2] >= c[2]) && (c[2] >= b[2])); +} + +// Returns true iff segments ab and cd intersect, properly or improperly. +static bool intersect(const int* a, const int* b, const int* c, const int* d) +{ + if (intersectProp(a, b, c, d)) + return true; + else if (between(a, b, c) || between(a, b, d) || + between(c, d, a) || between(c, d, b)) + return true; + else + return false; +} + +static bool vequal(const int* a, const int* b) +{ + return a[0] == b[0] && a[2] == b[2]; +} + +static bool intersectSegContour(const int* d0, const int* d1, int i, int n, const int* verts) +{ + // For each edge (k,k+1) of P + for (int k = 0; k < n; k++) + { + int k1 = next(k, n); + // Skip edges incident to i. + if (i == k || i == k1) + continue; + const int* p0 = &verts[k * 4]; + const int* p1 = &verts[k1 * 4]; + if (vequal(d0, p0) || vequal(d1, p0) || vequal(d0, p1) || vequal(d1, p1)) + continue; + + if (intersect(d0, d1, p0, p1)) + return true; + } + return false; +} + +static bool inCone(int i, int n, const int* verts, const int* pj) +{ + const int* pi = &verts[i * 4]; + const int* pi1 = &verts[next(i, n) * 4]; + const int* pin1 = &verts[prev(i, n) * 4]; + + // If P[i] is a convex vertex [ i+1 left or on (i-1,i) ]. + if (leftOn(pin1, pi, pi1)) + return left(pi, pj, pin1) && left(pj, pi, pi1); + // Assume (i-1,i,i+1) not collinear. + // else P[i] is reflex. + return !(leftOn(pi, pj, pi1) && leftOn(pj, pi, pin1)); +} + + +static void removeDegenerateSegments(rcTempVector& simplified) +{ + // Remove adjacent vertices which are equal on xz-plane, + // or else the triangulator will get confused. + int npts = static_cast(simplified.size()) / 4; + for (int i = 0; i < npts; ++i) + { + int ni = next(i, npts); + + if (vequal(&simplified[i*4], &simplified[ni*4])) + { + // Degenerate segment, remove. + for (int j = i; j < simplified.size()/4-1; ++j) + { + simplified[j*4+0] = simplified[(j+1)*4+0]; + simplified[j*4+1] = simplified[(j+1)*4+1]; + simplified[j*4+2] = simplified[(j+1)*4+2]; + simplified[j*4+3] = simplified[(j+1)*4+3]; + } + simplified.resize(simplified.size()-4); + npts--; + } + } +} + + +static bool mergeContours(rcContour& ca, rcContour& cb, int ia, int ib) +{ + const int maxVerts = ca.nverts + cb.nverts + 2; + int* verts = (int*)rcAlloc(sizeof(int)*maxVerts*4, RC_ALLOC_PERM); + if (!verts) + return false; + + int nv = 0; + + // Copy contour A. + for (int i = 0; i <= ca.nverts; ++i) + { + int* dst = &verts[nv*4]; + const int* src = &ca.verts[((ia+i)%ca.nverts)*4]; + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[2]; + dst[3] = src[3]; + nv++; + } + + // Copy contour B + for (int i = 0; i <= cb.nverts; ++i) + { + int* dst = &verts[nv*4]; + const int* src = &cb.verts[((ib+i)%cb.nverts)*4]; + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[2]; + dst[3] = src[3]; + nv++; + } + + rcFree(ca.verts); + ca.verts = verts; + ca.nverts = nv; + + rcFree(cb.verts); + cb.verts = 0; + cb.nverts = 0; + + return true; +} + +struct rcContourHole +{ + rcContour* contour; + int minx, minz, leftmost; +}; + +struct rcContourRegion +{ + rcContour* outline; + rcContourHole* holes; + int nholes; +}; + +struct rcPotentialDiagonal +{ + int vert; + int dist; +}; + +// Finds the lowest leftmost vertex of a contour. +static void findLeftMostVertex(rcContour* contour, int* minx, int* minz, int* leftmost) +{ + *minx = contour->verts[0]; + *minz = contour->verts[2]; + *leftmost = 0; + for (int i = 1; i < contour->nverts; i++) + { + const int x = contour->verts[i*4+0]; + const int z = contour->verts[i*4+2]; + if (x < *minx || (x == *minx && z < *minz)) + { + *minx = x; + *minz = z; + *leftmost = i; + } + } +} + +static int compareHoles(const void* va, const void* vb) +{ + const rcContourHole* a = (const rcContourHole*)va; + const rcContourHole* b = (const rcContourHole*)vb; + if (a->minx == b->minx) + { + if (a->minz < b->minz) + return -1; + if (a->minz > b->minz) + return 1; + } + else + { + if (a->minx < b->minx) + return -1; + if (a->minx > b->minx) + return 1; + } + return 0; +} + + +static int compareDiagDist(const void* va, const void* vb) +{ + const rcPotentialDiagonal* a = (const rcPotentialDiagonal*)va; + const rcPotentialDiagonal* b = (const rcPotentialDiagonal*)vb; + if (a->dist < b->dist) + return -1; + if (a->dist > b->dist) + return 1; + return 0; +} + + +static void mergeRegionHoles(rcContext* ctx, rcContourRegion& region) +{ + // Sort holes from left to right. + for (int i = 0; i < region.nholes; i++) + findLeftMostVertex(region.holes[i].contour, ®ion.holes[i].minx, ®ion.holes[i].minz, ®ion.holes[i].leftmost); + + qsort(region.holes, region.nholes, sizeof(rcContourHole), compareHoles); + + int maxVerts = region.outline->nverts; + for (int i = 0; i < region.nholes; i++) + maxVerts += region.holes[i].contour->nverts; + + rcScopedDelete diags((rcPotentialDiagonal*)rcAlloc(sizeof(rcPotentialDiagonal)*maxVerts, RC_ALLOC_TEMP)); + if (!diags) + { + ctx->log(RC_LOG_WARNING, "mergeRegionHoles: Failed to allocated diags %d.", maxVerts); + return; + } + + rcContour* outline = region.outline; + + // Merge holes into the outline one by one. + for (int i = 0; i < region.nholes; i++) + { + rcContour* hole = region.holes[i].contour; + + int index = -1; + int bestVertex = region.holes[i].leftmost; + for (int iter = 0; iter < hole->nverts; iter++) + { + // Find potential diagonals. + // The 'best' vertex must be in the cone described by 3 consecutive vertices of the outline. + // ..o j-1 + // | + // | * best + // | + // j o-----o j+1 + // : + int ndiags = 0; + const int* corner = &hole->verts[bestVertex*4]; + for (int j = 0; j < outline->nverts; j++) + { + if (inCone(j, outline->nverts, outline->verts, corner)) + { + int dx = outline->verts[j*4+0] - corner[0]; + int dz = outline->verts[j*4+2] - corner[2]; + diags[ndiags].vert = j; + diags[ndiags].dist = dx*dx + dz*dz; + ndiags++; + } + } + // Sort potential diagonals by distance, we want to make the connection as short as possible. + qsort(diags, ndiags, sizeof(rcPotentialDiagonal), compareDiagDist); + + // Find a diagonal that is not intersecting the outline not the remaining holes. + index = -1; + for (int j = 0; j < ndiags; j++) + { + const int* pt = &outline->verts[diags[j].vert*4]; + bool intersect = intersectSegContour(pt, corner, diags[i].vert, outline->nverts, outline->verts); + for (int k = i; k < region.nholes && !intersect; k++) + intersect |= intersectSegContour(pt, corner, -1, region.holes[k].contour->nverts, region.holes[k].contour->verts); + if (!intersect) + { + index = diags[j].vert; + break; + } + } + // If found non-intersecting diagonal, stop looking. + if (index != -1) + break; + // All the potential diagonals for the current vertex were intersecting, try next vertex. + bestVertex = (bestVertex + 1) % hole->nverts; + } + + if (index == -1) + { + ctx->log(RC_LOG_WARNING, "mergeHoles: Failed to find merge points for %p and %p.", region.outline, hole); + continue; + } + if (!mergeContours(*region.outline, *hole, index, bestVertex)) + { + ctx->log(RC_LOG_WARNING, "mergeHoles: Failed to merge contours %p and %p.", region.outline, hole); + continue; + } + } +} + + +/// @par +/// +/// The raw contours will match the region outlines exactly. The @p maxError and @p maxEdgeLen +/// parameters control how closely the simplified contours will match the raw contours. +/// +/// Simplified contours are generated such that the vertices for portals between areas match up. +/// (They are considered mandatory vertices.) +/// +/// Setting @p maxEdgeLength to zero will disabled the edge length feature. +/// +/// See the #rcConfig documentation for more information on the configuration parameters. +/// +/// @see rcAllocContourSet, rcCompactHeightfield, rcContourSet, rcConfig +bool rcBuildContours(rcContext* ctx, const rcCompactHeightfield& chf, + const float maxError, const int maxEdgeLen, + rcContourSet& cset, const int buildFlags) +{ + rcAssert(ctx); + + const int w = chf.width; + const int h = chf.height; + const int borderSize = chf.borderSize; + + rcScopedTimer timer(ctx, RC_TIMER_BUILD_CONTOURS); + + rcVcopy(cset.bmin, chf.bmin); + rcVcopy(cset.bmax, chf.bmax); + if (borderSize > 0) + { + // If the heightfield was build with bordersize, remove the offset. + const float pad = borderSize*chf.cs; + cset.bmin[0] += pad; + cset.bmin[2] += pad; + cset.bmax[0] -= pad; + cset.bmax[2] -= pad; + } + cset.cs = chf.cs; + cset.ch = chf.ch; + cset.width = chf.width - chf.borderSize*2; + cset.height = chf.height - chf.borderSize*2; + cset.borderSize = chf.borderSize; + cset.maxError = maxError; + + int maxContours = rcMax((int)chf.maxRegions, 8); + cset.conts = (rcContour*)rcAlloc(sizeof(rcContour)*maxContours, RC_ALLOC_PERM); + if (!cset.conts) + return false; + cset.nconts = 0; + + rcScopedDelete flags((unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP)); + if (!flags) + { + ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'flags' (%d).", chf.spanCount); + return false; + } + + ctx->startTimer(RC_TIMER_BUILD_CONTOURS_TRACE); + + // Mark boundaries. + for (int y = 0; y < h; ++y) + { + for (int x = 0; x < w; ++x) + { + const rcCompactCell& c = chf.cells[x+y*w]; + for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i) + { + unsigned char res = 0; + const rcCompactSpan& s = chf.spans[i]; + if (!chf.spans[i].reg || (chf.spans[i].reg & RC_BORDER_REG)) + { + flags[i] = 0; + continue; + } + for (int dir = 0; dir < 4; ++dir) + { + unsigned short r = 0; + if (rcGetCon(s, dir) != RC_NOT_CONNECTED) + { + const int ax = x + rcGetDirOffsetX(dir); + const int ay = y + rcGetDirOffsetY(dir); + const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir); + r = chf.spans[ai].reg; + } + if (r == chf.spans[i].reg) + res |= (1 << dir); + } + flags[i] = res ^ 0xf; // Inverse, mark non connected edges. + } + } + } + + ctx->stopTimer(RC_TIMER_BUILD_CONTOURS_TRACE); + + rcTempVector verts(256); + rcTempVector simplified(64); + + for (int y = 0; y < h; ++y) + { + for (int x = 0; x < w; ++x) + { + const rcCompactCell& c = chf.cells[x+y*w]; + for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i) + { + if (flags[i] == 0 || flags[i] == 0xf) + { + flags[i] = 0; + continue; + } + const unsigned short reg = chf.spans[i].reg; + if (!reg || (reg & RC_BORDER_REG)) + continue; + const unsigned char area = chf.areas[i]; + + verts.clear(); + simplified.clear(); + + ctx->startTimer(RC_TIMER_BUILD_CONTOURS_TRACE); + walkContour(x, y, i, chf, flags, verts); + ctx->stopTimer(RC_TIMER_BUILD_CONTOURS_TRACE); + + ctx->startTimer(RC_TIMER_BUILD_CONTOURS_SIMPLIFY); + simplifyContour(verts, simplified, maxError, maxEdgeLen, buildFlags); + removeDegenerateSegments(simplified); + ctx->stopTimer(RC_TIMER_BUILD_CONTOURS_SIMPLIFY); + + + // Store region->contour remap info. + // Create contour. + if (simplified.size()/4 >= 3) + { + if (cset.nconts >= maxContours) + { + // Allocate more contours. + // This happens when a region has holes. + const int oldMax = maxContours; + maxContours *= 2; + rcContour* newConts = (rcContour*)rcAlloc(sizeof(rcContour)*maxContours, RC_ALLOC_PERM); + for (int j = 0; j < cset.nconts; ++j) + { + newConts[j] = cset.conts[j]; + // Reset source pointers to prevent data deletion. + cset.conts[j].verts = 0; + cset.conts[j].rverts = 0; + } + rcFree(cset.conts); + cset.conts = newConts; + + ctx->log(RC_LOG_WARNING, "rcBuildContours: Expanding max contours from %d to %d.", oldMax, maxContours); + } + + rcContour* cont = &cset.conts[cset.nconts++]; + + cont->nverts = static_cast(simplified.size()) / 4; + cont->verts = (int*)rcAlloc(sizeof(int)*cont->nverts*4, RC_ALLOC_PERM); + if (!cont->verts) + { + ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'verts' (%d).", cont->nverts); + return false; + } + memcpy(cont->verts, &simplified[0], sizeof(int)*cont->nverts*4); + if (borderSize > 0) + { + // If the heightfield was build with bordersize, remove the offset. + for (int j = 0; j < cont->nverts; ++j) + { + int* v = &cont->verts[j*4]; + v[0] -= borderSize; + v[2] -= borderSize; + } + } + + cont->nrverts = static_cast(verts.size()) / 4; + cont->rverts = static_cast(rcAlloc(sizeof(int) * cont->nrverts * 4, RC_ALLOC_PERM)); + if (!cont->rverts) + { + ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'rverts' (%d).", cont->nrverts); + return false; + } + memcpy(cont->rverts, &verts[0], sizeof(int)*cont->nrverts*4); + if (borderSize > 0) + { + // If the heightfield was build with bordersize, remove the offset. + for (int j = 0; j < cont->nrverts; ++j) + { + int* v = &cont->rverts[j*4]; + v[0] -= borderSize; + v[2] -= borderSize; + } + } + + cont->reg = reg; + cont->area = area; + } + } + } + } + + // Merge holes if needed. + if (cset.nconts > 0) + { + // Calculate winding of all polygons. + rcScopedDelete winding((signed char*)rcAlloc(sizeof(signed char)*cset.nconts, RC_ALLOC_TEMP)); + if (!winding) + { + ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'hole' (%d).", cset.nconts); + return false; + } + int nholes = 0; + for (int i = 0; i < cset.nconts; ++i) + { + rcContour& cont = cset.conts[i]; + // If the contour is wound backwards, it is a hole. + winding[i] = calcAreaOfPolygon2D(cont.verts, cont.nverts) < 0 ? -1 : 1; + if (winding[i] < 0) + nholes++; + } + + if (nholes > 0) + { + // Collect outline contour and holes contours per region. + // We assume that there is one outline and multiple holes. + const int nregions = chf.maxRegions+1; + rcScopedDelete regions((rcContourRegion*)rcAlloc(sizeof(rcContourRegion)*nregions, RC_ALLOC_TEMP)); + if (!regions) + { + ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'regions' (%d).", nregions); + return false; + } + memset(regions, 0, sizeof(rcContourRegion)*nregions); + + rcScopedDelete holes((rcContourHole*)rcAlloc(sizeof(rcContourHole)*cset.nconts, RC_ALLOC_TEMP)); + if (!holes) + { + ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'holes' (%d).", cset.nconts); + return false; + } + memset(holes, 0, sizeof(rcContourHole)*cset.nconts); + + for (int i = 0; i < cset.nconts; ++i) + { + rcContour& cont = cset.conts[i]; + // Positively would contours are outlines, negative holes. + if (winding[i] > 0) + { + if (regions[cont.reg].outline) + ctx->log(RC_LOG_ERROR, "rcBuildContours: Multiple outlines for region %d.", cont.reg); + regions[cont.reg].outline = &cont; + } + else + { + regions[cont.reg].nholes++; + } + } + int index = 0; + for (int i = 0; i < nregions; i++) + { + if (regions[i].nholes > 0) + { + regions[i].holes = &holes[index]; + index += regions[i].nholes; + regions[i].nholes = 0; + } + } + for (int i = 0; i < cset.nconts; ++i) + { + rcContour& cont = cset.conts[i]; + rcContourRegion& reg = regions[cont.reg]; + if (winding[i] < 0) + reg.holes[reg.nholes++].contour = &cont; + } + + // Finally merge each regions holes into the outline. + for (int i = 0; i < nregions; i++) + { + rcContourRegion& reg = regions[i]; + if (!reg.nholes) continue; + + if (reg.outline) + { + mergeRegionHoles(ctx, reg); + } + else + { + // The region does not have an outline. + // This can happen if the contour becaomes selfoverlapping because of + // too aggressive simplification settings. + ctx->log(RC_LOG_ERROR, "rcBuildContours: Bad outline for region %d, contour simplification is likely too aggressive.", i); + } + } + } + + } + + return true; +} diff --git a/native/third_party/recastnavigation/Recast/Source/RecastFilter.cpp b/native/third_party/recastnavigation/Recast/Source/RecastFilter.cpp new file mode 100644 index 0000000..7875040 --- /dev/null +++ b/native/third_party/recastnavigation/Recast/Source/RecastFilter.cpp @@ -0,0 +1,201 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#include "Recast.h" +#include "RecastAssert.h" + +#include + +namespace +{ + const int MAX_HEIGHTFIELD_HEIGHT = 0xffff; // TODO (graham): Move this to a more visible constant and update usages. +} + +void rcFilterLowHangingWalkableObstacles(rcContext* context, const int walkableClimb, rcHeightfield& heightfield) +{ + rcAssert(context); + + rcScopedTimer timer(context, RC_TIMER_FILTER_LOW_OBSTACLES); + + const int xSize = heightfield.width; + const int zSize = heightfield.height; + + for (int z = 0; z < zSize; ++z) + { + for (int x = 0; x < xSize; ++x) + { + rcSpan* previousSpan = NULL; + bool previousWasWalkable = false; + unsigned char previousAreaID = RC_NULL_AREA; + + // For each span in the column... + for (rcSpan* span = heightfield.spans[x + z * xSize]; span != NULL; previousSpan = span, span = span->next) + { + const bool walkable = span->area != RC_NULL_AREA; + + // If current span is not walkable, but there is walkable span just below it and the height difference + // is small enough for the agent to walk over, mark the current span as walkable too. + if (!walkable && previousWasWalkable && (int)span->smax - (int)previousSpan->smax <= walkableClimb) + { + span->area = previousAreaID; + } + + // Copy the original walkable value regardless of whether we changed it. + // This prevents multiple consecutive non-walkable spans from being erroneously marked as walkable. + previousWasWalkable = walkable; + previousAreaID = span->area; + } + } + } +} + +void rcFilterLedgeSpans(rcContext* context, const int walkableHeight, const int walkableClimb, rcHeightfield& heightfield) +{ + rcAssert(context); + + rcScopedTimer timer(context, RC_TIMER_FILTER_BORDER); + + const int xSize = heightfield.width; + const int zSize = heightfield.height; + + // Mark spans that are adjacent to a ledge as unwalkable.. + for (int z = 0; z < zSize; ++z) + { + for (int x = 0; x < xSize; ++x) + { + for (rcSpan* span = heightfield.spans[x + z * xSize]; span; span = span->next) + { + // Skip non-walkable spans. + if (span->area == RC_NULL_AREA) + { + continue; + } + + const int floor = (int)(span->smax); + const int ceiling = span->next ? (int)(span->next->smin) : MAX_HEIGHTFIELD_HEIGHT; + + // The difference between this walkable area and the lowest neighbor walkable area. + // This is the difference between the current span and all neighbor spans that have + // enough space for an agent to move between, but not accounting at all for surface slope. + int lowestNeighborFloorDifference = MAX_HEIGHTFIELD_HEIGHT; + + // Min and max height of accessible neighbours. + int lowestTraversableNeighborFloor = span->smax; + int highestTraversableNeighborFloor = span->smax; + + for (int direction = 0; direction < 4; ++direction) + { + const int neighborX = x + rcGetDirOffsetX(direction); + const int neighborZ = z + rcGetDirOffsetY(direction); + + // Skip neighbours which are out of bounds. + if (neighborX < 0 || neighborZ < 0 || neighborX >= xSize || neighborZ >= zSize) + { + lowestNeighborFloorDifference = -walkableClimb - 1; + break; + } + + const rcSpan* neighborSpan = heightfield.spans[neighborX + neighborZ * xSize]; + + // The most we can step down to the neighbor is the walkableClimb distance. + // Start with the area under the neighbor span + int neighborCeiling = neighborSpan ? (int)neighborSpan->smin : MAX_HEIGHTFIELD_HEIGHT; + + // Skip neighbour if the gap between the spans is too small. + if (rcMin(ceiling, neighborCeiling) - floor >= walkableHeight) + { + lowestNeighborFloorDifference = (-walkableClimb - 1); + break; + } + + // For each span in the neighboring column... + for (; neighborSpan != NULL; neighborSpan = neighborSpan->next) + { + const int neighborFloor = (int)neighborSpan->smax; + neighborCeiling = neighborSpan->next ? (int)neighborSpan->next->smin : MAX_HEIGHTFIELD_HEIGHT; + + // Only consider neighboring areas that have enough overlap to be potentially traversable. + if (rcMin(ceiling, neighborCeiling) - rcMax(floor, neighborFloor) < walkableHeight) + { + // No space to traverse between them. + continue; + } + + const int neighborFloorDifference = neighborFloor - floor; + lowestNeighborFloorDifference = rcMin(lowestNeighborFloorDifference, neighborFloorDifference); + + // Find min/max accessible neighbor height. + // Only consider neighbors that are at most walkableClimb away. + if (rcAbs(neighborFloorDifference) <= walkableClimb) + { + // There is space to move to the neighbor cell and the slope isn't too much. + lowestTraversableNeighborFloor = rcMin(lowestTraversableNeighborFloor, neighborFloor); + highestTraversableNeighborFloor = rcMax(highestTraversableNeighborFloor, neighborFloor); + } + else if (neighborFloorDifference < -walkableClimb) + { + // We already know this will be considered a ledge span so we can early-out + break; + } + } + } + + // The current span is close to a ledge if the magnitude of the drop to any neighbour span is greater than the walkableClimb distance. + // That is, there is a gap that is large enough to let an agent move between them, but the drop (surface slope) is too large to allow it. + // (If this is the case, then biggestNeighborStepDown will be negative, so compare against the negative walkableClimb as a means of checking + // the magnitude of the delta) + if (lowestNeighborFloorDifference < -walkableClimb) + { + span->area = RC_NULL_AREA; + } + // If the difference between all neighbor floors is too large, this is a steep slope, so mark the span as an unwalkable ledge. + else if (highestTraversableNeighborFloor - lowestTraversableNeighborFloor > walkableClimb) + { + span->area = RC_NULL_AREA; + } + } + } + } +} + +void rcFilterWalkableLowHeightSpans(rcContext* context, const int walkableHeight, rcHeightfield& heightfield) +{ + rcAssert(context); + rcScopedTimer timer(context, RC_TIMER_FILTER_WALKABLE); + + const int xSize = heightfield.width; + const int zSize = heightfield.height; + + // Remove walkable flag from spans which do not have enough + // space above them for the agent to stand there. + for (int z = 0; z < zSize; ++z) + { + for (int x = 0; x < xSize; ++x) + { + for (rcSpan* span = heightfield.spans[x + z*xSize]; span; span = span->next) + { + const int floor = (int)(span->smax); + const int ceiling = span->next ? (int)(span->next->smin) : MAX_HEIGHTFIELD_HEIGHT; + if (ceiling - floor < walkableHeight) + { + span->area = RC_NULL_AREA; + } + } + } + } +} diff --git a/native/third_party/recastnavigation/Recast/Source/RecastLayers.cpp b/native/third_party/recastnavigation/Recast/Source/RecastLayers.cpp new file mode 100644 index 0000000..ca37ebb --- /dev/null +++ b/native/third_party/recastnavigation/Recast/Source/RecastLayers.cpp @@ -0,0 +1,656 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#include +#include +#include +#include +#include +#include "Recast.h" +#include "RecastAlloc.h" +#include "RecastAssert.h" + + +// Must be 255 or smaller (not 256) because layer IDs are stored as +// a byte where 255 is a special value. +#ifndef RC_MAX_LAYERS_DEF +#define RC_MAX_LAYERS_DEF 63 +#endif + +#if RC_MAX_LAYERS_DEF > 255 +#error RC_MAX_LAYERS_DEF must be 255 or smaller +#endif + +#ifndef RC_MAX_NEIS_DEF +#define RC_MAX_NEIS_DEF 16 +#endif + +// Keep type checking. +static const int RC_MAX_LAYERS = RC_MAX_LAYERS_DEF; +static const int RC_MAX_NEIS = RC_MAX_NEIS_DEF; + +struct rcLayerRegion +{ + unsigned char layers[RC_MAX_LAYERS]; + unsigned char neis[RC_MAX_NEIS]; + unsigned short ymin, ymax; + unsigned char layerId; // Layer ID + unsigned char nlayers; // Layer count + unsigned char nneis; // Neighbour count + unsigned char base; // Flag indicating if the region is the base of merged regions. +}; + + +static bool contains(const unsigned char* a, const unsigned char an, const unsigned char v) +{ + const int n = (int)an; + for (int i = 0; i < n; ++i) + { + if (a[i] == v) + return true; + } + return false; +} + +static bool addUnique(unsigned char* a, unsigned char& an, int anMax, unsigned char v) +{ + if (contains(a, an, v)) + return true; + + if ((int)an >= anMax) + return false; + + a[an] = v; + an++; + return true; +} + + +inline bool overlapRange(const unsigned short amin, const unsigned short amax, + const unsigned short bmin, const unsigned short bmax) +{ + return (amin > bmax || amax < bmin) ? false : true; +} + + + +struct rcLayerSweepSpan +{ + unsigned short ns; // number samples + unsigned char id; // region id + unsigned char nei; // neighbour id +}; + +/// @par +/// +/// See the #rcConfig documentation for more information on the configuration parameters. +/// +/// @see rcAllocHeightfieldLayerSet, rcCompactHeightfield, rcHeightfieldLayerSet, rcConfig +bool rcBuildHeightfieldLayers(rcContext* ctx, const rcCompactHeightfield& chf, + const int borderSize, const int walkableHeight, + rcHeightfieldLayerSet& lset) +{ + rcAssert(ctx); + + rcScopedTimer timer(ctx, RC_TIMER_BUILD_LAYERS); + + const int w = chf.width; + const int h = chf.height; + + rcScopedDelete srcReg((unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP)); + if (!srcReg) + { + ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'srcReg' (%d).", chf.spanCount); + return false; + } + memset(srcReg,0xff,sizeof(unsigned char)*chf.spanCount); + + const int nsweeps = chf.width; + rcScopedDelete sweeps((rcLayerSweepSpan*)rcAlloc(sizeof(rcLayerSweepSpan)*nsweeps, RC_ALLOC_TEMP)); + if (!sweeps) + { + ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'sweeps' (%d).", nsweeps); + return false; + } + + + // Partition walkable area into monotone regions. + int prevCount[256]; + unsigned char regId = 0; + + for (int y = borderSize; y < h-borderSize; ++y) + { + memset(prevCount,0,sizeof(int)*regId); + unsigned char sweepId = 0; + + for (int x = borderSize; x < w-borderSize; ++x) + { + const rcCompactCell& c = chf.cells[x+y*w]; + + for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i) + { + const rcCompactSpan& s = chf.spans[i]; + if (chf.areas[i] == RC_NULL_AREA) continue; + + unsigned char sid = 0xff; + + // -x + if (rcGetCon(s, 0) != RC_NOT_CONNECTED) + { + const int ax = x + rcGetDirOffsetX(0); + const int ay = y + rcGetDirOffsetY(0); + const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 0); + if (chf.areas[ai] != RC_NULL_AREA && srcReg[ai] != 0xff) + sid = srcReg[ai]; + } + + if (sid == 0xff) + { + sid = sweepId++; + sweeps[sid].nei = 0xff; + sweeps[sid].ns = 0; + } + + // -y + if (rcGetCon(s,3) != RC_NOT_CONNECTED) + { + const int ax = x + rcGetDirOffsetX(3); + const int ay = y + rcGetDirOffsetY(3); + const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 3); + const unsigned char nr = srcReg[ai]; + if (nr != 0xff) + { + // Set neighbour when first valid neighbour is encoutered. + if (sweeps[sid].ns == 0) + sweeps[sid].nei = nr; + + if (sweeps[sid].nei == nr) + { + // Update existing neighbour + sweeps[sid].ns++; + prevCount[nr]++; + } + else + { + // This is hit if there is nore than one neighbour. + // Invalidate the neighbour. + sweeps[sid].nei = 0xff; + } + } + } + + srcReg[i] = sid; + } + } + + // Create unique ID. + for (int i = 0; i < sweepId; ++i) + { + // If the neighbour is set and there is only one continuous connection to it, + // the sweep will be merged with the previous one, else new region is created. + if (sweeps[i].nei != 0xff && prevCount[sweeps[i].nei] == (int)sweeps[i].ns) + { + sweeps[i].id = sweeps[i].nei; + } + else + { + if (regId == 255) + { + ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Region ID overflow."); + return false; + } + sweeps[i].id = regId++; + } + } + + // Remap local sweep ids to region ids. + for (int x = borderSize; x < w-borderSize; ++x) + { + const rcCompactCell& c = chf.cells[x+y*w]; + for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i) + { + if (srcReg[i] != 0xff) + srcReg[i] = sweeps[srcReg[i]].id; + } + } + } + + // Allocate and init layer regions. + const int nregs = (int)regId; + rcScopedDelete regs((rcLayerRegion*)rcAlloc(sizeof(rcLayerRegion)*nregs, RC_ALLOC_TEMP)); + if (!regs) + { + ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'regs' (%d).", nregs); + return false; + } + memset(regs, 0, sizeof(rcLayerRegion)*nregs); + for (int i = 0; i < nregs; ++i) + { + regs[i].layerId = 0xff; + regs[i].ymin = 0xffff; + regs[i].ymax = 0; + } + + // Find region neighbours and overlapping regions. + for (int y = 0; y < h; ++y) + { + for (int x = 0; x < w; ++x) + { + const rcCompactCell& c = chf.cells[x+y*w]; + + unsigned char lregs[RC_MAX_LAYERS]; + int nlregs = 0; + + for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i) + { + const rcCompactSpan& s = chf.spans[i]; + const unsigned char ri = srcReg[i]; + if (ri == 0xff) continue; + + regs[ri].ymin = rcMin(regs[ri].ymin, s.y); + regs[ri].ymax = rcMax(regs[ri].ymax, s.y); + + // Collect all region layers. + if (nlregs < RC_MAX_LAYERS) + lregs[nlregs++] = ri; + + // Update neighbours + for (int dir = 0; dir < 4; ++dir) + { + if (rcGetCon(s, dir) != RC_NOT_CONNECTED) + { + const int ax = x + rcGetDirOffsetX(dir); + const int ay = y + rcGetDirOffsetY(dir); + const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir); + const unsigned char rai = srcReg[ai]; + if (rai != 0xff && rai != ri) + { + // Don't check return value -- if we cannot add the neighbor + // it will just cause a few more regions to be created, which + // is fine. + addUnique(regs[ri].neis, regs[ri].nneis, RC_MAX_NEIS, rai); + } + } + } + + } + + // Update overlapping regions. + for (int i = 0; i < nlregs-1; ++i) + { + for (int j = i+1; j < nlregs; ++j) + { + if (lregs[i] != lregs[j]) + { + rcLayerRegion& ri = regs[lregs[i]]; + rcLayerRegion& rj = regs[lregs[j]]; + + if (!addUnique(ri.layers, ri.nlayers, RC_MAX_LAYERS, lregs[j]) || + !addUnique(rj.layers, rj.nlayers, RC_MAX_LAYERS, lregs[i])) + { + ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: layer overflow (too many overlapping walkable platforms). Try increasing RC_MAX_LAYERS."); + return false; + } + } + } + } + + } + } + + // Create 2D layers from regions. + unsigned char layerId = 0; + + static const int MAX_STACK = 64; + unsigned char stack[MAX_STACK]; + int nstack = 0; + + for (int i = 0; i < nregs; ++i) + { + rcLayerRegion& root = regs[i]; + // Skip already visited. + if (root.layerId != 0xff) + continue; + + // Start search. + root.layerId = layerId; + root.base = 1; + + nstack = 0; + stack[nstack++] = (unsigned char)i; + + while (nstack) + { + // Pop front + rcLayerRegion& reg = regs[stack[0]]; + nstack--; + for (int j = 0; j < nstack; ++j) + stack[j] = stack[j+1]; + + const int nneis = (int)reg.nneis; + for (int j = 0; j < nneis; ++j) + { + const unsigned char nei = reg.neis[j]; + rcLayerRegion& regn = regs[nei]; + // Skip already visited. + if (regn.layerId != 0xff) + continue; + // Skip if the neighbour is overlapping root region. + if (contains(root.layers, root.nlayers, nei)) + continue; + // Skip if the height range would become too large. + const int ymin = rcMin(root.ymin, regn.ymin); + const int ymax = rcMax(root.ymax, regn.ymax); + if ((ymax - ymin) >= 255) + continue; + + if (nstack < MAX_STACK) + { + // Deepen + stack[nstack++] = (unsigned char)nei; + + // Mark layer id + regn.layerId = layerId; + // Merge current layers to root. + for (int k = 0; k < regn.nlayers; ++k) + { + if (!addUnique(root.layers, root.nlayers, RC_MAX_LAYERS, regn.layers[k])) + { + ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: layer overflow (too many overlapping walkable platforms). Try increasing RC_MAX_LAYERS."); + return false; + } + } + root.ymin = rcMin(root.ymin, regn.ymin); + root.ymax = rcMax(root.ymax, regn.ymax); + } + } + } + + layerId++; + } + + // Merge non-overlapping regions that are close in height. + const unsigned short mergeHeight = (unsigned short)walkableHeight * 4; + + for (int i = 0; i < nregs; ++i) + { + rcLayerRegion& ri = regs[i]; + if (!ri.base) continue; + + unsigned char newId = ri.layerId; + + for (;;) + { + unsigned char oldId = 0xff; + + for (int j = 0; j < nregs; ++j) + { + if (i == j) continue; + rcLayerRegion& rj = regs[j]; + if (!rj.base) continue; + + // Skip if the regions are not close to each other. + if (!overlapRange(ri.ymin,ri.ymax+mergeHeight, rj.ymin,rj.ymax+mergeHeight)) + continue; + // Skip if the height range would become too large. + const int ymin = rcMin(ri.ymin, rj.ymin); + const int ymax = rcMax(ri.ymax, rj.ymax); + if ((ymax - ymin) >= 255) + continue; + + // Make sure that there is no overlap when merging 'ri' and 'rj'. + bool overlap = false; + // Iterate over all regions which have the same layerId as 'rj' + for (int k = 0; k < nregs; ++k) + { + if (regs[k].layerId != rj.layerId) + continue; + // Check if region 'k' is overlapping region 'ri' + // Index to 'regs' is the same as region id. + if (contains(ri.layers,ri.nlayers, (unsigned char)k)) + { + overlap = true; + break; + } + } + // Cannot merge of regions overlap. + if (overlap) + continue; + + // Can merge i and j. + oldId = rj.layerId; + break; + } + + // Could not find anything to merge with, stop. + if (oldId == 0xff) + break; + + // Merge + for (int j = 0; j < nregs; ++j) + { + rcLayerRegion& rj = regs[j]; + if (rj.layerId == oldId) + { + rj.base = 0; + // Remap layerIds. + rj.layerId = newId; + // Add overlaid layers from 'rj' to 'ri'. + for (int k = 0; k < rj.nlayers; ++k) + { + if (!addUnique(ri.layers, ri.nlayers, RC_MAX_LAYERS, rj.layers[k])) + { + ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: layer overflow (too many overlapping walkable platforms). Try increasing RC_MAX_LAYERS."); + return false; + } + } + + // Update height bounds. + ri.ymin = rcMin(ri.ymin, rj.ymin); + ri.ymax = rcMax(ri.ymax, rj.ymax); + } + } + } + } + + // Compact layerIds + unsigned char remap[256]; + memset(remap, 0, 256); + + // Find number of unique layers. + layerId = 0; + for (int i = 0; i < nregs; ++i) + remap[regs[i].layerId] = 1; + for (int i = 0; i < 256; ++i) + { + if (remap[i]) + remap[i] = layerId++; + else + remap[i] = 0xff; + } + // Remap ids. + for (int i = 0; i < nregs; ++i) + regs[i].layerId = remap[regs[i].layerId]; + + // No layers, return empty. + if (layerId == 0) + return true; + + // Create layers. + rcAssert(lset.layers == 0); + + const int lw = w - borderSize*2; + const int lh = h - borderSize*2; + + // Build contracted bbox for layers. + float bmin[3], bmax[3]; + rcVcopy(bmin, chf.bmin); + rcVcopy(bmax, chf.bmax); + bmin[0] += borderSize*chf.cs; + bmin[2] += borderSize*chf.cs; + bmax[0] -= borderSize*chf.cs; + bmax[2] -= borderSize*chf.cs; + + lset.nlayers = (int)layerId; + + lset.layers = (rcHeightfieldLayer*)rcAlloc(sizeof(rcHeightfieldLayer)*lset.nlayers, RC_ALLOC_PERM); + if (!lset.layers) + { + ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'layers' (%d).", lset.nlayers); + return false; + } + memset(lset.layers, 0, sizeof(rcHeightfieldLayer)*lset.nlayers); + + + // Store layers. + for (int i = 0; i < lset.nlayers; ++i) + { + unsigned char curId = (unsigned char)i; + + rcHeightfieldLayer* layer = &lset.layers[i]; + + const int gridSize = sizeof(unsigned char)*lw*lh; + + layer->heights = (unsigned char*)rcAlloc(gridSize, RC_ALLOC_PERM); + if (!layer->heights) + { + ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'heights' (%d).", gridSize); + return false; + } + memset(layer->heights, 0xff, gridSize); + + layer->areas = (unsigned char*)rcAlloc(gridSize, RC_ALLOC_PERM); + if (!layer->areas) + { + ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'areas' (%d).", gridSize); + return false; + } + memset(layer->areas, 0, gridSize); + + layer->cons = (unsigned char*)rcAlloc(gridSize, RC_ALLOC_PERM); + if (!layer->cons) + { + ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'cons' (%d).", gridSize); + return false; + } + memset(layer->cons, 0, gridSize); + + // Find layer height bounds. + int hmin = 0, hmax = 0; + for (int j = 0; j < nregs; ++j) + { + if (regs[j].base && regs[j].layerId == curId) + { + hmin = (int)regs[j].ymin; + hmax = (int)regs[j].ymax; + } + } + + layer->width = lw; + layer->height = lh; + layer->cs = chf.cs; + layer->ch = chf.ch; + + // Adjust the bbox to fit the heightfield. + rcVcopy(layer->bmin, bmin); + rcVcopy(layer->bmax, bmax); + layer->bmin[1] = bmin[1] + hmin*chf.ch; + layer->bmax[1] = bmin[1] + hmax*chf.ch; + layer->hmin = hmin; + layer->hmax = hmax; + + // Update usable data region. + layer->minx = layer->width; + layer->maxx = 0; + layer->miny = layer->height; + layer->maxy = 0; + + // Copy height and area from compact heightfield. + for (int y = 0; y < lh; ++y) + { + for (int x = 0; x < lw; ++x) + { + const int cx = borderSize+x; + const int cy = borderSize+y; + const rcCompactCell& c = chf.cells[cx+cy*w]; + for (int j = (int)c.index, nj = (int)(c.index+c.count); j < nj; ++j) + { + const rcCompactSpan& s = chf.spans[j]; + // Skip unassigned regions. + if (srcReg[j] == 0xff) + continue; + // Skip of does nto belong to current layer. + unsigned char lid = regs[srcReg[j]].layerId; + if (lid != curId) + continue; + + // Update data bounds. + layer->minx = rcMin(layer->minx, x); + layer->maxx = rcMax(layer->maxx, x); + layer->miny = rcMin(layer->miny, y); + layer->maxy = rcMax(layer->maxy, y); + + // Store height and area type. + const int idx = x+y*lw; + layer->heights[idx] = (unsigned char)(s.y - hmin); + layer->areas[idx] = chf.areas[j]; + + // Check connection. + unsigned char portal = 0; + unsigned char con = 0; + for (int dir = 0; dir < 4; ++dir) + { + if (rcGetCon(s, dir) != RC_NOT_CONNECTED) + { + const int ax = cx + rcGetDirOffsetX(dir); + const int ay = cy + rcGetDirOffsetY(dir); + const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir); + unsigned char alid = srcReg[ai] != 0xff ? regs[srcReg[ai]].layerId : 0xff; + // Portal mask + if (chf.areas[ai] != RC_NULL_AREA && lid != alid) + { + portal |= (unsigned char)(1< hmin) + layer->heights[idx] = rcMax(layer->heights[idx], (unsigned char)(as.y - hmin)); + } + // Valid connection mask + if (chf.areas[ai] != RC_NULL_AREA && lid == alid) + { + const int nx = ax - borderSize; + const int ny = ay - borderSize; + if (nx >= 0 && ny >= 0 && nx < lw && ny < lh) + con |= (unsigned char)(1<cons[idx] = (portal << 4) | con; + } + } + } + + if (layer->minx > layer->maxx) + layer->minx = layer->maxx = 0; + if (layer->miny > layer->maxy) + layer->miny = layer->maxy = 0; + } + + return true; +} diff --git a/native/third_party/recastnavigation/Recast/Source/RecastMesh.cpp b/native/third_party/recastnavigation/Recast/Source/RecastMesh.cpp new file mode 100644 index 0000000..98e15cd --- /dev/null +++ b/native/third_party/recastnavigation/Recast/Source/RecastMesh.cpp @@ -0,0 +1,1541 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#include +#include +#include +#include "Recast.h" +#include "RecastAlloc.h" +#include "RecastAssert.h" + +struct rcEdge +{ + unsigned short vert[2]; + unsigned short polyEdge[2]; + unsigned short poly[2]; +}; + +static bool buildMeshAdjacency(unsigned short* polys, const int npolys, + const int nverts, const int vertsPerPoly) +{ + // Based on code by Eric Lengyel from: + // https://web.archive.org/web/20080704083314/http://www.terathon.com/code/edges.php + + int maxEdgeCount = npolys*vertsPerPoly; + unsigned short* firstEdge = (unsigned short*)rcAlloc(sizeof(unsigned short)*(nverts + maxEdgeCount), RC_ALLOC_TEMP); + if (!firstEdge) + return false; + unsigned short* nextEdge = firstEdge + nverts; + int edgeCount = 0; + + rcEdge* edges = (rcEdge*)rcAlloc(sizeof(rcEdge)*maxEdgeCount, RC_ALLOC_TEMP); + if (!edges) + { + rcFree(firstEdge); + return false; + } + + for (int i = 0; i < nverts; i++) + firstEdge[i] = RC_MESH_NULL_IDX; + + for (int i = 0; i < npolys; ++i) + { + unsigned short* t = &polys[i*vertsPerPoly*2]; + for (int j = 0; j < vertsPerPoly; ++j) + { + if (t[j] == RC_MESH_NULL_IDX) break; + unsigned short v0 = t[j]; + unsigned short v1 = (j+1 >= vertsPerPoly || t[j+1] == RC_MESH_NULL_IDX) ? t[0] : t[j+1]; + if (v0 < v1) + { + rcEdge& edge = edges[edgeCount]; + edge.vert[0] = v0; + edge.vert[1] = v1; + edge.poly[0] = (unsigned short)i; + edge.polyEdge[0] = (unsigned short)j; + edge.poly[1] = (unsigned short)i; + edge.polyEdge[1] = 0; + // Insert edge + nextEdge[edgeCount] = firstEdge[v0]; + firstEdge[v0] = (unsigned short)edgeCount; + edgeCount++; + } + } + } + + for (int i = 0; i < npolys; ++i) + { + unsigned short* t = &polys[i*vertsPerPoly*2]; + for (int j = 0; j < vertsPerPoly; ++j) + { + if (t[j] == RC_MESH_NULL_IDX) break; + unsigned short v0 = t[j]; + unsigned short v1 = (j+1 >= vertsPerPoly || t[j+1] == RC_MESH_NULL_IDX) ? t[0] : t[j+1]; + if (v0 > v1) + { + for (unsigned short e = firstEdge[v1]; e != RC_MESH_NULL_IDX; e = nextEdge[e]) + { + rcEdge& edge = edges[e]; + if (edge.vert[1] == v0 && edge.poly[0] == edge.poly[1]) + { + edge.poly[1] = (unsigned short)i; + edge.polyEdge[1] = (unsigned short)j; + break; + } + } + } + } + } + + // Store adjacency + for (int i = 0; i < edgeCount; ++i) + { + const rcEdge& e = edges[i]; + if (e.poly[0] != e.poly[1]) + { + unsigned short* p0 = &polys[e.poly[0]*vertsPerPoly*2]; + unsigned short* p1 = &polys[e.poly[1]*vertsPerPoly*2]; + p0[vertsPerPoly + e.polyEdge[0]] = e.poly[1]; + p1[vertsPerPoly + e.polyEdge[1]] = e.poly[0]; + } + } + + rcFree(firstEdge); + rcFree(edges); + + return true; +} + + +static const int VERTEX_BUCKET_COUNT = (1<<12); + +inline int computeVertexHash(int x, int y, int z) +{ + const unsigned int h1 = 0x8da6b343; // Large multiplicative constants; + const unsigned int h2 = 0xd8163841; // here arbitrarily chosen primes + const unsigned int h3 = 0xcb1ab31f; + unsigned int n = h1 * x + h2 * y + h3 * z; + return (int)(n & (VERTEX_BUCKET_COUNT-1)); +} + +static unsigned short addVertex(unsigned short x, unsigned short y, unsigned short z, + unsigned short* verts, int* firstVert, int* nextVert, int& nv) +{ + int bucket = computeVertexHash(x, 0, z); + int i = firstVert[bucket]; + + while (i != -1) + { + const unsigned short* v = &verts[i*3]; + if (v[0] == x && (rcAbs(v[1] - y) <= 2) && v[2] == z) + return (unsigned short)i; + i = nextVert[i]; // next + } + + // Could not find, create new. + i = nv; nv++; + unsigned short* v = &verts[i*3]; + v[0] = x; + v[1] = y; + v[2] = z; + nextVert[i] = firstVert[bucket]; + firstVert[bucket] = i; + + return (unsigned short)i; +} + +// Last time I checked the if version got compiled using cmov, which was a lot faster than module (with idiv). +inline int prev(int i, int n) { return i-1 >= 0 ? i-1 : n-1; } +inline int next(int i, int n) { return i+1 < n ? i+1 : 0; } + +inline int area2(const int* a, const int* b, const int* c) +{ + return (b[0] - a[0]) * (c[2] - a[2]) - (c[0] - a[0]) * (b[2] - a[2]); +} + +// Returns true iff c is strictly to the left of the directed +// line through a to b. +inline bool left(const int* a, const int* b, const int* c) +{ + return area2(a, b, c) < 0; +} + +inline bool leftOn(const int* a, const int* b, const int* c) +{ + return area2(a, b, c) <= 0; +} + +inline bool collinear(const int* a, const int* b, const int* c) +{ + return area2(a, b, c) == 0; +} + +// Returns true iff ab properly intersects cd: they share +// a point interior to both segments. The properness of the +// intersection is ensured by using strict leftness. +static bool intersectProp(const int* a, const int* b, const int* c, const int* d) +{ + // Eliminate improper cases. + if (collinear(a,b,c) || collinear(a,b,d) || + collinear(c,d,a) || collinear(c,d,b)) + return false; + + return (left(a,b,c) ^ left(a,b,d)) && (left(c,d,a) ^ left(c,d,b)); +} + +// Returns T iff (a,b,c) are collinear and point c lies +// on the closed segement ab. +static bool between(const int* a, const int* b, const int* c) +{ + if (!collinear(a, b, c)) + return false; + // If ab not vertical, check betweenness on x; else on y. + if (a[0] != b[0]) + return ((a[0] <= c[0]) && (c[0] <= b[0])) || ((a[0] >= c[0]) && (c[0] >= b[0])); + + return ((a[2] <= c[2]) && (c[2] <= b[2])) || ((a[2] >= c[2]) && (c[2] >= b[2])); +} + +// Returns true iff segments ab and cd intersect, properly or improperly. +static bool intersect(const int* a, const int* b, const int* c, const int* d) +{ + if (intersectProp(a, b, c, d)) + return true; + + if (between(a, b, c) || between(a, b, d) || + between(c, d, a) || between(c, d, b)) + return true; + + return false; +} + +static bool vequal(const int* a, const int* b) +{ + return a[0] == b[0] && a[2] == b[2]; +} + +// Returns T iff (v_i, v_j) is a proper internal *or* external +// diagonal of P, *ignoring edges incident to v_i and v_j*. +static bool diagonalie(int i, int j, int n, const int* verts, int* indices) +{ + const int* d0 = &verts[(indices[i] & 0x0fffffff) * 4]; + const int* d1 = &verts[(indices[j] & 0x0fffffff) * 4]; + + // For each edge (k,k+1) of P + for (int k = 0; k < n; k++) + { + int k1 = next(k, n); + // Skip edges incident to i or j + if (!((k == i) || (k1 == i) || (k == j) || (k1 == j))) + { + const int* p0 = &verts[(indices[k] & 0x0fffffff) * 4]; + const int* p1 = &verts[(indices[k1] & 0x0fffffff) * 4]; + + if (vequal(d0, p0) || vequal(d1, p0) || vequal(d0, p1) || vequal(d1, p1)) + continue; + + if (intersect(d0, d1, p0, p1)) + return false; + } + } + return true; +} + +// Returns true iff the diagonal (i,j) is strictly internal to the +// polygon P in the neighborhood of the i endpoint. +static bool inCone(int i, int j, int n, const int* verts, int* indices) +{ + const int* pi = &verts[(indices[i] & 0x0fffffff) * 4]; + const int* pj = &verts[(indices[j] & 0x0fffffff) * 4]; + const int* pi1 = &verts[(indices[next(i, n)] & 0x0fffffff) * 4]; + const int* pin1 = &verts[(indices[prev(i, n)] & 0x0fffffff) * 4]; + + // If P[i] is a convex vertex [ i+1 left or on (i-1,i) ]. + if (leftOn(pin1, pi, pi1)) + return left(pi, pj, pin1) && left(pj, pi, pi1); + // Assume (i-1,i,i+1) not collinear. + // else P[i] is reflex. + return !(leftOn(pi, pj, pi1) && leftOn(pj, pi, pin1)); +} + +// Returns T iff (v_i, v_j) is a proper internal +// diagonal of P. +static bool diagonal(int i, int j, int n, const int* verts, int* indices) +{ + return inCone(i, j, n, verts, indices) && diagonalie(i, j, n, verts, indices); +} + + +static bool diagonalieLoose(int i, int j, int n, const int* verts, int* indices) +{ + const int* d0 = &verts[(indices[i] & 0x0fffffff) * 4]; + const int* d1 = &verts[(indices[j] & 0x0fffffff) * 4]; + + // For each edge (k,k+1) of P + for (int k = 0; k < n; k++) + { + int k1 = next(k, n); + // Skip edges incident to i or j + if (!((k == i) || (k1 == i) || (k == j) || (k1 == j))) + { + const int* p0 = &verts[(indices[k] & 0x0fffffff) * 4]; + const int* p1 = &verts[(indices[k1] & 0x0fffffff) * 4]; + + if (vequal(d0, p0) || vequal(d1, p0) || vequal(d0, p1) || vequal(d1, p1)) + continue; + + if (intersectProp(d0, d1, p0, p1)) + return false; + } + } + return true; +} + +static bool inConeLoose(int i, int j, int n, const int* verts, int* indices) +{ + const int* pi = &verts[(indices[i] & 0x0fffffff) * 4]; + const int* pj = &verts[(indices[j] & 0x0fffffff) * 4]; + const int* pi1 = &verts[(indices[next(i, n)] & 0x0fffffff) * 4]; + const int* pin1 = &verts[(indices[prev(i, n)] & 0x0fffffff) * 4]; + + // If P[i] is a convex vertex [ i+1 left or on (i-1,i) ]. + if (leftOn(pin1, pi, pi1)) + return leftOn(pi, pj, pin1) && leftOn(pj, pi, pi1); + // Assume (i-1,i,i+1) not collinear. + // else P[i] is reflex. + return !(leftOn(pi, pj, pi1) && leftOn(pj, pi, pin1)); +} + +static bool diagonalLoose(int i, int j, int n, const int* verts, int* indices) +{ + return inConeLoose(i, j, n, verts, indices) && diagonalieLoose(i, j, n, verts, indices); +} + + +static int triangulate(int n, const int* verts, int* indices, int* tris) +{ + int ntris = 0; + int* dst = tris; + + // The last bit of the index is used to indicate if the vertex can be removed. + for (int i = 0; i < n; i++) + { + int i1 = next(i, n); + int i2 = next(i1, n); + if (diagonal(i, i2, n, verts, indices)) + indices[i1] |= 0x80000000; + } + + while (n > 3) + { + int minLen = -1; + int mini = -1; + for (int i = 0; i < n; i++) + { + int i1 = next(i, n); + if (indices[i1] & 0x80000000) + { + const int* p0 = &verts[(indices[i] & 0x0fffffff) * 4]; + const int* p2 = &verts[(indices[next(i1, n)] & 0x0fffffff) * 4]; + + int dx = p2[0] - p0[0]; + int dy = p2[2] - p0[2]; + int len = dx*dx + dy*dy; + + if (minLen < 0 || len < minLen) + { + minLen = len; + mini = i; + } + } + } + + if (mini == -1) + { + // We might get here because the contour has overlapping segments, like this: + // + // A o-o=====o---o B + // / |C D| \. + // o o o o + // : : : : + // We'll try to recover by loosing up the inCone test a bit so that a diagonal + // like A-B or C-D can be found and we can continue. + minLen = -1; + mini = -1; + for (int i = 0; i < n; i++) + { + int i1 = next(i, n); + int i2 = next(i1, n); + if (diagonalLoose(i, i2, n, verts, indices)) + { + const int* p0 = &verts[(indices[i] & 0x0fffffff) * 4]; + const int* p2 = &verts[(indices[next(i2, n)] & 0x0fffffff) * 4]; + int dx = p2[0] - p0[0]; + int dy = p2[2] - p0[2]; + int len = dx*dx + dy*dy; + + if (minLen < 0 || len < minLen) + { + minLen = len; + mini = i; + } + } + } + if (mini == -1) + { + // The contour is messed up. This sometimes happens + // if the contour simplification is too aggressive. + return -ntris; + } + } + + int i = mini; + int i1 = next(i, n); + int i2 = next(i1, n); + + *dst++ = indices[i] & 0x0fffffff; + *dst++ = indices[i1] & 0x0fffffff; + *dst++ = indices[i2] & 0x0fffffff; + ntris++; + + // Removes P[i1] by copying P[i+1]...P[n-1] left one index. + n--; + for (int k = i1; k < n; k++) + indices[k] = indices[k+1]; + + if (i1 >= n) i1 = 0; + i = prev(i1,n); + // Update diagonal flags. + if (diagonal(prev(i, n), i1, n, verts, indices)) + indices[i] |= 0x80000000; + else + indices[i] &= 0x0fffffff; + + if (diagonal(i, next(i1, n), n, verts, indices)) + indices[i1] |= 0x80000000; + else + indices[i1] &= 0x0fffffff; + } + + // Append the remaining triangle. + *dst++ = indices[0] & 0x0fffffff; + *dst++ = indices[1] & 0x0fffffff; + *dst++ = indices[2] & 0x0fffffff; + ntris++; + + return ntris; +} + +static int countPolyVerts(const unsigned short* p, const int nvp) +{ + for (int i = 0; i < nvp; ++i) + if (p[i] == RC_MESH_NULL_IDX) + return i; + return nvp; +} + +inline bool uleft(const unsigned short* a, const unsigned short* b, const unsigned short* c) +{ + return ((int)b[0] - (int)a[0]) * ((int)c[2] - (int)a[2]) - + ((int)c[0] - (int)a[0]) * ((int)b[2] - (int)a[2]) < 0; +} + +static int getPolyMergeValue(unsigned short* pa, unsigned short* pb, + const unsigned short* verts, int& ea, int& eb, + const int nvp) +{ + const int na = countPolyVerts(pa, nvp); + const int nb = countPolyVerts(pb, nvp); + + // If the merged polygon would be too big, do not merge. + if (na+nb-2 > nvp) + return -1; + + // Check if the polygons share an edge. + ea = -1; + eb = -1; + + for (int i = 0; i < na; ++i) + { + unsigned short va0 = pa[i]; + unsigned short va1 = pa[(i+1) % na]; + if (va0 > va1) + rcSwap(va0, va1); + for (int j = 0; j < nb; ++j) + { + unsigned short vb0 = pb[j]; + unsigned short vb1 = pb[(j+1) % nb]; + if (vb0 > vb1) + rcSwap(vb0, vb1); + if (va0 == vb0 && va1 == vb1) + { + ea = i; + eb = j; + break; + } + } + } + + // No common edge, cannot merge. + if (ea == -1 || eb == -1) + return -1; + + // Check to see if the merged polygon would be convex. + unsigned short va, vb, vc; + + va = pa[(ea+na-1) % na]; + vb = pa[ea]; + vc = pb[(eb+2) % nb]; + if (!uleft(&verts[va*3], &verts[vb*3], &verts[vc*3])) + return -1; + + va = pb[(eb+nb-1) % nb]; + vb = pb[eb]; + vc = pa[(ea+2) % na]; + if (!uleft(&verts[va*3], &verts[vb*3], &verts[vc*3])) + return -1; + + va = pa[ea]; + vb = pa[(ea+1)%na]; + + int dx = (int)verts[va*3+0] - (int)verts[vb*3+0]; + int dy = (int)verts[va*3+2] - (int)verts[vb*3+2]; + + return dx*dx + dy*dy; +} + +static void mergePolyVerts(unsigned short* pa, unsigned short* pb, int ea, int eb, + unsigned short* tmp, const int nvp) +{ + const int na = countPolyVerts(pa, nvp); + const int nb = countPolyVerts(pb, nvp); + + // Merge polygons. + memset(tmp, 0xff, sizeof(unsigned short)*nvp); + int n = 0; + // Add pa + for (int i = 0; i < na-1; ++i) + tmp[n++] = pa[(ea+1+i) % na]; + // Add pb + for (int i = 0; i < nb-1; ++i) + tmp[n++] = pb[(eb+1+i) % nb]; + + memcpy(pa, tmp, sizeof(unsigned short)*nvp); +} + + +static void pushFront(int v, int* arr, int& an) +{ + an++; + for (int i = an-1; i > 0; --i) arr[i] = arr[i-1]; + arr[0] = v; +} + +static void pushBack(int v, int* arr, int& an) +{ + arr[an] = v; + an++; +} + +static bool canRemoveVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short rem) +{ + const int nvp = mesh.nvp; + + // Count number of polygons to remove. + int numTouchedVerts = 0; + int numRemainingEdges = 0; + for (int i = 0; i < mesh.npolys; ++i) + { + unsigned short* p = &mesh.polys[i*nvp*2]; + const int nv = countPolyVerts(p, nvp); + int numRemoved = 0; + int numVerts = 0; + for (int j = 0; j < nv; ++j) + { + if (p[j] == rem) + { + numTouchedVerts++; + numRemoved++; + } + numVerts++; + } + if (numRemoved) + { + numRemainingEdges += numVerts-(numRemoved+1); + } + } + + // There would be too few edges remaining to create a polygon. + // This can happen for example when a tip of a triangle is marked + // as deletion, but there are no other polys that share the vertex. + // In this case, the vertex should not be removed. + if (numRemainingEdges <= 2) + return false; + + // Find edges which share the removed vertex. + const int maxEdges = numTouchedVerts*2; + int nedges = 0; + rcScopedDelete edges((int*)rcAlloc(sizeof(int)*maxEdges*3, RC_ALLOC_TEMP)); + if (!edges) + { + ctx->log(RC_LOG_WARNING, "canRemoveVertex: Out of memory 'edges' (%d).", maxEdges*3); + return false; + } + + for (int i = 0; i < mesh.npolys; ++i) + { + unsigned short* p = &mesh.polys[i*nvp*2]; + const int nv = countPolyVerts(p, nvp); + + // Collect edges which touches the removed vertex. + for (int j = 0, k = nv-1; j < nv; k = j++) + { + if (p[j] == rem || p[k] == rem) + { + // Arrange edge so that a=rem. + int a = p[j], b = p[k]; + if (b == rem) + rcSwap(a,b); + + // Check if the edge exists + bool exists = false; + for (int m = 0; m < nedges; ++m) + { + int* e = &edges[m*3]; + if (e[1] == b) + { + // Exists, increment vertex share count. + e[2]++; + exists = true; + } + } + // Add new edge. + if (!exists) + { + int* e = &edges[nedges*3]; + e[0] = a; + e[1] = b; + e[2] = 1; + nedges++; + } + } + } + } + + // There should be no more than 2 open edges. + // This catches the case that two non-adjacent polygons + // share the removed vertex. In that case, do not remove the vertex. + int numOpenEdges = 0; + for (int i = 0; i < nedges; ++i) + { + if (edges[i*3+2] < 2) + numOpenEdges++; + } + if (numOpenEdges > 2) + return false; + + return true; +} + +static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short rem, const int maxTris) +{ + const int nvp = mesh.nvp; + + // Count number of polygons to remove. + int numRemovedVerts = 0; + for (int i = 0; i < mesh.npolys; ++i) + { + unsigned short* p = &mesh.polys[i*nvp*2]; + const int nv = countPolyVerts(p, nvp); + for (int j = 0; j < nv; ++j) + { + if (p[j] == rem) + numRemovedVerts++; + } + } + + int nedges = 0; + rcScopedDelete edges((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp*4, RC_ALLOC_TEMP)); + if (!edges) + { + ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'edges' (%d).", numRemovedVerts*nvp*4); + return false; + } + + int nhole = 0; + rcScopedDelete hole((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP)); + if (!hole) + { + ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'hole' (%d).", numRemovedVerts*nvp); + return false; + } + + int nhreg = 0; + rcScopedDelete hreg((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP)); + if (!hreg) + { + ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'hreg' (%d).", numRemovedVerts*nvp); + return false; + } + + int nharea = 0; + rcScopedDelete harea((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP)); + if (!harea) + { + ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'harea' (%d).", numRemovedVerts*nvp); + return false; + } + + for (int i = 0; i < mesh.npolys; ++i) + { + unsigned short* p = &mesh.polys[i*nvp*2]; + const int nv = countPolyVerts(p, nvp); + bool hasRem = false; + for (int j = 0; j < nv; ++j) + if (p[j] == rem) hasRem = true; + if (hasRem) + { + // Collect edges which does not touch the removed vertex. + for (int j = 0, k = nv-1; j < nv; k = j++) + { + if (p[j] != rem && p[k] != rem) + { + int* e = &edges[nedges*4]; + e[0] = p[k]; + e[1] = p[j]; + e[2] = mesh.regs[i]; + e[3] = mesh.areas[i]; + nedges++; + } + } + // Remove the polygon. + unsigned short* p2 = &mesh.polys[(mesh.npolys-1)*nvp*2]; + if (p != p2) + memcpy(p,p2,sizeof(unsigned short)*nvp); + memset(p+nvp,0xff,sizeof(unsigned short)*nvp); + mesh.regs[i] = mesh.regs[mesh.npolys-1]; + mesh.areas[i] = mesh.areas[mesh.npolys-1]; + mesh.npolys--; + --i; + } + } + + // Remove vertex. + for (int i = (int)rem; i < mesh.nverts - 1; ++i) + { + mesh.verts[i*3+0] = mesh.verts[(i+1)*3+0]; + mesh.verts[i*3+1] = mesh.verts[(i+1)*3+1]; + mesh.verts[i*3+2] = mesh.verts[(i+1)*3+2]; + } + mesh.nverts--; + + // Adjust indices to match the removed vertex layout. + for (int i = 0; i < mesh.npolys; ++i) + { + unsigned short* p = &mesh.polys[i*nvp*2]; + const int nv = countPolyVerts(p, nvp); + for (int j = 0; j < nv; ++j) + if (p[j] > rem) p[j]--; + } + for (int i = 0; i < nedges; ++i) + { + if (edges[i*4+0] > rem) edges[i*4+0]--; + if (edges[i*4+1] > rem) edges[i*4+1]--; + } + + if (nedges == 0) + return true; + + // Start with one vertex, keep appending connected + // segments to the start and end of the hole. + pushBack(edges[0], hole, nhole); + pushBack(edges[2], hreg, nhreg); + pushBack(edges[3], harea, nharea); + + while (nedges) + { + bool match = false; + + for (int i = 0; i < nedges; ++i) + { + const int ea = edges[i*4+0]; + const int eb = edges[i*4+1]; + const int r = edges[i*4+2]; + const int a = edges[i*4+3]; + bool add = false; + if (hole[0] == eb) + { + // The segment matches the beginning of the hole boundary. + pushFront(ea, hole, nhole); + pushFront(r, hreg, nhreg); + pushFront(a, harea, nharea); + add = true; + } + else if (hole[nhole-1] == ea) + { + // The segment matches the end of the hole boundary. + pushBack(eb, hole, nhole); + pushBack(r, hreg, nhreg); + pushBack(a, harea, nharea); + add = true; + } + if (add) + { + // The edge segment was added, remove it. + edges[i*4+0] = edges[(nedges-1)*4+0]; + edges[i*4+1] = edges[(nedges-1)*4+1]; + edges[i*4+2] = edges[(nedges-1)*4+2]; + edges[i*4+3] = edges[(nedges-1)*4+3]; + --nedges; + match = true; + --i; + } + } + + if (!match) + break; + } + + rcScopedDelete tris((int*)rcAlloc(sizeof(int)*nhole*3, RC_ALLOC_TEMP)); + if (!tris) + { + ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'tris' (%d).", nhole*3); + return false; + } + + rcScopedDelete tverts((int*)rcAlloc(sizeof(int)*nhole*4, RC_ALLOC_TEMP)); + if (!tverts) + { + ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'tverts' (%d).", nhole*4); + return false; + } + + rcScopedDelete thole((int*)rcAlloc(sizeof(int)*nhole, RC_ALLOC_TEMP)); + if (!thole) + { + ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'thole' (%d).", nhole); + return false; + } + + // Generate temp vertex array for triangulation. + for (int i = 0; i < nhole; ++i) + { + const int pi = hole[i]; + tverts[i*4+0] = mesh.verts[pi*3+0]; + tverts[i*4+1] = mesh.verts[pi*3+1]; + tverts[i*4+2] = mesh.verts[pi*3+2]; + tverts[i*4+3] = 0; + thole[i] = i; + } + + // Triangulate the hole. + int ntris = triangulate(nhole, &tverts[0], &thole[0], tris); + if (ntris < 0) + { + ntris = -ntris; + ctx->log(RC_LOG_WARNING, "removeVertex: triangulate() returned bad results."); + } + + // Merge the hole triangles back to polygons. + rcScopedDelete polys((unsigned short*)rcAlloc(sizeof(unsigned short)*(ntris+1)*nvp, RC_ALLOC_TEMP)); + if (!polys) + { + ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'polys' (%d).", (ntris+1)*nvp); + return false; + } + rcScopedDelete pregs((unsigned short*)rcAlloc(sizeof(unsigned short)*ntris, RC_ALLOC_TEMP)); + if (!pregs) + { + ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'pregs' (%d).", ntris); + return false; + } + rcScopedDelete pareas((unsigned char*)rcAlloc(sizeof(unsigned char)*ntris, RC_ALLOC_TEMP)); + if (!pareas) + { + ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'pareas' (%d).", ntris); + return false; + } + + unsigned short* tmpPoly = &polys[ntris*nvp]; + + // Build initial polygons. + int npolys = 0; + memset(polys, 0xff, ntris*nvp*sizeof(unsigned short)); + for (int j = 0; j < ntris; ++j) + { + int* t = &tris[j*3]; + if (t[0] != t[1] && t[0] != t[2] && t[1] != t[2]) + { + polys[npolys*nvp+0] = (unsigned short)hole[t[0]]; + polys[npolys*nvp+1] = (unsigned short)hole[t[1]]; + polys[npolys*nvp+2] = (unsigned short)hole[t[2]]; + + // If this polygon covers multiple region types then + // mark it as such + if (hreg[t[0]] != hreg[t[1]] || hreg[t[1]] != hreg[t[2]]) + pregs[npolys] = RC_MULTIPLE_REGS; + else + pregs[npolys] = (unsigned short)hreg[t[0]]; + + pareas[npolys] = (unsigned char)harea[t[0]]; + npolys++; + } + } + if (!npolys) + return true; + + // Merge polygons. + if (nvp > 3) + { + for (;;) + { + // Find best polygons to merge. + int bestMergeVal = 0; + int bestPa = 0, bestPb = 0, bestEa = 0, bestEb = 0; + + for (int j = 0; j < npolys-1; ++j) + { + unsigned short* pj = &polys[j*nvp]; + for (int k = j+1; k < npolys; ++k) + { + unsigned short* pk = &polys[k*nvp]; + int ea, eb; + int v = getPolyMergeValue(pj, pk, mesh.verts, ea, eb, nvp); + if (v > bestMergeVal) + { + bestMergeVal = v; + bestPa = j; + bestPb = k; + bestEa = ea; + bestEb = eb; + } + } + } + + if (bestMergeVal > 0) + { + // Found best, merge. + unsigned short* pa = &polys[bestPa*nvp]; + unsigned short* pb = &polys[bestPb*nvp]; + mergePolyVerts(pa, pb, bestEa, bestEb, tmpPoly, nvp); + if (pregs[bestPa] != pregs[bestPb]) + pregs[bestPa] = RC_MULTIPLE_REGS; + + unsigned short* last = &polys[(npolys-1)*nvp]; + if (pb != last) + memcpy(pb, last, sizeof(unsigned short)*nvp); + pregs[bestPb] = pregs[npolys-1]; + pareas[bestPb] = pareas[npolys-1]; + npolys--; + } + else + { + // Could not merge any polygons, stop. + break; + } + } + } + + // Store polygons. + for (int i = 0; i < npolys; ++i) + { + if (mesh.npolys >= maxTris) break; + unsigned short* p = &mesh.polys[mesh.npolys*nvp*2]; + memset(p,0xff,sizeof(unsigned short)*nvp*2); + for (int j = 0; j < nvp; ++j) + p[j] = polys[i*nvp+j]; + mesh.regs[mesh.npolys] = pregs[i]; + mesh.areas[mesh.npolys] = pareas[i]; + mesh.npolys++; + if (mesh.npolys > maxTris) + { + ctx->log(RC_LOG_ERROR, "removeVertex: Too many polygons %d (max:%d).", mesh.npolys, maxTris); + return false; + } + } + + return true; +} + +/// @par +/// +/// @note If the mesh data is to be used to construct a Detour navigation mesh, then the upper +/// limit must be restricted to <= #DT_VERTS_PER_POLYGON. +/// +/// @see rcAllocPolyMesh, rcContourSet, rcPolyMesh, rcConfig +bool rcBuildPolyMesh(rcContext* ctx, const rcContourSet& cset, const int nvp, rcPolyMesh& mesh) +{ + rcAssert(ctx); + + rcScopedTimer timer(ctx, RC_TIMER_BUILD_POLYMESH); + + rcVcopy(mesh.bmin, cset.bmin); + rcVcopy(mesh.bmax, cset.bmax); + mesh.cs = cset.cs; + mesh.ch = cset.ch; + mesh.borderSize = cset.borderSize; + mesh.maxEdgeError = cset.maxError; + + int maxVertices = 0; + int maxTris = 0; + int maxVertsPerCont = 0; + for (int i = 0; i < cset.nconts; ++i) + { + // Skip null contours. + if (cset.conts[i].nverts < 3) continue; + maxVertices += cset.conts[i].nverts; + maxTris += cset.conts[i].nverts - 2; + maxVertsPerCont = rcMax(maxVertsPerCont, cset.conts[i].nverts); + } + + if (maxVertices >= 0xfffe) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Too many vertices %d.", maxVertices); + return false; + } + + rcScopedDelete vflags((unsigned char*)rcAlloc(sizeof(unsigned char)*maxVertices, RC_ALLOC_TEMP)); + if (!vflags) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'vflags' (%d).", maxVertices); + return false; + } + memset(vflags, 0, maxVertices); + + mesh.verts = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxVertices*3, RC_ALLOC_PERM); + if (!mesh.verts) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.verts' (%d).", maxVertices); + return false; + } + mesh.polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxTris*nvp*2, RC_ALLOC_PERM); + if (!mesh.polys) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.polys' (%d).", maxTris*nvp*2); + return false; + } + mesh.regs = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxTris, RC_ALLOC_PERM); + if (!mesh.regs) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.regs' (%d).", maxTris); + return false; + } + mesh.areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*maxTris, RC_ALLOC_PERM); + if (!mesh.areas) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.areas' (%d).", maxTris); + return false; + } + + mesh.nverts = 0; + mesh.npolys = 0; + mesh.nvp = nvp; + mesh.maxpolys = maxTris; + + memset(mesh.verts, 0, sizeof(unsigned short)*maxVertices*3); + memset(mesh.polys, 0xff, sizeof(unsigned short)*maxTris*nvp*2); + memset(mesh.regs, 0, sizeof(unsigned short)*maxTris); + memset(mesh.areas, 0, sizeof(unsigned char)*maxTris); + + rcScopedDelete nextVert((int*)rcAlloc(sizeof(int)*maxVertices, RC_ALLOC_TEMP)); + if (!nextVert) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'nextVert' (%d).", maxVertices); + return false; + } + memset(nextVert, 0, sizeof(int)*maxVertices); + + rcScopedDelete firstVert((int*)rcAlloc(sizeof(int)*VERTEX_BUCKET_COUNT, RC_ALLOC_TEMP)); + if (!firstVert) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'firstVert' (%d).", VERTEX_BUCKET_COUNT); + return false; + } + for (int i = 0; i < VERTEX_BUCKET_COUNT; ++i) + firstVert[i] = -1; + + rcScopedDelete indices((int*)rcAlloc(sizeof(int)*maxVertsPerCont, RC_ALLOC_TEMP)); + if (!indices) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'indices' (%d).", maxVertsPerCont); + return false; + } + rcScopedDelete tris((int*)rcAlloc(sizeof(int)*maxVertsPerCont*3, RC_ALLOC_TEMP)); + if (!tris) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'tris' (%d).", maxVertsPerCont*3); + return false; + } + rcScopedDelete polys((unsigned short*)rcAlloc(sizeof(unsigned short)*(maxVertsPerCont+1)*nvp, RC_ALLOC_TEMP)); + if (!polys) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'polys' (%d).", maxVertsPerCont*nvp); + return false; + } + unsigned short* tmpPoly = &polys[maxVertsPerCont*nvp]; + + for (int i = 0; i < cset.nconts; ++i) + { + rcContour& cont = cset.conts[i]; + + // Skip null contours. + if (cont.nverts < 3) + continue; + + // Triangulate contour + for (int j = 0; j < cont.nverts; ++j) + indices[j] = j; + + int ntris = triangulate(cont.nverts, cont.verts, &indices[0], &tris[0]); + if (ntris <= 0) + { + // Bad triangulation, should not happen. +/* printf("\tconst float bmin[3] = {%ff,%ff,%ff};\n", cset.bmin[0], cset.bmin[1], cset.bmin[2]); + printf("\tconst float cs = %ff;\n", cset.cs); + printf("\tconst float ch = %ff;\n", cset.ch); + printf("\tconst int verts[] = {\n"); + for (int k = 0; k < cont.nverts; ++k) + { + const int* v = &cont.verts[k*4]; + printf("\t\t%d,%d,%d,%d,\n", v[0], v[1], v[2], v[3]); + } + printf("\t};\n\tconst int nverts = sizeof(verts)/(sizeof(int)*4);\n");*/ + ctx->log(RC_LOG_WARNING, "rcBuildPolyMesh: Bad triangulation Contour %d.", i); + ntris = -ntris; + } + + // Add and merge vertices. + for (int j = 0; j < cont.nverts; ++j) + { + const int* v = &cont.verts[j*4]; + indices[j] = addVertex((unsigned short)v[0], (unsigned short)v[1], (unsigned short)v[2], + mesh.verts, firstVert, nextVert, mesh.nverts); + if (v[3] & RC_BORDER_VERTEX) + { + // This vertex should be removed. + vflags[indices[j]] = 1; + } + } + + // Build initial polygons. + int npolys = 0; + memset(polys, 0xff, maxVertsPerCont*nvp*sizeof(unsigned short)); + for (int j = 0; j < ntris; ++j) + { + int* t = &tris[j*3]; + if (t[0] != t[1] && t[0] != t[2] && t[1] != t[2]) + { + polys[npolys*nvp+0] = (unsigned short)indices[t[0]]; + polys[npolys*nvp+1] = (unsigned short)indices[t[1]]; + polys[npolys*nvp+2] = (unsigned short)indices[t[2]]; + npolys++; + } + } + if (!npolys) + continue; + + // Merge polygons. + if (nvp > 3) + { + for(;;) + { + // Find best polygons to merge. + int bestMergeVal = 0; + int bestPa = 0, bestPb = 0, bestEa = 0, bestEb = 0; + + for (int j = 0; j < npolys-1; ++j) + { + unsigned short* pj = &polys[j*nvp]; + for (int k = j+1; k < npolys; ++k) + { + unsigned short* pk = &polys[k*nvp]; + int ea, eb; + int v = getPolyMergeValue(pj, pk, mesh.verts, ea, eb, nvp); + if (v > bestMergeVal) + { + bestMergeVal = v; + bestPa = j; + bestPb = k; + bestEa = ea; + bestEb = eb; + } + } + } + + if (bestMergeVal > 0) + { + // Found best, merge. + unsigned short* pa = &polys[bestPa*nvp]; + unsigned short* pb = &polys[bestPb*nvp]; + mergePolyVerts(pa, pb, bestEa, bestEb, tmpPoly, nvp); + unsigned short* lastPoly = &polys[(npolys-1)*nvp]; + if (pb != lastPoly) + memcpy(pb, lastPoly, sizeof(unsigned short)*nvp); + npolys--; + } + else + { + // Could not merge any polygons, stop. + break; + } + } + } + + // Store polygons. + for (int j = 0; j < npolys; ++j) + { + unsigned short* p = &mesh.polys[mesh.npolys*nvp*2]; + unsigned short* q = &polys[j*nvp]; + for (int k = 0; k < nvp; ++k) + p[k] = q[k]; + mesh.regs[mesh.npolys] = cont.reg; + mesh.areas[mesh.npolys] = cont.area; + mesh.npolys++; + if (mesh.npolys > maxTris) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Too many polygons %d (max:%d).", mesh.npolys, maxTris); + return false; + } + } + } + + + // Remove edge vertices. + for (int i = 0; i < mesh.nverts; ++i) + { + if (vflags[i]) + { + if (!canRemoveVertex(ctx, mesh, (unsigned short)i)) + continue; + if (!removeVertex(ctx, mesh, (unsigned short)i, maxTris)) + { + // Failed to remove vertex + ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Failed to remove edge vertex %d.", i); + return false; + } + // Remove vertex + // Note: mesh.nverts is already decremented inside removeVertex()! + // Fixup vertex flags + for (int j = i; j < mesh.nverts; ++j) + vflags[j] = vflags[j+1]; + --i; + } + } + + // Calculate adjacency. + if (!buildMeshAdjacency(mesh.polys, mesh.npolys, mesh.nverts, nvp)) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Adjacency failed."); + return false; + } + + // Find portal edges + if (mesh.borderSize > 0) + { + const int w = cset.width; + const int h = cset.height; + for (int i = 0; i < mesh.npolys; ++i) + { + unsigned short* p = &mesh.polys[i*2*nvp]; + for (int j = 0; j < nvp; ++j) + { + if (p[j] == RC_MESH_NULL_IDX) break; + // Skip connected edges. + if (p[nvp+j] != RC_MESH_NULL_IDX) + continue; + int nj = j+1; + if (nj >= nvp || p[nj] == RC_MESH_NULL_IDX) nj = 0; + const unsigned short* va = &mesh.verts[p[j]*3]; + const unsigned short* vb = &mesh.verts[p[nj]*3]; + + if ((int)va[0] == 0 && (int)vb[0] == 0) + p[nvp+j] = 0x8000 | 0; + else if ((int)va[2] == h && (int)vb[2] == h) + p[nvp+j] = 0x8000 | 1; + else if ((int)va[0] == w && (int)vb[0] == w) + p[nvp+j] = 0x8000 | 2; + else if ((int)va[2] == 0 && (int)vb[2] == 0) + p[nvp+j] = 0x8000 | 3; + } + } + } + + // Just allocate the mesh flags array. The user is resposible to fill it. + mesh.flags = (unsigned short*)rcAlloc(sizeof(unsigned short)*mesh.npolys, RC_ALLOC_PERM); + if (!mesh.flags) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.flags' (%d).", mesh.npolys); + return false; + } + memset(mesh.flags, 0, sizeof(unsigned short) * mesh.npolys); + + if (mesh.nverts > 0xffff) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: The resulting mesh has too many vertices %d (max %d). Data can be corrupted.", mesh.nverts, 0xffff); + } + if (mesh.npolys > 0xffff) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: The resulting mesh has too many polygons %d (max %d). Data can be corrupted.", mesh.npolys, 0xffff); + } + + return true; +} + +/// @see rcAllocPolyMesh, rcPolyMesh +bool rcMergePolyMeshes(rcContext* ctx, rcPolyMesh** meshes, const int nmeshes, rcPolyMesh& mesh) +{ + rcAssert(ctx); + + if (!nmeshes || !meshes) + return true; + + rcScopedTimer timer(ctx, RC_TIMER_MERGE_POLYMESH); + + mesh.nvp = meshes[0]->nvp; + mesh.cs = meshes[0]->cs; + mesh.ch = meshes[0]->ch; + rcVcopy(mesh.bmin, meshes[0]->bmin); + rcVcopy(mesh.bmax, meshes[0]->bmax); + + int maxVerts = 0; + int maxPolys = 0; + int maxVertsPerMesh = 0; + for (int i = 0; i < nmeshes; ++i) + { + rcVmin(mesh.bmin, meshes[i]->bmin); + rcVmax(mesh.bmax, meshes[i]->bmax); + maxVertsPerMesh = rcMax(maxVertsPerMesh, meshes[i]->nverts); + maxVerts += meshes[i]->nverts; + maxPolys += meshes[i]->npolys; + } + + mesh.nverts = 0; + mesh.verts = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxVerts*3, RC_ALLOC_PERM); + if (!mesh.verts) + { + ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.verts' (%d).", maxVerts*3); + return false; + } + + mesh.npolys = 0; + mesh.polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxPolys*2*mesh.nvp, RC_ALLOC_PERM); + if (!mesh.polys) + { + ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.polys' (%d).", maxPolys*2*mesh.nvp); + return false; + } + memset(mesh.polys, 0xff, sizeof(unsigned short)*maxPolys*2*mesh.nvp); + + mesh.regs = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxPolys, RC_ALLOC_PERM); + if (!mesh.regs) + { + ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.regs' (%d).", maxPolys); + return false; + } + memset(mesh.regs, 0, sizeof(unsigned short)*maxPolys); + + mesh.areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*maxPolys, RC_ALLOC_PERM); + if (!mesh.areas) + { + ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.areas' (%d).", maxPolys); + return false; + } + memset(mesh.areas, 0, sizeof(unsigned char)*maxPolys); + + mesh.flags = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxPolys, RC_ALLOC_PERM); + if (!mesh.flags) + { + ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.flags' (%d).", maxPolys); + return false; + } + memset(mesh.flags, 0, sizeof(unsigned short)*maxPolys); + + rcScopedDelete nextVert((int*)rcAlloc(sizeof(int)*maxVerts, RC_ALLOC_TEMP)); + if (!nextVert) + { + ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'nextVert' (%d).", maxVerts); + return false; + } + memset(nextVert, 0, sizeof(int)*maxVerts); + + rcScopedDelete firstVert((int*)rcAlloc(sizeof(int)*VERTEX_BUCKET_COUNT, RC_ALLOC_TEMP)); + if (!firstVert) + { + ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'firstVert' (%d).", VERTEX_BUCKET_COUNT); + return false; + } + for (int i = 0; i < VERTEX_BUCKET_COUNT; ++i) + firstVert[i] = -1; + + rcScopedDelete vremap((unsigned short*)rcAlloc(sizeof(unsigned short)*maxVertsPerMesh, RC_ALLOC_PERM)); + if (!vremap) + { + ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'vremap' (%d).", maxVertsPerMesh); + return false; + } + memset(vremap, 0, sizeof(unsigned short)*maxVertsPerMesh); + + for (int i = 0; i < nmeshes; ++i) + { + const rcPolyMesh* pmesh = meshes[i]; + + const unsigned short ox = (unsigned short)floorf((pmesh->bmin[0]-mesh.bmin[0])/mesh.cs+0.5f); + const unsigned short oz = (unsigned short)floorf((pmesh->bmin[2]-mesh.bmin[2])/mesh.cs+0.5f); + + bool isMinX = (ox == 0); + bool isMinZ = (oz == 0); + bool isMaxX = ((unsigned short)floorf((mesh.bmax[0] - pmesh->bmax[0]) / mesh.cs + 0.5f)) == 0; + bool isMaxZ = ((unsigned short)floorf((mesh.bmax[2] - pmesh->bmax[2]) / mesh.cs + 0.5f)) == 0; + bool isOnBorder = (isMinX || isMinZ || isMaxX || isMaxZ); + + for (int j = 0; j < pmesh->nverts; ++j) + { + unsigned short* v = &pmesh->verts[j*3]; + vremap[j] = addVertex(v[0]+ox, v[1], v[2]+oz, + mesh.verts, firstVert, nextVert, mesh.nverts); + } + + for (int j = 0; j < pmesh->npolys; ++j) + { + unsigned short* tgt = &mesh.polys[mesh.npolys*2*mesh.nvp]; + unsigned short* src = &pmesh->polys[j*2*mesh.nvp]; + mesh.regs[mesh.npolys] = pmesh->regs[j]; + mesh.areas[mesh.npolys] = pmesh->areas[j]; + mesh.flags[mesh.npolys] = pmesh->flags[j]; + mesh.npolys++; + for (int k = 0; k < mesh.nvp; ++k) + { + if (src[k] == RC_MESH_NULL_IDX) break; + tgt[k] = vremap[src[k]]; + } + + if (isOnBorder) + { + for (int k = mesh.nvp; k < mesh.nvp * 2; ++k) + { + if (src[k] & 0x8000 && src[k] != 0xffff) + { + unsigned short dir = src[k] & 0xf; + switch (dir) + { + case 0: // Portal x- + if (isMinX) + tgt[k] = src[k]; + break; + case 1: // Portal z+ + if (isMaxZ) + tgt[k] = src[k]; + break; + case 2: // Portal x+ + if (isMaxX) + tgt[k] = src[k]; + break; + case 3: // Portal z- + if (isMinZ) + tgt[k] = src[k]; + break; + } + } + } + } + } + } + + // Calculate adjacency. + if (!buildMeshAdjacency(mesh.polys, mesh.npolys, mesh.nverts, mesh.nvp)) + { + ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Adjacency failed."); + return false; + } + + if (mesh.nverts > 0xffff) + { + ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: The resulting mesh has too many vertices %d (max %d). Data can be corrupted.", mesh.nverts, 0xffff); + } + if (mesh.npolys > 0xffff) + { + ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: The resulting mesh has too many polygons %d (max %d). Data can be corrupted.", mesh.npolys, 0xffff); + } + + return true; +} + +bool rcCopyPolyMesh(rcContext* ctx, const rcPolyMesh& src, rcPolyMesh& dst) +{ + rcAssert(ctx); + + // Destination must be empty. + rcAssert(dst.verts == 0); + rcAssert(dst.polys == 0); + rcAssert(dst.regs == 0); + rcAssert(dst.areas == 0); + rcAssert(dst.flags == 0); + + dst.nverts = src.nverts; + dst.npolys = src.npolys; + dst.maxpolys = src.npolys; + dst.nvp = src.nvp; + rcVcopy(dst.bmin, src.bmin); + rcVcopy(dst.bmax, src.bmax); + dst.cs = src.cs; + dst.ch = src.ch; + dst.borderSize = src.borderSize; + dst.maxEdgeError = src.maxEdgeError; + + dst.verts = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.nverts*3, RC_ALLOC_PERM); + if (!dst.verts) + { + ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.verts' (%d).", src.nverts*3); + return false; + } + memcpy(dst.verts, src.verts, sizeof(unsigned short)*src.nverts*3); + + dst.polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys*2*src.nvp, RC_ALLOC_PERM); + if (!dst.polys) + { + ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.polys' (%d).", src.npolys*2*src.nvp); + return false; + } + memcpy(dst.polys, src.polys, sizeof(unsigned short)*src.npolys*2*src.nvp); + + dst.regs = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys, RC_ALLOC_PERM); + if (!dst.regs) + { + ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.regs' (%d).", src.npolys); + return false; + } + memcpy(dst.regs, src.regs, sizeof(unsigned short)*src.npolys); + + dst.areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*src.npolys, RC_ALLOC_PERM); + if (!dst.areas) + { + ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.areas' (%d).", src.npolys); + return false; + } + memcpy(dst.areas, src.areas, sizeof(unsigned char)*src.npolys); + + dst.flags = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys, RC_ALLOC_PERM); + if (!dst.flags) + { + ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.flags' (%d).", src.npolys); + return false; + } + memcpy(dst.flags, src.flags, sizeof(unsigned short)*src.npolys); + + return true; +} diff --git a/native/third_party/recastnavigation/Recast/Source/RecastMeshDetail.cpp b/native/third_party/recastnavigation/Recast/Source/RecastMeshDetail.cpp new file mode 100644 index 0000000..07bbdbd --- /dev/null +++ b/native/third_party/recastnavigation/Recast/Source/RecastMeshDetail.cpp @@ -0,0 +1,1476 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#include +#include +#include +#include +#include +#include "Recast.h" +#include "RecastAlloc.h" +#include "RecastAssert.h" + + +static const unsigned RC_UNSET_HEIGHT = 0xffff; + +struct rcHeightPatch +{ + inline rcHeightPatch() : data(0), xmin(0), ymin(0), width(0), height(0) {} + inline ~rcHeightPatch() { rcFree(data); } + unsigned short* data; + int xmin, ymin, width, height; +}; + + +inline float vdot2(const float* a, const float* b) +{ + return a[0]*b[0] + a[2]*b[2]; +} + +inline float vdistSq2(const float* p, const float* q) +{ + const float dx = q[0] - p[0]; + const float dy = q[2] - p[2]; + return dx*dx + dy*dy; +} + +inline float vdist2(const float* p, const float* q) +{ + return sqrtf(vdistSq2(p,q)); +} + +inline float vcross2(const float* p1, const float* p2, const float* p3) +{ + const float u1 = p2[0] - p1[0]; + const float v1 = p2[2] - p1[2]; + const float u2 = p3[0] - p1[0]; + const float v2 = p3[2] - p1[2]; + return u1 * v2 - v1 * u2; +} + +static bool circumCircle(const float* p1, const float* p2, const float* p3, + float* c, float& r) +{ + static const float EPS = 1e-6f; + // Calculate the circle relative to p1, to avoid some precision issues. + const float v1[3] = {0,0,0}; + float v2[3], v3[3]; + rcVsub(v2, p2,p1); + rcVsub(v3, p3,p1); + + const float cp = vcross2(v1, v2, v3); + if (fabsf(cp) > EPS) + { + const float v1Sq = vdot2(v1,v1); + const float v2Sq = vdot2(v2,v2); + const float v3Sq = vdot2(v3,v3); + c[0] = (v1Sq*(v2[2]-v3[2]) + v2Sq*(v3[2]-v1[2]) + v3Sq*(v1[2]-v2[2])) / (2*cp); + c[1] = 0; + c[2] = (v1Sq*(v3[0]-v2[0]) + v2Sq*(v1[0]-v3[0]) + v3Sq*(v2[0]-v1[0])) / (2*cp); + r = vdist2(c, v1); + rcVadd(c, c, p1); + return true; + } + + rcVcopy(c, p1); + r = 0; + return false; +} + +static float distPtTri(const float* p, const float* a, const float* b, const float* c) +{ + float v0[3], v1[3], v2[3]; + rcVsub(v0, c,a); + rcVsub(v1, b,a); + rcVsub(v2, p,a); + + const float dot00 = vdot2(v0, v0); + const float dot01 = vdot2(v0, v1); + const float dot02 = vdot2(v0, v2); + const float dot11 = vdot2(v1, v1); + const float dot12 = vdot2(v1, v2); + + // Compute barycentric coordinates + const float invDenom = 1.0f / (dot00 * dot11 - dot01 * dot01); + const float u = (dot11 * dot02 - dot01 * dot12) * invDenom; + float v = (dot00 * dot12 - dot01 * dot02) * invDenom; + + // If point lies inside the triangle, return interpolated y-coord. + static const float EPS = 1e-4f; + if (u >= -EPS && v >= -EPS && (u+v) <= 1+EPS) + { + const float y = a[1] + v0[1]*u + v1[1]*v; + return fabsf(y-p[1]); + } + return FLT_MAX; +} + +static float distancePtSeg(const float* pt, const float* p, const float* q) +{ + float pqx = q[0] - p[0]; + float pqy = q[1] - p[1]; + float pqz = q[2] - p[2]; + float dx = pt[0] - p[0]; + float dy = pt[1] - p[1]; + float dz = pt[2] - p[2]; + float d = pqx*pqx + pqy*pqy + pqz*pqz; + float t = pqx*dx + pqy*dy + pqz*dz; + if (d > 0) + t /= d; + if (t < 0) + t = 0; + else if (t > 1) + t = 1; + + dx = p[0] + t*pqx - pt[0]; + dy = p[1] + t*pqy - pt[1]; + dz = p[2] + t*pqz - pt[2]; + + return dx*dx + dy*dy + dz*dz; +} + +static float distancePtSeg2d(const float* pt, const float* p, const float* q) +{ + float pqx = q[0] - p[0]; + float pqz = q[2] - p[2]; + float dx = pt[0] - p[0]; + float dz = pt[2] - p[2]; + float d = pqx*pqx + pqz*pqz; + float t = pqx*dx + pqz*dz; + if (d > 0) + t /= d; + if (t < 0) + t = 0; + else if (t > 1) + t = 1; + + dx = p[0] + t*pqx - pt[0]; + dz = p[2] + t*pqz - pt[2]; + + return dx*dx + dz*dz; +} + +static float distToTriMesh(const float* p, const float* verts, const int /*nverts*/, const int* tris, const int ntris) +{ + float dmin = FLT_MAX; + for (int i = 0; i < ntris; ++i) + { + const float* va = &verts[tris[i*4+0]*3]; + const float* vb = &verts[tris[i*4+1]*3]; + const float* vc = &verts[tris[i*4+2]*3]; + float d = distPtTri(p, va,vb,vc); + if (d < dmin) + dmin = d; + } + if (dmin == FLT_MAX) return -1; + return dmin; +} + +static float distToPoly(int nvert, const float* verts, const float* p) +{ + + float dmin = FLT_MAX; + int i, j, c = 0; + for (i = 0, j = nvert-1; i < nvert; j = i++) + { + const float* vi = &verts[i*3]; + const float* vj = &verts[j*3]; + if (((vi[2] > p[2]) != (vj[2] > p[2])) && + (p[0] < (vj[0]-vi[0]) * (p[2]-vi[2]) / (vj[2]-vi[2]) + vi[0]) ) + c = !c; + dmin = rcMin(dmin, distancePtSeg2d(p, vj, vi)); + } + return c ? -dmin : dmin; +} + + +static unsigned short getHeight(const float fx, const float fy, const float fz, + const float /*cs*/, const float ics, const float ch, + const int radius, const rcHeightPatch& hp) +{ + int ix = (int)floorf(fx*ics + 0.01f); + int iz = (int)floorf(fz*ics + 0.01f); + ix = rcClamp(ix-hp.xmin, 0, hp.width - 1); + iz = rcClamp(iz-hp.ymin, 0, hp.height - 1); + unsigned short h = hp.data[ix+iz*hp.width]; + if (h == RC_UNSET_HEIGHT) + { + // Special case when data might be bad. + // Walk adjacent cells in a spiral up to 'radius', and look + // for a pixel which has a valid height. + int x = 1, z = 0, dx = 1, dz = 0; + int maxSize = radius * 2 + 1; + int maxIter = maxSize * maxSize - 1; + + int nextRingIterStart = 8; + int nextRingIters = 16; + + float dmin = FLT_MAX; + for (int i = 0; i < maxIter; i++) + { + const int nx = ix + x; + const int nz = iz + z; + + if (nx >= 0 && nz >= 0 && nx < hp.width && nz < hp.height) + { + const unsigned short nh = hp.data[nx + nz*hp.width]; + if (nh != RC_UNSET_HEIGHT) + { + const float d = fabsf(nh*ch - fy); + if (d < dmin) + { + h = nh; + dmin = d; + } + } + } + + // We are searching in a grid which looks approximately like this: + // __________ + // |2 ______ 2| + // | |1 __ 1| | + // | | |__| | | + // | |______| | + // |__________| + // We want to find the best height as close to the center cell as possible. This means that + // if we find a height in one of the neighbor cells to the center, we don't want to + // expand further out than the 8 neighbors - we want to limit our search to the closest + // of these "rings", but the best height in the ring. + // For example, the center is just 1 cell. We checked that at the entrance to the function. + // The next "ring" contains 8 cells (marked 1 above). Those are all the neighbors to the center cell. + // The next one again contains 16 cells (marked 2). In general each ring has 8 additional cells, which + // can be thought of as adding 2 cells around the "center" of each side when we expand the ring. + // Here we detect if we are about to enter the next ring, and if we are and we have found + // a height, we abort the search. + if (i + 1 == nextRingIterStart) + { + if (h != RC_UNSET_HEIGHT) + break; + + nextRingIterStart += nextRingIters; + nextRingIters += 8; + } + + if ((x == z) || ((x < 0) && (x == -z)) || ((x > 0) && (x == 1 - z))) + { + int tmp = dx; + dx = -dz; + dz = tmp; + } + x += dx; + z += dz; + } + } + return h; +} + + +enum EdgeValues +{ + EV_UNDEF = -1, + EV_HULL = -2 +}; + +static int findEdge(const int* edges, int nedges, int s, int t) +{ + for (int i = 0; i < nedges; i++) + { + const int* e = &edges[i*4]; + if ((e[0] == s && e[1] == t) || (e[0] == t && e[1] == s)) + return i; + } + return EV_UNDEF; +} + +static int addEdge(rcContext* ctx, int* edges, int& nedges, const int maxEdges, int s, int t, int l, int r) +{ + if (nedges >= maxEdges) + { + ctx->log(RC_LOG_ERROR, "addEdge: Too many edges (%d/%d).", nedges, maxEdges); + return EV_UNDEF; + } + + // Add edge if not already in the triangulation. + int e = findEdge(edges, nedges, s, t); + if (e == EV_UNDEF) + { + int* edge = &edges[nedges*4]; + edge[0] = s; + edge[1] = t; + edge[2] = l; + edge[3] = r; + return nedges++; + } + else + { + return EV_UNDEF; + } +} + +static void updateLeftFace(int* e, int s, int t, int f) +{ + if (e[0] == s && e[1] == t && e[2] == EV_UNDEF) + e[2] = f; + else if (e[1] == s && e[0] == t && e[3] == EV_UNDEF) + e[3] = f; +} + +static int overlapSegSeg2d(const float* a, const float* b, const float* c, const float* d) +{ + const float a1 = vcross2(a, b, d); + const float a2 = vcross2(a, b, c); + if (a1*a2 < 0.0f) + { + float a3 = vcross2(c, d, a); + float a4 = a3 + a2 - a1; + if (a3 * a4 < 0.0f) + return 1; + } + return 0; +} + +static bool overlapEdges(const float* pts, const int* edges, int nedges, int s1, int t1) +{ + for (int i = 0; i < nedges; ++i) + { + const int s0 = edges[i*4+0]; + const int t0 = edges[i*4+1]; + // Same or connected edges do not overlap. + if (s0 == s1 || s0 == t1 || t0 == s1 || t0 == t1) + continue; + if (overlapSegSeg2d(&pts[s0*3],&pts[t0*3], &pts[s1*3],&pts[t1*3])) + return true; + } + return false; +} + +static void completeFacet(rcContext* ctx, const float* pts, int npts, int* edges, int& nedges, const int maxEdges, int& nfaces, int e) +{ + static const float EPS = 1e-5f; + + int* edge = &edges[e*4]; + + // Cache s and t. + int s,t; + if (edge[2] == EV_UNDEF) + { + s = edge[0]; + t = edge[1]; + } + else if (edge[3] == EV_UNDEF) + { + s = edge[1]; + t = edge[0]; + } + else + { + // Edge already completed. + return; + } + + // Find best point on left of edge. + int pt = npts; + float c[3] = {0,0,0}; + float r = -1; + for (int u = 0; u < npts; ++u) + { + if (u == s || u == t) continue; + if (vcross2(&pts[s*3], &pts[t*3], &pts[u*3]) > EPS) + { + if (r < 0) + { + // The circle is not updated yet, do it now. + pt = u; + circumCircle(&pts[s*3], &pts[t*3], &pts[u*3], c, r); + continue; + } + const float d = vdist2(c, &pts[u*3]); + const float tol = 0.001f; + if (d > r*(1+tol)) + { + // Outside current circumcircle, skip. + continue; + } + else if (d < r*(1-tol)) + { + // Inside safe circumcircle, update circle. + pt = u; + circumCircle(&pts[s*3], &pts[t*3], &pts[u*3], c, r); + } + else + { + // Inside epsilon circum circle, do extra tests to make sure the edge is valid. + // s-u and t-u cannot overlap with s-pt nor t-pt if they exists. + if (overlapEdges(pts, edges, nedges, s,u)) + continue; + if (overlapEdges(pts, edges, nedges, t,u)) + continue; + // Edge is valid. + pt = u; + circumCircle(&pts[s*3], &pts[t*3], &pts[u*3], c, r); + } + } + } + + // Add new triangle or update edge info if s-t is on hull. + if (pt < npts) + { + // Update face information of edge being completed. + updateLeftFace(&edges[e*4], s, t, nfaces); + + // Add new edge or update face info of old edge. + e = findEdge(edges, nedges, pt, s); + if (e == EV_UNDEF) + addEdge(ctx, edges, nedges, maxEdges, pt, s, nfaces, EV_UNDEF); + else + updateLeftFace(&edges[e*4], pt, s, nfaces); + + // Add new edge or update face info of old edge. + e = findEdge(edges, nedges, t, pt); + if (e == EV_UNDEF) + addEdge(ctx, edges, nedges, maxEdges, t, pt, nfaces, EV_UNDEF); + else + updateLeftFace(&edges[e*4], t, pt, nfaces); + + nfaces++; + } + else + { + updateLeftFace(&edges[e*4], s, t, EV_HULL); + } +} + +static void delaunayHull(rcContext* ctx, const int npts, const float* pts, + const int nhull, const int* hull, + rcTempVector& tris, rcTempVector& edges) +{ + int nfaces = 0; + int nedges = 0; + const int maxEdges = npts*10; + edges.resize(maxEdges*4); + + for (int i = 0, j = nhull-1; i < nhull; j=i++) + addEdge(ctx, &edges[0], nedges, maxEdges, hull[j],hull[i], EV_HULL, EV_UNDEF); + + int currentEdge = 0; + while (currentEdge < nedges) + { + if (edges[currentEdge*4+2] == EV_UNDEF) + completeFacet(ctx, pts, npts, &edges[0], nedges, maxEdges, nfaces, currentEdge); + if (edges[currentEdge*4+3] == EV_UNDEF) + completeFacet(ctx, pts, npts, &edges[0], nedges, maxEdges, nfaces, currentEdge); + currentEdge++; + } + + // Create tris + tris.resize(nfaces*4); + for (int i = 0; i < nfaces*4; ++i) + tris[i] = -1; + + for (int i = 0; i < nedges; ++i) + { + const int* e = &edges[i*4]; + if (e[3] >= 0) + { + // Left face + int* t = &tris[e[3]*4]; + if (t[0] == -1) + { + t[0] = e[0]; + t[1] = e[1]; + } + else if (t[0] == e[1]) + t[2] = e[0]; + else if (t[1] == e[0]) + t[2] = e[1]; + } + if (e[2] >= 0) + { + // Right + int* t = &tris[e[2]*4]; + if (t[0] == -1) + { + t[0] = e[1]; + t[1] = e[0]; + } + else if (t[0] == e[0]) + t[2] = e[1]; + else if (t[1] == e[1]) + t[2] = e[0]; + } + } + + for (int i = 0; i < tris.size()/4; ++i) + { + int* t = &tris[i*4]; + if (t[0] == -1 || t[1] == -1 || t[2] == -1) + { + ctx->log(RC_LOG_WARNING, "delaunayHull: Removing dangling face %d [%d,%d,%d].", i, t[0],t[1],t[2]); + t[0] = tris[tris.size()-4]; + t[1] = tris[tris.size()-3]; + t[2] = tris[tris.size()-2]; + t[3] = tris[tris.size()-1]; + tris.resize(tris.size()-4); + --i; + } + } +} + +// Calculate minimum extend of the polygon. +static float polyMinExtent(const float* verts, const int nverts) +{ + float minDist = FLT_MAX; + for (int i = 0; i < nverts; i++) + { + const int ni = (i+1) % nverts; + const float* p1 = &verts[i*3]; + const float* p2 = &verts[ni*3]; + float maxEdgeDist = 0; + for (int j = 0; j < nverts; j++) + { + if (j == i || j == ni) continue; + float d = distancePtSeg2d(&verts[j*3], p1,p2); + maxEdgeDist = rcMax(maxEdgeDist, d); + } + minDist = rcMin(minDist, maxEdgeDist); + } + return rcSqrt(minDist); +} + +// Last time I checked the if version got compiled using cmov, which was a lot faster than module (with idiv). +inline int prev(int i, int n) { return i-1 >= 0 ? i-1 : n-1; } +inline int next(int i, int n) { return i+1 < n ? i+1 : 0; } + +static void triangulateHull(const int /*nverts*/, const float* verts, const int nhull, const int* hull, const int nin, rcTempVector& tris) +{ + int start = 0, left = 1, right = nhull-1; + + // Start from an ear with shortest perimeter. + // This tends to favor well formed triangles as starting point. + float dmin = FLT_MAX; + for (int i = 0; i < nhull; i++) + { + if (hull[i] >= nin) continue; // Ears are triangles with original vertices as middle vertex while others are actually line segments on edges + int pi = prev(i, nhull); + int ni = next(i, nhull); + const float* pv = &verts[hull[pi]*3]; + const float* cv = &verts[hull[i]*3]; + const float* nv = &verts[hull[ni]*3]; + const float d = vdist2(pv,cv) + vdist2(cv,nv) + vdist2(nv,pv); + if (d < dmin) + { + start = i; + left = ni; + right = pi; + dmin = d; + } + } + + // Add first triangle + tris.push_back(hull[start]); + tris.push_back(hull[left]); + tris.push_back(hull[right]); + tris.push_back(0); + + // Triangulate the polygon by moving left or right, + // depending on which triangle has shorter perimeter. + // This heuristic was chose empirically, since it seems + // handle tessellated straight edges well. + while (next(left, nhull) != right) + { + // Check to see if se should advance left or right. + int nleft = next(left, nhull); + int nright = prev(right, nhull); + + const float* cvleft = &verts[hull[left]*3]; + const float* nvleft = &verts[hull[nleft]*3]; + const float* cvright = &verts[hull[right]*3]; + const float* nvright = &verts[hull[nright]*3]; + const float dleft = vdist2(cvleft, nvleft) + vdist2(nvleft, cvright); + const float dright = vdist2(cvright, nvright) + vdist2(cvleft, nvright); + + if (dleft < dright) + { + tris.push_back(hull[left]); + tris.push_back(hull[nleft]); + tris.push_back(hull[right]); + tris.push_back(0); + left = nleft; + } + else + { + tris.push_back(hull[left]); + tris.push_back(hull[nright]); + tris.push_back(hull[right]); + tris.push_back(0); + right = nright; + } + } +} + + +inline float getJitterX(const int i) +{ + return (((i * 0x8da6b343) & 0xffff) / 65535.0f * 2.0f) - 1.0f; +} + +inline float getJitterY(const int i) +{ + return (((i * 0xd8163841) & 0xffff) / 65535.0f * 2.0f) - 1.0f; +} + +static bool onHull(int a, int b, int nhull, int* hull) +{ + // All internal sampled points come after the hull so we can early out for those. + if (a >= nhull || b >= nhull) + return false; + + for (int j = nhull - 1, i = 0; i < nhull; j = i++) + { + if (a == hull[j] && b == hull[i]) + return true; + } + + return false; +} + +// Find edges that lie on hull and mark them as such. +static void setTriFlags(rcTempVector& tris, int nhull, int* hull) +{ + // Matches DT_DETAIL_EDGE_BOUNDARY + const int DETAIL_EDGE_BOUNDARY = 0x1; + + for (int i = 0; i < tris.size(); i += 4) + { + int a = tris[i + 0]; + int b = tris[i + 1]; + int c = tris[i + 2]; + unsigned short flags = 0; + flags |= (onHull(a, b, nhull, hull) ? DETAIL_EDGE_BOUNDARY : 0) << 0; + flags |= (onHull(b, c, nhull, hull) ? DETAIL_EDGE_BOUNDARY : 0) << 2; + flags |= (onHull(c, a, nhull, hull) ? DETAIL_EDGE_BOUNDARY : 0) << 4; + tris[i + 3] = (int)flags; + } +} + +static bool buildPolyDetail(rcContext* ctx, const float* in, const int nin, + const float sampleDist, const float sampleMaxError, + const int heightSearchRadius, const rcCompactHeightfield& chf, + const rcHeightPatch& hp, float* verts, int& nverts, + rcTempVector& tris, rcTempVector& edges, rcTempVector& samples) +{ + static const int MAX_VERTS = 127; + static const int MAX_TRIS = 255; // Max tris for delaunay is 2n-2-k (n=num verts, k=num hull verts). + static const int MAX_VERTS_PER_EDGE = 32; + float edge[(MAX_VERTS_PER_EDGE+1)*3]; + int hull[MAX_VERTS]; + int nhull = 0; + + nverts = nin; + + for (int i = 0; i < nin; ++i) + rcVcopy(&verts[i*3], &in[i*3]); + + edges.clear(); + tris.clear(); + + const float cs = chf.cs; + const float ics = 1.0f/cs; + + // Calculate minimum extents of the polygon based on input data. + float minExtent = polyMinExtent(verts, nverts); + + // Tessellate outlines. + // This is done in separate pass in order to ensure + // seamless height values across the ply boundaries. + if (sampleDist > 0) + { + for (int i = 0, j = nin-1; i < nin; j=i++) + { + const float* vj = &in[j*3]; + const float* vi = &in[i*3]; + bool swapped = false; + // Make sure the segments are always handled in same order + // using lexological sort or else there will be seams. + if (fabsf(vj[0]-vi[0]) < 1e-6f) + { + if (vj[2] > vi[2]) + { + rcSwap(vj,vi); + swapped = true; + } + } + else + { + if (vj[0] > vi[0]) + { + rcSwap(vj,vi); + swapped = true; + } + } + // Create samples along the edge. + float dx = vi[0] - vj[0]; + float dy = vi[1] - vj[1]; + float dz = vi[2] - vj[2]; + float d = sqrtf(dx*dx + dz*dz); + int nn = 1 + (int)floorf(d/sampleDist); + if (nn >= MAX_VERTS_PER_EDGE) nn = MAX_VERTS_PER_EDGE-1; + if (nverts+nn >= MAX_VERTS) + nn = MAX_VERTS-1-nverts; + + for (int k = 0; k <= nn; ++k) + { + float u = (float)k/(float)nn; + float* pos = &edge[k*3]; + pos[0] = vj[0] + dx*u; + pos[1] = vj[1] + dy*u; + pos[2] = vj[2] + dz*u; + pos[1] = getHeight(pos[0],pos[1],pos[2], cs, ics, chf.ch, heightSearchRadius, hp)*chf.ch; + } + // Simplify samples. + int idx[MAX_VERTS_PER_EDGE] = {0,nn}; + int nidx = 2; + for (int k = 0; k < nidx-1; ) + { + const int a = idx[k]; + const int b = idx[k+1]; + const float* va = &edge[a*3]; + const float* vb = &edge[b*3]; + // Find maximum deviation along the segment. + float maxd = 0; + int maxi = -1; + for (int m = a+1; m < b; ++m) + { + float dev = distancePtSeg(&edge[m*3],va,vb); + if (dev > maxd) + { + maxd = dev; + maxi = m; + } + } + // If the max deviation is larger than accepted error, + // add new point, else continue to next segment. + if (maxi != -1 && maxd > rcSqr(sampleMaxError)) + { + for (int m = nidx; m > k; --m) + idx[m] = idx[m-1]; + idx[k+1] = maxi; + nidx++; + } + else + { + ++k; + } + } + + hull[nhull++] = j; + // Add new vertices. + if (swapped) + { + for (int k = nidx-2; k > 0; --k) + { + rcVcopy(&verts[nverts*3], &edge[idx[k]*3]); + hull[nhull++] = nverts; + nverts++; + } + } + else + { + for (int k = 1; k < nidx-1; ++k) + { + rcVcopy(&verts[nverts*3], &edge[idx[k]*3]); + hull[nhull++] = nverts; + nverts++; + } + } + } + } + + // If the polygon minimum extent is small (sliver or small triangle), do not try to add internal points. + if (minExtent < sampleDist*2) + { + triangulateHull(nverts, verts, nhull, hull, nin, tris); + setTriFlags(tris, nhull, hull); + return true; + } + + // Tessellate the base mesh. + // We're using the triangulateHull instead of delaunayHull as it tends to + // create a bit better triangulation for long thin triangles when there + // are no internal points. + triangulateHull(nverts, verts, nhull, hull, nin, tris); + + if (tris.size() == 0) + { + // Could not triangulate the poly, make sure there is some valid data there. + ctx->log(RC_LOG_WARNING, "buildPolyDetail: Could not triangulate polygon (%d verts).", nverts); + return true; + } + + if (sampleDist > 0) + { + // Create sample locations in a grid. + float bmin[3], bmax[3]; + rcVcopy(bmin, in); + rcVcopy(bmax, in); + for (int i = 1; i < nin; ++i) + { + rcVmin(bmin, &in[i*3]); + rcVmax(bmax, &in[i*3]); + } + int x0 = (int)floorf(bmin[0]/sampleDist); + int x1 = (int)ceilf(bmax[0]/sampleDist); + int z0 = (int)floorf(bmin[2]/sampleDist); + int z1 = (int)ceilf(bmax[2]/sampleDist); + samples.clear(); + for (int z = z0; z < z1; ++z) + { + for (int x = x0; x < x1; ++x) + { + float pt[3]; + pt[0] = x*sampleDist; + pt[1] = (bmax[1]+bmin[1])*0.5f; + pt[2] = z*sampleDist; + // Make sure the samples are not too close to the edges. + if (distToPoly(nin,in,pt) > -sampleDist/2) continue; + samples.push_back(x); + samples.push_back(getHeight(pt[0], pt[1], pt[2], cs, ics, chf.ch, heightSearchRadius, hp)); + samples.push_back(z); + samples.push_back(0); // Not added + } + } + + // Add the samples starting from the one that has the most + // error. The procedure stops when all samples are added + // or when the max error is within treshold. + const int nsamples = static_cast(samples.size()) / 4; + for (int iter = 0; iter < nsamples; ++iter) + { + if (nverts >= MAX_VERTS) + break; + + // Find sample with most error. + float bestpt[3] = {0,0,0}; + float bestd = 0; + int besti = -1; + for (int i = 0; i < nsamples; ++i) + { + const int* s = &samples[i*4]; + if (s[3]) continue; // skip added. + float pt[3]; + // The sample location is jittered to get rid of some bad triangulations + // which are cause by symmetrical data from the grid structure. + pt[0] = s[0]*sampleDist + getJitterX(i)*cs*0.1f; + pt[1] = s[1]*chf.ch; + pt[2] = s[2]*sampleDist + getJitterY(i)*cs*0.1f; + if (tris.size() == 0) continue; + float d = distToTriMesh(pt, verts, nverts, &tris[0], static_cast(tris.size()) / 4); + if (d < 0) continue; // did not hit the mesh. + if (d > bestd) + { + bestd = d; + besti = i; + rcVcopy(bestpt,pt); + } + } + // If the max error is within accepted threshold, stop tesselating. + if (bestd <= sampleMaxError || besti == -1) + break; + // Mark sample as added. + samples[besti*4+3] = 1; + // Add the new sample point. + rcVcopy(&verts[nverts*3],bestpt); + nverts++; + + // Create new triangulation. + // TODO: Incremental add instead of full rebuild. + edges.clear(); + tris.clear(); + delaunayHull(ctx, nverts, verts, nhull, hull, tris, edges); + } + } + + const int ntris = static_cast(tris.size()) / 4; + if (ntris > MAX_TRIS) + { + tris.resize(MAX_TRIS*4); + ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Shrinking triangle count from %d to max %d.", ntris, MAX_TRIS); + } + + setTriFlags(tris, nhull, hull); + + return true; +} + +static void seedArrayWithPolyCenter(rcContext* ctx, const rcCompactHeightfield& chf, + const unsigned short* poly, const int npoly, + const unsigned short* verts, const int bs, + rcHeightPatch& hp, rcTempVector& array) +{ + // Note: Reads to the compact heightfield are offset by border size (bs) + // since border size offset is already removed from the polymesh vertices. + + static const int offset[9*2] = + { + 0,0, -1,-1, 0,-1, 1,-1, 1,0, 1,1, 0,1, -1,1, -1,0, + }; + + // Find cell closest to a poly vertex + int startCellX = 0, startCellY = 0, startSpanIndex = -1; + int dmin = RC_UNSET_HEIGHT; + for (int j = 0; j < npoly && dmin > 0; ++j) + { + for (int k = 0; k < 9 && dmin > 0; ++k) + { + const int ax = (int)verts[poly[j]*3+0] + offset[k*2+0]; + const int ay = (int)verts[poly[j]*3+1]; + const int az = (int)verts[poly[j]*3+2] + offset[k*2+1]; + if (ax < hp.xmin || ax >= hp.xmin+hp.width || + az < hp.ymin || az >= hp.ymin+hp.height) + continue; + + const rcCompactCell& c = chf.cells[(ax+bs)+(az+bs)*chf.width]; + for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni && dmin > 0; ++i) + { + const rcCompactSpan& s = chf.spans[i]; + int d = rcAbs(ay - (int)s.y); + if (d < dmin) + { + startCellX = ax; + startCellY = az; + startSpanIndex = i; + dmin = d; + } + } + } + } + + rcAssert(startSpanIndex != -1); + // Find center of the polygon + int pcx = 0, pcy = 0; + for (int j = 0; j < npoly; ++j) + { + pcx += (int)verts[poly[j]*3+0]; + pcy += (int)verts[poly[j]*3+2]; + } + pcx /= npoly; + pcy /= npoly; + + // Use seeds array as a stack for DFS + array.clear(); + array.push_back(startCellX); + array.push_back(startCellY); + array.push_back(startSpanIndex); + + int dirs[] = { 0, 1, 2, 3 }; + memset(hp.data, 0, sizeof(unsigned short)*hp.width*hp.height); + // DFS to move to the center. Note that we need a DFS here and can not just move + // directly towards the center without recording intermediate nodes, even though the polygons + // are convex. In very rare we can get stuck due to contour simplification if we do not + // record nodes. + int cx = -1, cy = -1, ci = -1; + while (true) + { + if (array.size() < 3) + { + ctx->log(RC_LOG_WARNING, "Walk towards polygon center failed to reach center"); + break; + } + + ci = array.back(); array.pop_back(); + cy = array.back(); array.pop_back(); + cx = array.back(); array.pop_back(); + + if (cx == pcx && cy == pcy) + break; + + // If we are already at the correct X-position, prefer direction + // directly towards the center in the Y-axis; otherwise prefer + // direction in the X-axis + int directDir; + if (cx == pcx) + directDir = rcGetDirForOffset(0, pcy > cy ? 1 : -1); + else + directDir = rcGetDirForOffset(pcx > cx ? 1 : -1, 0); + + // Push the direct dir last so we start with this on next iteration + rcSwap(dirs[directDir], dirs[3]); + + const rcCompactSpan& cs = chf.spans[ci]; + for (int i = 0; i < 4; i++) + { + int dir = dirs[i]; + if (rcGetCon(cs, dir) == RC_NOT_CONNECTED) + continue; + + int newX = cx + rcGetDirOffsetX(dir); + int newY = cy + rcGetDirOffsetY(dir); + + int hpx = newX - hp.xmin; + int hpy = newY - hp.ymin; + if (hpx < 0 || hpx >= hp.width || hpy < 0 || hpy >= hp.height) + continue; + + if (hp.data[hpx+hpy*hp.width] != 0) + continue; + + hp.data[hpx+hpy*hp.width] = 1; + array.push_back(newX); + array.push_back(newY); + array.push_back((int)chf.cells[(newX+bs)+(newY+bs)*chf.width].index + rcGetCon(cs, dir)); + } + + rcSwap(dirs[directDir], dirs[3]); + } + + array.clear(); + // getHeightData seeds are given in coordinates with borders + array.push_back(cx+bs); + array.push_back(cy+bs); + array.push_back(ci); + + memset(hp.data, 0xff, sizeof(unsigned short)*hp.width*hp.height); + const rcCompactSpan& cs = chf.spans[ci]; + hp.data[cx-hp.xmin+(cy-hp.ymin)*hp.width] = cs.y; +} + + +static void push3(rcTempVector& queue, int v1, int v2, int v3) +{ + queue.resize(queue.size() + 3); + queue[queue.size() - 3] = v1; + queue[queue.size() - 2] = v2; + queue[queue.size() - 1] = v3; +} + +static void getHeightData(rcContext* ctx, const rcCompactHeightfield& chf, + const unsigned short* poly, const int npoly, + const unsigned short* verts, const int bs, + rcHeightPatch& hp, rcTempVector& queue, + int region) +{ + // Note: Reads to the compact heightfield are offset by border size (bs) + // since border size offset is already removed from the polymesh vertices. + + queue.clear(); + // Set all heights to RC_UNSET_HEIGHT. + memset(hp.data, 0xff, sizeof(unsigned short)*hp.width*hp.height); + + bool empty = true; + + // We cannot sample from this poly if it was created from polys + // of different regions. If it was then it could potentially be overlapping + // with polys of that region and the heights sampled here could be wrong. + if (region != RC_MULTIPLE_REGS) + { + // Copy the height from the same region, and mark region borders + // as seed points to fill the rest. + for (int hy = 0; hy < hp.height; hy++) + { + int y = hp.ymin + hy + bs; + for (int hx = 0; hx < hp.width; hx++) + { + int x = hp.xmin + hx + bs; + const rcCompactCell& c = chf.cells[x + y*chf.width]; + for (int i = (int)c.index, ni = (int)(c.index + c.count); i < ni; ++i) + { + const rcCompactSpan& s = chf.spans[i]; + if (s.reg == region) + { + // Store height + hp.data[hx + hy*hp.width] = s.y; + empty = false; + + // If any of the neighbours is not in same region, + // add the current location as flood fill start + bool border = false; + for (int dir = 0; dir < 4; ++dir) + { + if (rcGetCon(s, dir) != RC_NOT_CONNECTED) + { + const int ax = x + rcGetDirOffsetX(dir); + const int ay = y + rcGetDirOffsetY(dir); + const int ai = (int)chf.cells[ax + ay*chf.width].index + rcGetCon(s, dir); + const rcCompactSpan& as = chf.spans[ai]; + if (as.reg != region) + { + border = true; + break; + } + } + } + if (border) + push3(queue, x, y, i); + break; + } + } + } + } + } + + // if the polygon does not contain any points from the current region (rare, but happens) + // or if it could potentially be overlapping polygons of the same region, + // then use the center as the seed point. + if (empty) + seedArrayWithPolyCenter(ctx, chf, poly, npoly, verts, bs, hp, queue); + + static const int RETRACT_SIZE = 256; + int head = 0; + + // We assume the seed is centered in the polygon, so a BFS to collect + // height data will ensure we do not move onto overlapping polygons and + // sample wrong heights. + while (head*3 < queue.size()) + { + int cx = queue[head*3+0]; + int cy = queue[head*3+1]; + int ci = queue[head*3+2]; + head++; + if (head >= RETRACT_SIZE) + { + head = 0; + if (queue.size() > RETRACT_SIZE*3) + memmove(&queue[0], &queue[RETRACT_SIZE*3], sizeof(int)*(queue.size()-RETRACT_SIZE*3)); + queue.resize(queue.size()-RETRACT_SIZE*3); + } + + const rcCompactSpan& cs = chf.spans[ci]; + for (int dir = 0; dir < 4; ++dir) + { + if (rcGetCon(cs, dir) == RC_NOT_CONNECTED) continue; + + const int ax = cx + rcGetDirOffsetX(dir); + const int ay = cy + rcGetDirOffsetY(dir); + const int hx = ax - hp.xmin - bs; + const int hy = ay - hp.ymin - bs; + + if ((unsigned int)hx >= (unsigned int)hp.width || (unsigned int)hy >= (unsigned int)hp.height) + continue; + + if (hp.data[hx + hy*hp.width] != RC_UNSET_HEIGHT) + continue; + + const int ai = (int)chf.cells[ax + ay*chf.width].index + rcGetCon(cs, dir); + const rcCompactSpan& as = chf.spans[ai]; + + hp.data[hx + hy*hp.width] = as.y; + + push3(queue, ax, ay, ai); + } + } +} + +/// @par +/// +/// See the #rcConfig documentation for more information on the configuration parameters. +/// +/// @see rcAllocPolyMeshDetail, rcPolyMesh, rcCompactHeightfield, rcPolyMeshDetail, rcConfig +bool rcBuildPolyMeshDetail(rcContext* ctx, const rcPolyMesh& mesh, const rcCompactHeightfield& chf, + const float sampleDist, const float sampleMaxError, + rcPolyMeshDetail& dmesh) +{ + rcAssert(ctx); + + rcScopedTimer timer(ctx, RC_TIMER_BUILD_POLYMESHDETAIL); + + if (mesh.nverts == 0 || mesh.npolys == 0) + return true; + + const int nvp = mesh.nvp; + const float cs = mesh.cs; + const float ch = mesh.ch; + const float* orig = mesh.bmin; + const int borderSize = mesh.borderSize; + const int heightSearchRadius = rcMax(1, (int)ceilf(mesh.maxEdgeError)); + + rcTempVector edges(64); + rcTempVector tris(512); + rcTempVector arr(512); + rcTempVector samples(512); + float verts[256*3]; + rcHeightPatch hp; + int nPolyVerts = 0; + int maxhw = 0, maxhh = 0; + + rcScopedDelete bounds((int*)rcAlloc(sizeof(int)*mesh.npolys*4, RC_ALLOC_TEMP)); + if (!bounds) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'bounds' (%d).", mesh.npolys*4); + return false; + } + rcScopedDelete poly((float*)rcAlloc(sizeof(float)*nvp*3, RC_ALLOC_TEMP)); + if (!poly) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'poly' (%d).", nvp*3); + return false; + } + + // Find max size for a polygon area. + for (int i = 0; i < mesh.npolys; ++i) + { + const unsigned short* p = &mesh.polys[i*nvp*2]; + int& xmin = bounds[i*4+0]; + int& xmax = bounds[i*4+1]; + int& ymin = bounds[i*4+2]; + int& ymax = bounds[i*4+3]; + xmin = chf.width; + xmax = 0; + ymin = chf.height; + ymax = 0; + for (int j = 0; j < nvp; ++j) + { + if(p[j] == RC_MESH_NULL_IDX) break; + const unsigned short* v = &mesh.verts[p[j]*3]; + xmin = rcMin(xmin, (int)v[0]); + xmax = rcMax(xmax, (int)v[0]); + ymin = rcMin(ymin, (int)v[2]); + ymax = rcMax(ymax, (int)v[2]); + nPolyVerts++; + } + xmin = rcMax(0,xmin-1); + xmax = rcMin(chf.width,xmax+1); + ymin = rcMax(0,ymin-1); + ymax = rcMin(chf.height,ymax+1); + if (xmin >= xmax || ymin >= ymax) continue; + maxhw = rcMax(maxhw, xmax-xmin); + maxhh = rcMax(maxhh, ymax-ymin); + } + + hp.data = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxhw*maxhh, RC_ALLOC_TEMP); + if (!hp.data) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'hp.data' (%d).", maxhw*maxhh); + return false; + } + + dmesh.nmeshes = mesh.npolys; + dmesh.nverts = 0; + dmesh.ntris = 0; + dmesh.meshes = (unsigned int*)rcAlloc(sizeof(unsigned int)*dmesh.nmeshes*4, RC_ALLOC_PERM); + if (!dmesh.meshes) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.meshes' (%d).", dmesh.nmeshes*4); + return false; + } + + int vcap = nPolyVerts+nPolyVerts/2; + int tcap = vcap*2; + + dmesh.nverts = 0; + dmesh.verts = (float*)rcAlloc(sizeof(float)*vcap*3, RC_ALLOC_PERM); + if (!dmesh.verts) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.verts' (%d).", vcap*3); + return false; + } + dmesh.ntris = 0; + dmesh.tris = (unsigned char*)rcAlloc(sizeof(unsigned char)*tcap*4, RC_ALLOC_PERM); + if (!dmesh.tris) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.tris' (%d).", tcap*4); + return false; + } + + for (int i = 0; i < mesh.npolys; ++i) + { + const unsigned short* p = &mesh.polys[i*nvp*2]; + + // Store polygon vertices for processing. + int npoly = 0; + for (int j = 0; j < nvp; ++j) + { + if(p[j] == RC_MESH_NULL_IDX) break; + const unsigned short* v = &mesh.verts[p[j]*3]; + poly[j*3+0] = v[0]*cs; + poly[j*3+1] = v[1]*ch; + poly[j*3+2] = v[2]*cs; + npoly++; + } + + // Get the height data from the area of the polygon. + hp.xmin = bounds[i*4+0]; + hp.ymin = bounds[i*4+2]; + hp.width = bounds[i*4+1]-bounds[i*4+0]; + hp.height = bounds[i*4+3]-bounds[i*4+2]; + getHeightData(ctx, chf, p, npoly, mesh.verts, borderSize, hp, arr, mesh.regs[i]); + + // Build detail mesh. + int nverts = 0; + if (!buildPolyDetail(ctx, poly, npoly, + sampleDist, sampleMaxError, + heightSearchRadius, chf, hp, + verts, nverts, tris, + edges, samples)) + { + return false; + } + + // Move detail verts to world space. + for (int j = 0; j < nverts; ++j) + { + verts[j*3+0] += orig[0]; + verts[j*3+1] += orig[1] + chf.ch; // Is this offset necessary? + verts[j*3+2] += orig[2]; + } + // Offset poly too, will be used to flag checking. + for (int j = 0; j < npoly; ++j) + { + poly[j*3+0] += orig[0]; + poly[j*3+1] += orig[1]; + poly[j*3+2] += orig[2]; + } + + // Store detail submesh. + const int ntris = static_cast(tris.size()) / 4; + + dmesh.meshes[i*4+0] = (unsigned int)dmesh.nverts; + dmesh.meshes[i*4+1] = (unsigned int)nverts; + dmesh.meshes[i*4+2] = (unsigned int)dmesh.ntris; + dmesh.meshes[i*4+3] = (unsigned int)ntris; + + // Store vertices, allocate more memory if necessary. + if (dmesh.nverts+nverts > vcap) + { + while (dmesh.nverts+nverts > vcap) + vcap += 256; + + float* newv = (float*)rcAlloc(sizeof(float)*vcap*3, RC_ALLOC_PERM); + if (!newv) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'newv' (%d).", vcap*3); + return false; + } + if (dmesh.nverts) + memcpy(newv, dmesh.verts, sizeof(float)*3*dmesh.nverts); + rcFree(dmesh.verts); + dmesh.verts = newv; + } + for (int j = 0; j < nverts; ++j) + { + dmesh.verts[dmesh.nverts*3+0] = verts[j*3+0]; + dmesh.verts[dmesh.nverts*3+1] = verts[j*3+1]; + dmesh.verts[dmesh.nverts*3+2] = verts[j*3+2]; + dmesh.nverts++; + } + + // Store triangles, allocate more memory if necessary. + if (dmesh.ntris+ntris > tcap) + { + while (dmesh.ntris+ntris > tcap) + tcap += 256; + unsigned char* newt = (unsigned char*)rcAlloc(sizeof(unsigned char)*tcap*4, RC_ALLOC_PERM); + if (!newt) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'newt' (%d).", tcap*4); + return false; + } + if (dmesh.ntris) + memcpy(newt, dmesh.tris, sizeof(unsigned char)*4*dmesh.ntris); + rcFree(dmesh.tris); + dmesh.tris = newt; + } + for (int j = 0; j < ntris; ++j) + { + const int* t = &tris[j*4]; + dmesh.tris[dmesh.ntris*4+0] = (unsigned char)t[0]; + dmesh.tris[dmesh.ntris*4+1] = (unsigned char)t[1]; + dmesh.tris[dmesh.ntris*4+2] = (unsigned char)t[2]; + dmesh.tris[dmesh.ntris*4+3] = (unsigned char)t[3]; + dmesh.ntris++; + } + } + + return true; +} + +/// @see rcAllocPolyMeshDetail, rcPolyMeshDetail +bool rcMergePolyMeshDetails(rcContext* ctx, rcPolyMeshDetail** meshes, const int nmeshes, rcPolyMeshDetail& mesh) +{ + rcAssert(ctx); + + rcScopedTimer timer(ctx, RC_TIMER_MERGE_POLYMESHDETAIL); + + int maxVerts = 0; + int maxTris = 0; + int maxMeshes = 0; + + for (int i = 0; i < nmeshes; ++i) + { + if (!meshes[i]) continue; + maxVerts += meshes[i]->nverts; + maxTris += meshes[i]->ntris; + maxMeshes += meshes[i]->nmeshes; + } + + mesh.nmeshes = 0; + mesh.meshes = (unsigned int*)rcAlloc(sizeof(unsigned int)*maxMeshes*4, RC_ALLOC_PERM); + if (!mesh.meshes) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'pmdtl.meshes' (%d).", maxMeshes*4); + return false; + } + + mesh.ntris = 0; + mesh.tris = (unsigned char*)rcAlloc(sizeof(unsigned char)*maxTris*4, RC_ALLOC_PERM); + if (!mesh.tris) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.tris' (%d).", maxTris*4); + return false; + } + + mesh.nverts = 0; + mesh.verts = (float*)rcAlloc(sizeof(float)*maxVerts*3, RC_ALLOC_PERM); + if (!mesh.verts) + { + ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.verts' (%d).", maxVerts*3); + return false; + } + + // Merge datas. + for (int i = 0; i < nmeshes; ++i) + { + rcPolyMeshDetail* dm = meshes[i]; + if (!dm) continue; + for (int j = 0; j < dm->nmeshes; ++j) + { + unsigned int* dst = &mesh.meshes[mesh.nmeshes*4]; + unsigned int* src = &dm->meshes[j*4]; + dst[0] = (unsigned int)mesh.nverts+src[0]; + dst[1] = src[1]; + dst[2] = (unsigned int)mesh.ntris+src[2]; + dst[3] = src[3]; + mesh.nmeshes++; + } + + for (int k = 0; k < dm->nverts; ++k) + { + rcVcopy(&mesh.verts[mesh.nverts*3], &dm->verts[k*3]); + mesh.nverts++; + } + for (int k = 0; k < dm->ntris; ++k) + { + mesh.tris[mesh.ntris*4+0] = dm->tris[k*4+0]; + mesh.tris[mesh.ntris*4+1] = dm->tris[k*4+1]; + mesh.tris[mesh.ntris*4+2] = dm->tris[k*4+2]; + mesh.tris[mesh.ntris*4+3] = dm->tris[k*4+3]; + mesh.ntris++; + } + } + + return true; +} diff --git a/native/third_party/recastnavigation/Recast/Source/RecastRasterization.cpp b/native/third_party/recastnavigation/Recast/Source/RecastRasterization.cpp new file mode 100644 index 0000000..c65d6ea --- /dev/null +++ b/native/third_party/recastnavigation/Recast/Source/RecastRasterization.cpp @@ -0,0 +1,562 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#include +#include "Recast.h" +#include "RecastAlloc.h" +#include "RecastAssert.h" + +/// Check whether two bounding boxes overlap +/// +/// @param[in] aMin Min axis extents of bounding box A +/// @param[in] aMax Max axis extents of bounding box A +/// @param[in] bMin Min axis extents of bounding box B +/// @param[in] bMax Max axis extents of bounding box B +/// @returns true if the two bounding boxes overlap. False otherwise. +static bool overlapBounds(const float* aMin, const float* aMax, const float* bMin, const float* bMax) +{ + return + aMin[0] <= bMax[0] && aMax[0] >= bMin[0] && + aMin[1] <= bMax[1] && aMax[1] >= bMin[1] && + aMin[2] <= bMax[2] && aMax[2] >= bMin[2]; +} + +/// Allocates a new span in the heightfield. +/// Use a memory pool and free list to minimize actual allocations. +/// +/// @param[in] heightfield The heightfield +/// @returns A pointer to the allocated or re-used span memory. +static rcSpan* allocSpan(rcHeightfield& heightfield) +{ + // If necessary, allocate new page and update the freelist. + if (heightfield.freelist == NULL || heightfield.freelist->next == NULL) + { + // Create new page. + // Allocate memory for the new pool. + rcSpanPool* spanPool = (rcSpanPool*)rcAlloc(sizeof(rcSpanPool), RC_ALLOC_PERM); + if (spanPool == NULL) + { + return NULL; + } + + // Add the pool into the list of pools. + spanPool->next = heightfield.pools; + heightfield.pools = spanPool; + + // Add new spans to the free list. + rcSpan* freeList = heightfield.freelist; + rcSpan* head = &spanPool->items[0]; + rcSpan* it = &spanPool->items[RC_SPANS_PER_POOL]; + do + { + --it; + it->next = freeList; + freeList = it; + } + while (it != head); + heightfield.freelist = it; + } + + // Pop item from the front of the free list. + rcSpan* newSpan = heightfield.freelist; + heightfield.freelist = heightfield.freelist->next; + return newSpan; +} + +/// Releases the memory used by the span back to the heightfield, so it can be re-used for new spans. +/// @param[in] heightfield The heightfield. +/// @param[in] span A pointer to the span to free +static void freeSpan(rcHeightfield& heightfield, rcSpan* span) +{ + if (span == NULL) + { + return; + } + // Add the span to the front of the free list. + span->next = heightfield.freelist; + heightfield.freelist = span; +} + +/// Adds a span to the heightfield. If the new span overlaps existing spans, +/// it will merge the new span with the existing ones. +/// +/// @param[in] heightfield Heightfield to add spans to +/// @param[in] x The new span's column cell x index +/// @param[in] z The new span's column cell z index +/// @param[in] min The new span's minimum cell index +/// @param[in] max The new span's maximum cell index +/// @param[in] areaID The new span's area type ID +/// @param[in] flagMergeThreshold How close two spans maximum extents need to be to merge area type IDs +static bool addSpan(rcHeightfield& heightfield, + const int x, const int z, + const unsigned short min, const unsigned short max, + const unsigned char areaID, const int flagMergeThreshold) +{ + // Create the new span. + rcSpan* newSpan = allocSpan(heightfield); + if (newSpan == NULL) + { + return false; + } + newSpan->smin = min; + newSpan->smax = max; + newSpan->area = areaID; + newSpan->next = NULL; + + const int columnIndex = x + z * heightfield.width; + rcSpan* previousSpan = NULL; + rcSpan* currentSpan = heightfield.spans[columnIndex]; + + // Insert the new span, possibly merging it with existing spans. + while (currentSpan != NULL) + { + if (currentSpan->smin > newSpan->smax) + { + // Current span is completely after the new span, break. + break; + } + + if (currentSpan->smax < newSpan->smin) + { + // Current span is completely before the new span. Keep going. + previousSpan = currentSpan; + currentSpan = currentSpan->next; + } + else + { + // The new span overlaps with an existing span. Merge them. + if (currentSpan->smin < newSpan->smin) + { + newSpan->smin = currentSpan->smin; + } + if (currentSpan->smax > newSpan->smax) + { + newSpan->smax = currentSpan->smax; + } + + // Merge flags. + if (rcAbs((int)newSpan->smax - (int)currentSpan->smax) <= flagMergeThreshold) + { + // Higher area ID numbers indicate higher resolution priority. + newSpan->area = rcMax(newSpan->area, currentSpan->area); + } + + // Remove the current span since it's now merged with newSpan. + // Keep going because there might be other overlapping spans that also need to be merged. + rcSpan* next = currentSpan->next; + freeSpan(heightfield, currentSpan); + if (previousSpan) + { + previousSpan->next = next; + } + else + { + heightfield.spans[columnIndex] = next; + } + currentSpan = next; + } + } + + // Insert new span after prev + if (previousSpan != NULL) + { + newSpan->next = previousSpan->next; + previousSpan->next = newSpan; + } + else + { + // This span should go before the others in the list + newSpan->next = heightfield.spans[columnIndex]; + heightfield.spans[columnIndex] = newSpan; + } + + return true; +} + +bool rcAddSpan(rcContext* context, rcHeightfield& heightfield, + const int x, const int z, + const unsigned short spanMin, const unsigned short spanMax, + const unsigned char areaID, const int flagMergeThreshold) +{ + rcAssert(context); + + // Span is zero size or inverted size. Ignore. + if (spanMin >= spanMax) + { + context->log(RC_LOG_WARNING, "rcAddSpan: Adding a span with zero or negative size. Ignored."); + return true; + } + + if (!addSpan(heightfield, x, z, spanMin, spanMax, areaID, flagMergeThreshold)) + { + context->log(RC_LOG_ERROR, "rcAddSpan: Out of memory."); + return false; + } + + return true; +} + +enum rcAxis +{ + RC_AXIS_X = 0, + RC_AXIS_Y = 1, + RC_AXIS_Z = 2 +}; + +/// Divides a convex polygon of max 12 vertices into two convex polygons +/// across a separating axis. +/// +/// @param[in] inVerts The input polygon vertices +/// @param[in] inVertsCount The number of input polygon vertices +/// @param[out] outVerts1 Resulting polygon 1's vertices +/// @param[out] outVerts1Count The number of resulting polygon 1 vertices +/// @param[out] outVerts2 Resulting polygon 2's vertices +/// @param[out] outVerts2Count The number of resulting polygon 2 vertices +/// @param[in] axisOffset THe offset along the specified axis +/// @param[in] axis The separating axis +static void dividePoly(const float* inVerts, int inVertsCount, + float* outVerts1, int* outVerts1Count, + float* outVerts2, int* outVerts2Count, + float axisOffset, rcAxis axis) +{ + rcAssert(inVertsCount <= 12); + + // How far positive or negative away from the separating axis is each vertex. + float inVertAxisDelta[12]; + for (int inVert = 0; inVert < inVertsCount; ++inVert) + { + inVertAxisDelta[inVert] = axisOffset - inVerts[inVert * 3 + axis]; + } + + int poly1Vert = 0; + int poly2Vert = 0; + for (int inVertA = 0, inVertB = inVertsCount - 1; inVertA < inVertsCount; inVertB = inVertA, ++inVertA) + { + // If the two vertices are on the same side of the separating axis + bool sameSide = (inVertAxisDelta[inVertA] >= 0) == (inVertAxisDelta[inVertB] >= 0); + + if (!sameSide) + { + float s = inVertAxisDelta[inVertB] / (inVertAxisDelta[inVertB] - inVertAxisDelta[inVertA]); + outVerts1[poly1Vert * 3 + 0] = inVerts[inVertB * 3 + 0] + (inVerts[inVertA * 3 + 0] - inVerts[inVertB * 3 + 0]) * s; + outVerts1[poly1Vert * 3 + 1] = inVerts[inVertB * 3 + 1] + (inVerts[inVertA * 3 + 1] - inVerts[inVertB * 3 + 1]) * s; + outVerts1[poly1Vert * 3 + 2] = inVerts[inVertB * 3 + 2] + (inVerts[inVertA * 3 + 2] - inVerts[inVertB * 3 + 2]) * s; + rcVcopy(&outVerts2[poly2Vert * 3], &outVerts1[poly1Vert * 3]); + poly1Vert++; + poly2Vert++; + + // add the inVertA point to the right polygon. Do NOT add points that are on the dividing line + // since these were already added above + if (inVertAxisDelta[inVertA] > 0) + { + rcVcopy(&outVerts1[poly1Vert * 3], &inVerts[inVertA * 3]); + poly1Vert++; + } + else if (inVertAxisDelta[inVertA] < 0) + { + rcVcopy(&outVerts2[poly2Vert * 3], &inVerts[inVertA * 3]); + poly2Vert++; + } + } + else + { + // add the inVertA point to the right polygon. Addition is done even for points on the dividing line + if (inVertAxisDelta[inVertA] >= 0) + { + rcVcopy(&outVerts1[poly1Vert * 3], &inVerts[inVertA * 3]); + poly1Vert++; + if (inVertAxisDelta[inVertA] != 0) + { + continue; + } + } + rcVcopy(&outVerts2[poly2Vert * 3], &inVerts[inVertA * 3]); + poly2Vert++; + } + } + + *outVerts1Count = poly1Vert; + *outVerts2Count = poly2Vert; +} + +/// Rasterize a single triangle to the heightfield. +/// +/// This code is extremely hot, so much care should be given to maintaining maximum perf here. +/// +/// @param[in] v0 Triangle vertex 0 +/// @param[in] v1 Triangle vertex 1 +/// @param[in] v2 Triangle vertex 2 +/// @param[in] areaID The area ID to assign to the rasterized spans +/// @param[in] heightfield Heightfield to rasterize into +/// @param[in] heightfieldBBMin The min extents of the heightfield bounding box +/// @param[in] heightfieldBBMax The max extents of the heightfield bounding box +/// @param[in] cellSize The x and z axis size of a voxel in the heightfield +/// @param[in] inverseCellSize 1 / cellSize +/// @param[in] inverseCellHeight 1 / cellHeight +/// @param[in] flagMergeThreshold The threshold in which area flags will be merged +/// @returns true if the operation completes successfully. false if there was an error adding spans to the heightfield. +static bool rasterizeTri(const float* v0, const float* v1, const float* v2, + const unsigned char areaID, rcHeightfield& heightfield, + const float* heightfieldBBMin, const float* heightfieldBBMax, + const float cellSize, const float inverseCellSize, const float inverseCellHeight, + const int flagMergeThreshold) +{ + // Calculate the bounding box of the triangle. + float triBBMin[3]; + rcVcopy(triBBMin, v0); + rcVmin(triBBMin, v1); + rcVmin(triBBMin, v2); + + float triBBMax[3]; + rcVcopy(triBBMax, v0); + rcVmax(triBBMax, v1); + rcVmax(triBBMax, v2); + + // If the triangle does not touch the bounding box of the heightfield, skip the triangle. + if (!overlapBounds(triBBMin, triBBMax, heightfieldBBMin, heightfieldBBMax)) + { + return true; + } + + const int w = heightfield.width; + const int h = heightfield.height; + const float by = heightfieldBBMax[1] - heightfieldBBMin[1]; + + // Calculate the footprint of the triangle on the grid's z-axis + int z0 = (int)((triBBMin[2] - heightfieldBBMin[2]) * inverseCellSize); + int z1 = (int)((triBBMax[2] - heightfieldBBMin[2]) * inverseCellSize); + + // use -1 rather than 0 to cut the polygon properly at the start of the tile + z0 = rcClamp(z0, -1, h - 1); + z1 = rcClamp(z1, 0, h - 1); + + // Clip the triangle into all grid cells it touches. + float buf[7 * 3 * 4]; + float* in = buf; + float* inRow = buf + 7 * 3; + float* p1 = inRow + 7 * 3; + float* p2 = p1 + 7 * 3; + + rcVcopy(&in[0], v0); + rcVcopy(&in[1 * 3], v1); + rcVcopy(&in[2 * 3], v2); + int nvRow; + int nvIn = 3; + + for (int z = z0; z <= z1; ++z) + { + // Clip polygon to row. Store the remaining polygon as well + const float cellZ = heightfieldBBMin[2] + (float)z * cellSize; + dividePoly(in, nvIn, inRow, &nvRow, p1, &nvIn, cellZ + cellSize, RC_AXIS_Z); + rcSwap(in, p1); + + if (nvRow < 3) + { + continue; + } + if (z < 0) + { + continue; + } + + // find X-axis bounds of the row + float minX = inRow[0]; + float maxX = inRow[0]; + for (int vert = 1; vert < nvRow; ++vert) + { + if (minX > inRow[vert * 3]) + { + minX = inRow[vert * 3]; + } + if (maxX < inRow[vert * 3]) + { + maxX = inRow[vert * 3]; + } + } + int x0 = (int)((minX - heightfieldBBMin[0]) * inverseCellSize); + int x1 = (int)((maxX - heightfieldBBMin[0]) * inverseCellSize); + if (x1 < 0 || x0 >= w) + { + continue; + } + x0 = rcClamp(x0, -1, w - 1); + x1 = rcClamp(x1, 0, w - 1); + + int nv; + int nv2 = nvRow; + + for (int x = x0; x <= x1; ++x) + { + // Clip polygon to column. store the remaining polygon as well + const float cx = heightfieldBBMin[0] + (float)x * cellSize; + dividePoly(inRow, nv2, p1, &nv, p2, &nv2, cx + cellSize, RC_AXIS_X); + rcSwap(inRow, p2); + + if (nv < 3) + { + continue; + } + if (x < 0) + { + continue; + } + + // Calculate min and max of the span. + float spanMin = p1[1]; + float spanMax = p1[1]; + for (int vert = 1; vert < nv; ++vert) + { + spanMin = rcMin(spanMin, p1[vert * 3 + 1]); + spanMax = rcMax(spanMax, p1[vert * 3 + 1]); + } + spanMin -= heightfieldBBMin[1]; + spanMax -= heightfieldBBMin[1]; + + // Skip the span if it's completely outside the heightfield bounding box + if (spanMax < 0.0f) + { + continue; + } + if (spanMin > by) + { + continue; + } + + // Clamp the span to the heightfield bounding box. + if (spanMin < 0.0f) + { + spanMin = 0; + } + if (spanMax > by) + { + spanMax = by; + } + + // Snap the span to the heightfield height grid. + unsigned short spanMinCellIndex = (unsigned short)rcClamp((int)floorf(spanMin * inverseCellHeight), 0, RC_SPAN_MAX_HEIGHT); + unsigned short spanMaxCellIndex = (unsigned short)rcClamp((int)ceilf(spanMax * inverseCellHeight), (int)spanMinCellIndex + 1, RC_SPAN_MAX_HEIGHT); + + if (!addSpan(heightfield, x, z, spanMinCellIndex, spanMaxCellIndex, areaID, flagMergeThreshold)) + { + return false; + } + } + } + + return true; +} + +bool rcRasterizeTriangle(rcContext* context, + const float* v0, const float* v1, const float* v2, + const unsigned char areaID, rcHeightfield& heightfield, const int flagMergeThreshold) +{ + rcAssert(context != NULL); + + rcScopedTimer timer(context, RC_TIMER_RASTERIZE_TRIANGLES); + + // Rasterize the single triangle. + const float inverseCellSize = 1.0f / heightfield.cs; + const float inverseCellHeight = 1.0f / heightfield.ch; + if (!rasterizeTri(v0, v1, v2, areaID, heightfield, heightfield.bmin, heightfield.bmax, heightfield.cs, inverseCellSize, inverseCellHeight, flagMergeThreshold)) + { + context->log(RC_LOG_ERROR, "rcRasterizeTriangle: Out of memory."); + return false; + } + + return true; +} + +bool rcRasterizeTriangles(rcContext* context, + const float* verts, const int /*nv*/, + const int* tris, const unsigned char* triAreaIDs, const int numTris, + rcHeightfield& heightfield, const int flagMergeThreshold) +{ + rcAssert(context != NULL); + + rcScopedTimer timer(context, RC_TIMER_RASTERIZE_TRIANGLES); + + // Rasterize the triangles. + const float inverseCellSize = 1.0f / heightfield.cs; + const float inverseCellHeight = 1.0f / heightfield.ch; + for (int triIndex = 0; triIndex < numTris; ++triIndex) + { + const float* v0 = &verts[tris[triIndex * 3 + 0] * 3]; + const float* v1 = &verts[tris[triIndex * 3 + 1] * 3]; + const float* v2 = &verts[tris[triIndex * 3 + 2] * 3]; + if (!rasterizeTri(v0, v1, v2, triAreaIDs[triIndex], heightfield, heightfield.bmin, heightfield.bmax, heightfield.cs, inverseCellSize, inverseCellHeight, flagMergeThreshold)) + { + context->log(RC_LOG_ERROR, "rcRasterizeTriangles: Out of memory."); + return false; + } + } + + return true; +} + +bool rcRasterizeTriangles(rcContext* context, + const float* verts, const int /*nv*/, + const unsigned short* tris, const unsigned char* triAreaIDs, const int numTris, + rcHeightfield& heightfield, const int flagMergeThreshold) +{ + rcAssert(context != NULL); + + rcScopedTimer timer(context, RC_TIMER_RASTERIZE_TRIANGLES); + + // Rasterize the triangles. + const float inverseCellSize = 1.0f / heightfield.cs; + const float inverseCellHeight = 1.0f / heightfield.ch; + for (int triIndex = 0; triIndex < numTris; ++triIndex) + { + const float* v0 = &verts[tris[triIndex * 3 + 0] * 3]; + const float* v1 = &verts[tris[triIndex * 3 + 1] * 3]; + const float* v2 = &verts[tris[triIndex * 3 + 2] * 3]; + if (!rasterizeTri(v0, v1, v2, triAreaIDs[triIndex], heightfield, heightfield.bmin, heightfield.bmax, heightfield.cs, inverseCellSize, inverseCellHeight, flagMergeThreshold)) + { + context->log(RC_LOG_ERROR, "rcRasterizeTriangles: Out of memory."); + return false; + } + } + + return true; +} + +bool rcRasterizeTriangles(rcContext* context, + const float* verts, const unsigned char* triAreaIDs, const int numTris, + rcHeightfield& heightfield, const int flagMergeThreshold) +{ + rcAssert(context != NULL); + + rcScopedTimer timer(context, RC_TIMER_RASTERIZE_TRIANGLES); + + // Rasterize the triangles. + const float inverseCellSize = 1.0f / heightfield.cs; + const float inverseCellHeight = 1.0f / heightfield.ch; + for (int triIndex = 0; triIndex < numTris; ++triIndex) + { + const float* v0 = &verts[(triIndex * 3 + 0) * 3]; + const float* v1 = &verts[(triIndex * 3 + 1) * 3]; + const float* v2 = &verts[(triIndex * 3 + 2) * 3]; + if (!rasterizeTri(v0, v1, v2, triAreaIDs[triIndex], heightfield, heightfield.bmin, heightfield.bmax, heightfield.cs, inverseCellSize, inverseCellHeight, flagMergeThreshold)) + { + context->log(RC_LOG_ERROR, "rcRasterizeTriangles: Out of memory."); + return false; + } + } + + return true; +} diff --git a/native/third_party/recastnavigation/Recast/Source/RecastRegion.cpp b/native/third_party/recastnavigation/Recast/Source/RecastRegion.cpp new file mode 100644 index 0000000..48eed36 --- /dev/null +++ b/native/third_party/recastnavigation/Recast/Source/RecastRegion.cpp @@ -0,0 +1,1820 @@ +// +// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. +// + +#include +#include +#include +#include +#include +#include "Recast.h" +#include "RecastAlloc.h" +#include "RecastAssert.h" + +namespace +{ +struct LevelStackEntry +{ + LevelStackEntry(int x_, int y_, int index_) : x(x_), y(y_), index(index_) {} + int x; + int y; + int index; +}; +} // namespace + +static void calculateDistanceField(rcCompactHeightfield& chf, unsigned short* src, unsigned short& maxDist) +{ + const int w = chf.width; + const int h = chf.height; + + // Init distance and points. + for (int i = 0; i < chf.spanCount; ++i) + src[i] = 0xffff; + + // Mark boundary cells. + for (int y = 0; y < h; ++y) + { + for (int x = 0; x < w; ++x) + { + const rcCompactCell& c = chf.cells[x+y*w]; + for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i) + { + const rcCompactSpan& s = chf.spans[i]; + const unsigned char area = chf.areas[i]; + + int nc = 0; + for (int dir = 0; dir < 4; ++dir) + { + if (rcGetCon(s, dir) != RC_NOT_CONNECTED) + { + const int ax = x + rcGetDirOffsetX(dir); + const int ay = y + rcGetDirOffsetY(dir); + const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir); + if (area == chf.areas[ai]) + nc++; + } + } + if (nc != 4) + src[i] = 0; + } + } + } + + + // Pass 1 + for (int y = 0; y < h; ++y) + { + for (int x = 0; x < w; ++x) + { + const rcCompactCell& c = chf.cells[x+y*w]; + for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i) + { + const rcCompactSpan& s = chf.spans[i]; + + if (rcGetCon(s, 0) != RC_NOT_CONNECTED) + { + // (-1,0) + const int ax = x + rcGetDirOffsetX(0); + const int ay = y + rcGetDirOffsetY(0); + const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 0); + const rcCompactSpan& as = chf.spans[ai]; + if (src[ai]+2 < src[i]) + src[i] = src[ai]+2; + + // (-1,-1) + if (rcGetCon(as, 3) != RC_NOT_CONNECTED) + { + const int aax = ax + rcGetDirOffsetX(3); + const int aay = ay + rcGetDirOffsetY(3); + const int aai = (int)chf.cells[aax+aay*w].index + rcGetCon(as, 3); + if (src[aai]+3 < src[i]) + src[i] = src[aai]+3; + } + } + if (rcGetCon(s, 3) != RC_NOT_CONNECTED) + { + // (0,-1) + const int ax = x + rcGetDirOffsetX(3); + const int ay = y + rcGetDirOffsetY(3); + const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 3); + const rcCompactSpan& as = chf.spans[ai]; + if (src[ai]+2 < src[i]) + src[i] = src[ai]+2; + + // (1,-1) + if (rcGetCon(as, 2) != RC_NOT_CONNECTED) + { + const int aax = ax + rcGetDirOffsetX(2); + const int aay = ay + rcGetDirOffsetY(2); + const int aai = (int)chf.cells[aax+aay*w].index + rcGetCon(as, 2); + if (src[aai]+3 < src[i]) + src[i] = src[aai]+3; + } + } + } + } + } + + // Pass 2 + for (int y = h-1; y >= 0; --y) + { + for (int x = w-1; x >= 0; --x) + { + const rcCompactCell& c = chf.cells[x+y*w]; + for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i) + { + const rcCompactSpan& s = chf.spans[i]; + + if (rcGetCon(s, 2) != RC_NOT_CONNECTED) + { + // (1,0) + const int ax = x + rcGetDirOffsetX(2); + const int ay = y + rcGetDirOffsetY(2); + const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 2); + const rcCompactSpan& as = chf.spans[ai]; + if (src[ai]+2 < src[i]) + src[i] = src[ai]+2; + + // (1,1) + if (rcGetCon(as, 1) != RC_NOT_CONNECTED) + { + const int aax = ax + rcGetDirOffsetX(1); + const int aay = ay + rcGetDirOffsetY(1); + const int aai = (int)chf.cells[aax+aay*w].index + rcGetCon(as, 1); + if (src[aai]+3 < src[i]) + src[i] = src[aai]+3; + } + } + if (rcGetCon(s, 1) != RC_NOT_CONNECTED) + { + // (0,1) + const int ax = x + rcGetDirOffsetX(1); + const int ay = y + rcGetDirOffsetY(1); + const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 1); + const rcCompactSpan& as = chf.spans[ai]; + if (src[ai]+2 < src[i]) + src[i] = src[ai]+2; + + // (-1,1) + if (rcGetCon(as, 0) != RC_NOT_CONNECTED) + { + const int aax = ax + rcGetDirOffsetX(0); + const int aay = ay + rcGetDirOffsetY(0); + const int aai = (int)chf.cells[aax+aay*w].index + rcGetCon(as, 0); + if (src[aai]+3 < src[i]) + src[i] = src[aai]+3; + } + } + } + } + } + + maxDist = 0; + for (int i = 0; i < chf.spanCount; ++i) + maxDist = rcMax(src[i], maxDist); + +} + +static unsigned short* boxBlur(rcCompactHeightfield& chf, int thr, + unsigned short* src, unsigned short* dst) +{ + const int w = chf.width; + const int h = chf.height; + + thr *= 2; + + for (int y = 0; y < h; ++y) + { + for (int x = 0; x < w; ++x) + { + const rcCompactCell& c = chf.cells[x+y*w]; + for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i) + { + const rcCompactSpan& s = chf.spans[i]; + const unsigned short cd = src[i]; + if (cd <= thr) + { + dst[i] = cd; + continue; + } + + int d = (int)cd; + for (int dir = 0; dir < 4; ++dir) + { + if (rcGetCon(s, dir) != RC_NOT_CONNECTED) + { + const int ax = x + rcGetDirOffsetX(dir); + const int ay = y + rcGetDirOffsetY(dir); + const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir); + d += (int)src[ai]; + + const rcCompactSpan& as = chf.spans[ai]; + const int dir2 = (dir+1) & 0x3; + if (rcGetCon(as, dir2) != RC_NOT_CONNECTED) + { + const int ax2 = ax + rcGetDirOffsetX(dir2); + const int ay2 = ay + rcGetDirOffsetY(dir2); + const int ai2 = (int)chf.cells[ax2+ay2*w].index + rcGetCon(as, dir2); + d += (int)src[ai2]; + } + else + { + d += cd; + } + } + else + { + d += cd*2; + } + } + dst[i] = (unsigned short)((d+5)/9); + } + } + } + return dst; +} + + +static bool floodRegion(int x, int y, int i, + unsigned short level, unsigned short r, + rcCompactHeightfield& chf, + unsigned short* srcReg, unsigned short* srcDist, + rcTempVector& stack) +{ + const int w = chf.width; + + const unsigned char area = chf.areas[i]; + + // Flood fill mark region. + stack.clear(); + stack.push_back(LevelStackEntry(x, y, i)); + srcReg[i] = r; + srcDist[i] = 0; + + unsigned short lev = level >= 2 ? level-2 : 0; + int count = 0; + + while (stack.size() > 0) + { + LevelStackEntry& back = stack.back(); + int cx = back.x; + int cy = back.y; + int ci = back.index; + stack.pop_back(); + + const rcCompactSpan& cs = chf.spans[ci]; + + // Check if any of the neighbours already have a valid region set. + unsigned short ar = 0; + for (int dir = 0; dir < 4; ++dir) + { + // 8 connected + if (rcGetCon(cs, dir) != RC_NOT_CONNECTED) + { + const int ax = cx + rcGetDirOffsetX(dir); + const int ay = cy + rcGetDirOffsetY(dir); + const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(cs, dir); + if (chf.areas[ai] != area) + continue; + unsigned short nr = srcReg[ai]; + if (nr & RC_BORDER_REG) // Do not take borders into account. + continue; + if (nr != 0 && nr != r) + { + ar = nr; + break; + } + + const rcCompactSpan& as = chf.spans[ai]; + + const int dir2 = (dir+1) & 0x3; + if (rcGetCon(as, dir2) != RC_NOT_CONNECTED) + { + const int ax2 = ax + rcGetDirOffsetX(dir2); + const int ay2 = ay + rcGetDirOffsetY(dir2); + const int ai2 = (int)chf.cells[ax2+ay2*w].index + rcGetCon(as, dir2); + if (chf.areas[ai2] != area) + continue; + unsigned short nr2 = srcReg[ai2]; + if (nr2 != 0 && nr2 != r) + { + ar = nr2; + break; + } + } + } + } + if (ar != 0) + { + srcReg[ci] = 0; + continue; + } + + count++; + + // Expand neighbours. + for (int dir = 0; dir < 4; ++dir) + { + if (rcGetCon(cs, dir) != RC_NOT_CONNECTED) + { + const int ax = cx + rcGetDirOffsetX(dir); + const int ay = cy + rcGetDirOffsetY(dir); + const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(cs, dir); + if (chf.areas[ai] != area) + continue; + if (chf.dist[ai] >= lev && srcReg[ai] == 0) + { + srcReg[ai] = r; + srcDist[ai] = 0; + stack.push_back(LevelStackEntry(ax, ay, ai)); + } + } + } + } + + return count > 0; +} + +// Struct to keep track of entries in the region table that have been changed. +struct DirtyEntry +{ + DirtyEntry(int index_, unsigned short region_, unsigned short distance2_) + : index(index_), region(region_), distance2(distance2_) {} + int index; + unsigned short region; + unsigned short distance2; +}; +static void expandRegions(int maxIter, unsigned short level, + rcCompactHeightfield& chf, + unsigned short* srcReg, unsigned short* srcDist, + rcTempVector& stack, + bool fillStack) +{ + const int w = chf.width; + const int h = chf.height; + + if (fillStack) + { + // Find cells revealed by the raised level. + stack.clear(); + for (int y = 0; y < h; ++y) + { + for (int x = 0; x < w; ++x) + { + const rcCompactCell& c = chf.cells[x+y*w]; + for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i) + { + if (chf.dist[i] >= level && srcReg[i] == 0 && chf.areas[i] != RC_NULL_AREA) + { + stack.push_back(LevelStackEntry(x, y, i)); + } + } + } + } + } + else // use cells in the input stack + { + // mark all cells which already have a region + for (int j=0; j dirtyEntries; + int iter = 0; + while (stack.size() > 0) + { + int failed = 0; + dirtyEntries.clear(); + + for (int j = 0; j < stack.size(); j++) + { + int x = stack[j].x; + int y = stack[j].y; + int i = stack[j].index; + if (i < 0) + { + failed++; + continue; + } + + unsigned short r = srcReg[i]; + unsigned short d2 = 0xffff; + const unsigned char area = chf.areas[i]; + const rcCompactSpan& s = chf.spans[i]; + for (int dir = 0; dir < 4; ++dir) + { + if (rcGetCon(s, dir) == RC_NOT_CONNECTED) continue; + const int ax = x + rcGetDirOffsetX(dir); + const int ay = y + rcGetDirOffsetY(dir); + const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir); + if (chf.areas[ai] != area) continue; + if (srcReg[ai] > 0 && (srcReg[ai] & RC_BORDER_REG) == 0) + { + if ((int)srcDist[ai]+2 < (int)d2) + { + r = srcReg[ai]; + d2 = srcDist[ai]+2; + } + } + } + if (r) + { + stack[j].index = -1; // mark as used + dirtyEntries.push_back(DirtyEntry(i, r, d2)); + } + else + { + failed++; + } + } + + // Copy entries that differ between src and dst to keep them in sync. + for (int i = 0; i < dirtyEntries.size(); i++) { + int idx = dirtyEntries[i].index; + srcReg[idx] = dirtyEntries[i].region; + srcDist[idx] = dirtyEntries[i].distance2; + } + + if (failed == stack.size()) + break; + + if (level > 0) + { + ++iter; + if (iter >= maxIter) + break; + } + } +} + + + +static void sortCellsByLevel(unsigned short startLevel, + rcCompactHeightfield& chf, + const unsigned short* srcReg, + unsigned int nbStacks, rcTempVector* stacks, + unsigned short loglevelsPerStack) // the levels per stack (2 in our case) as a bit shift +{ + const int w = chf.width; + const int h = chf.height; + startLevel = startLevel >> loglevelsPerStack; + + for (unsigned int j=0; j> loglevelsPerStack; + int sId = startLevel - level; + if (sId >= (int)nbStacks) + continue; + if (sId < 0) + sId = 0; + + stacks[sId].push_back(LevelStackEntry(x, y, i)); + } + } + } +} + + +static void appendStacks(const rcTempVector& srcStack, + rcTempVector& dstStack, + const unsigned short* srcReg) +{ + for (int j=0; j connections; + rcTempVector floors; +}; + +static void removeAdjacentNeighbours(rcRegion& reg) +{ + // Remove adjacent duplicates. + for (int i = 0; i < reg.connections.size() && reg.connections.size() > 1; ) + { + int ni = (i+1) % reg.connections.size(); + if (reg.connections[i] == reg.connections[ni]) + { + // Remove duplicate + for (int j = i; j < reg.connections.size()-1; ++j) + reg.connections[j] = reg.connections[j+1]; + reg.connections.pop_back(); + } + else + ++i; + } +} + +static void replaceNeighbour(rcRegion& reg, unsigned short oldId, unsigned short newId) +{ + bool neiChanged = false; + for (int i = 0; i < reg.connections.size(); ++i) + { + if (reg.connections[i] == oldId) + { + reg.connections[i] = newId; + neiChanged = true; + } + } + for (int i = 0; i < reg.floors.size(); ++i) + { + if (reg.floors[i] == oldId) + reg.floors[i] = newId; + } + if (neiChanged) + removeAdjacentNeighbours(reg); +} + +static bool canMergeWithRegion(const rcRegion& rega, const rcRegion& regb) +{ + if (rega.areaType != regb.areaType) + return false; + int n = 0; + for (int i = 0; i < rega.connections.size(); ++i) + { + if (rega.connections[i] == regb.id) + n++; + } + if (n > 1) + return false; + for (int i = 0; i < rega.floors.size(); ++i) + { + if (rega.floors[i] == regb.id) + return false; + } + return true; +} + +static void addUniqueFloorRegion(rcRegion& reg, int n) +{ + for (int i = 0; i < reg.floors.size(); ++i) + if (reg.floors[i] == n) + return; + reg.floors.push_back(n); +} + +static bool mergeRegions(rcRegion& rega, rcRegion& regb) +{ + unsigned short aid = rega.id; + unsigned short bid = regb.id; + + // Duplicate current neighbourhood. + rcTempVector acon; + acon.resize(rega.connections.size()); + for (int i = 0; i < rega.connections.size(); ++i) + acon[i] = rega.connections[i]; + rcTempVector& bcon = regb.connections; + + // Find insertion point on A. + int insa = -1; + for (int i = 0; i < acon.size(); ++i) + { + if (acon[i] == bid) + { + insa = i; + break; + } + } + if (insa == -1) + return false; + + // Find insertion point on B. + int insb = -1; + for (int i = 0; i < bcon.size(); ++i) + { + if (bcon[i] == aid) + { + insb = i; + break; + } + } + if (insb == -1) + return false; + + // Merge neighbours. + rega.connections.clear(); + for (int i = 0, ni = static_cast(acon.size()); i < ni-1; ++i) + { + rega.connections.push_back(acon[(insa+1+i) % ni]); + } + + for (int i = 0, ni = static_cast(bcon.size()); i < ni-1; ++i) + { + rega.connections.push_back(bcon[(insb+1+i) % ni]); + } + + removeAdjacentNeighbours(rega); + + for (int j = 0; j < regb.floors.size(); ++j) + addUniqueFloorRegion(rega, regb.floors[j]); + rega.spanCount += regb.spanCount; + regb.spanCount = 0; + regb.connections.resize(0); + + return true; +} + +static bool isRegionConnectedToBorder(const rcRegion& reg) +{ + // Region is connected to border if + // one of the neighbours is null id. + for (int i = 0; i < reg.connections.size(); ++i) + { + if (reg.connections[i] == 0) + return true; + } + return false; +} + +static bool isSolidEdge(rcCompactHeightfield& chf, const unsigned short* srcReg, + int x, int y, int i, int dir) +{ + const rcCompactSpan& s = chf.spans[i]; + unsigned short r = 0; + if (rcGetCon(s, dir) != RC_NOT_CONNECTED) + { + const int ax = x + rcGetDirOffsetX(dir); + const int ay = y + rcGetDirOffsetY(dir); + const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(s, dir); + r = srcReg[ai]; + } + if (r == srcReg[i]) + return false; + return true; +} + +static void walkContour(int x, int y, int i, int dir, + rcCompactHeightfield& chf, + const unsigned short* srcReg, + rcTempVector& cont) +{ + int startDir = dir; + int starti = i; + + const rcCompactSpan& ss = chf.spans[i]; + unsigned short curReg = 0; + if (rcGetCon(ss, dir) != RC_NOT_CONNECTED) + { + const int ax = x + rcGetDirOffsetX(dir); + const int ay = y + rcGetDirOffsetY(dir); + const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(ss, dir); + curReg = srcReg[ai]; + } + cont.push_back(curReg); + + int iter = 0; + while (++iter < 40000) + { + const rcCompactSpan& s = chf.spans[i]; + + if (isSolidEdge(chf, srcReg, x, y, i, dir)) + { + // Choose the edge corner + unsigned short r = 0; + if (rcGetCon(s, dir) != RC_NOT_CONNECTED) + { + const int ax = x + rcGetDirOffsetX(dir); + const int ay = y + rcGetDirOffsetY(dir); + const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(s, dir); + r = srcReg[ai]; + } + if (r != curReg) + { + curReg = r; + cont.push_back(curReg); + } + + dir = (dir+1) & 0x3; // Rotate CW + } + else + { + int ni = -1; + const int nx = x + rcGetDirOffsetX(dir); + const int ny = y + rcGetDirOffsetY(dir); + if (rcGetCon(s, dir) != RC_NOT_CONNECTED) + { + const rcCompactCell& nc = chf.cells[nx+ny*chf.width]; + ni = (int)nc.index + rcGetCon(s, dir); + } + if (ni == -1) + { + // Should not happen. + return; + } + x = nx; + y = ny; + i = ni; + dir = (dir+3) & 0x3; // Rotate CCW + } + + if (starti == i && startDir == dir) + { + break; + } + } + + // Remove adjacent duplicates. + if (cont.size() > 1) + { + for (int j = 0; j < cont.size(); ) + { + int nj = (j+1) % cont.size(); + if (cont[j] == cont[nj]) + { + for (int k = j; k < cont.size()-1; ++k) + cont[k] = cont[k+1]; + cont.pop_back(); + } + else + ++j; + } + } +} + + +static bool mergeAndFilterRegions(rcContext* ctx, int minRegionArea, int mergeRegionSize, + unsigned short& maxRegionId, + rcCompactHeightfield& chf, + unsigned short* srcReg, rcTempVector& overlaps) +{ + const int w = chf.width; + const int h = chf.height; + + const int nreg = maxRegionId+1; + rcTempVector regions; + if (!regions.reserve(nreg)) { + ctx->log(RC_LOG_ERROR, "mergeAndFilterRegions: Out of memory 'regions' (%d).", nreg); + return false; + } + + // Construct regions + for (int i = 0; i < nreg; ++i) + regions.push_back(rcRegion((unsigned short) i)); + + // Find edge of a region and find connections around the contour. + for (int y = 0; y < h; ++y) + { + for (int x = 0; x < w; ++x) + { + const rcCompactCell& c = chf.cells[x+y*w]; + for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i) + { + unsigned short r = srcReg[i]; + if (r == 0 || r >= nreg) + continue; + + rcRegion& reg = regions[r]; + reg.spanCount++; + + // Update floors. + for (int j = (int)c.index; j < ni; ++j) + { + if (i == j) continue; + unsigned short floorId = srcReg[j]; + if (floorId == 0 || floorId >= nreg) + continue; + if (floorId == r) + reg.overlap = true; + addUniqueFloorRegion(reg, floorId); + } + + // Have found contour + if (reg.connections.size() > 0) + continue; + + reg.areaType = chf.areas[i]; + + // Check if this cell is next to a border. + int ndir = -1; + for (int dir = 0; dir < 4; ++dir) + { + if (isSolidEdge(chf, srcReg, x, y, i, dir)) + { + ndir = dir; + break; + } + } + + if (ndir != -1) + { + // The cell is at border. + // Walk around the contour to find all the neighbours. + walkContour(x, y, i, ndir, chf, srcReg, reg.connections); + } + } + } + } + + // Remove too small regions. + rcTempVector stack(32); + rcTempVector trace(32); + for (int i = 0; i < nreg; ++i) + { + rcRegion& reg = regions[i]; + if (reg.id == 0 || (reg.id & RC_BORDER_REG)) + continue; + if (reg.spanCount == 0) + continue; + if (reg.visited) + continue; + + // Count the total size of all the connected regions. + // Also keep track of the regions connects to a tile border. + bool connectsToBorder = false; + int spanCount = 0; + stack.clear(); + trace.clear(); + + reg.visited = true; + stack.push_back(i); + + while (stack.size()) + { + // Pop + int ri = stack.back(); stack.pop_back(); + + rcRegion& creg = regions[ri]; + + spanCount += creg.spanCount; + trace.push_back(ri); + + for (int j = 0; j < creg.connections.size(); ++j) + { + if (creg.connections[j] & RC_BORDER_REG) + { + connectsToBorder = true; + continue; + } + rcRegion& neireg = regions[creg.connections[j]]; + if (neireg.visited) + continue; + if (neireg.id == 0 || (neireg.id & RC_BORDER_REG)) + continue; + // Visit + stack.push_back(neireg.id); + neireg.visited = true; + } + } + + // If the accumulated regions size is too small, remove it. + // Do not remove areas which connect to tile borders + // as their size cannot be estimated correctly and removing them + // can potentially remove necessary areas. + if (spanCount < minRegionArea && !connectsToBorder) + { + // Kill all visited regions. + for (int j = 0; j < trace.size(); ++j) + { + regions[trace[j]].spanCount = 0; + regions[trace[j]].id = 0; + } + } + } + + // Merge too small regions to neighbour regions. + int mergeCount = 0 ; + do + { + mergeCount = 0; + for (int i = 0; i < nreg; ++i) + { + rcRegion& reg = regions[i]; + if (reg.id == 0 || (reg.id & RC_BORDER_REG)) + continue; + if (reg.overlap) + continue; + if (reg.spanCount == 0) + continue; + + // Check to see if the region should be merged. + if (reg.spanCount > mergeRegionSize && isRegionConnectedToBorder(reg)) + continue; + + // Small region with more than 1 connection. + // Or region which is not connected to a border at all. + // Find smallest neighbour region that connects to this one. + int smallest = 0xfffffff; + unsigned short mergeId = reg.id; + for (int j = 0; j < reg.connections.size(); ++j) + { + if (reg.connections[j] & RC_BORDER_REG) continue; + rcRegion& mreg = regions[reg.connections[j]]; + if (mreg.id == 0 || (mreg.id & RC_BORDER_REG) || mreg.overlap) continue; + if (mreg.spanCount < smallest && + canMergeWithRegion(reg, mreg) && + canMergeWithRegion(mreg, reg)) + { + smallest = mreg.spanCount; + mergeId = mreg.id; + } + } + // Found new id. + if (mergeId != reg.id) + { + unsigned short oldId = reg.id; + rcRegion& target = regions[mergeId]; + + // Merge neighbours. + if (mergeRegions(target, reg)) + { + // Fixup regions pointing to current region. + for (int j = 0; j < nreg; ++j) + { + if (regions[j].id == 0 || (regions[j].id & RC_BORDER_REG)) continue; + // If another region was already merged into current region + // change the nid of the previous region too. + if (regions[j].id == oldId) + regions[j].id = mergeId; + // Replace the current region with the new one if the + // current regions is neighbour. + replaceNeighbour(regions[j], oldId, mergeId); + } + mergeCount++; + } + } + } + } + while (mergeCount > 0); + + // Compress region Ids. + for (int i = 0; i < nreg; ++i) + { + regions[i].remap = false; + if (regions[i].id == 0) continue; // Skip nil regions. + if (regions[i].id & RC_BORDER_REG) continue; // Skip external regions. + regions[i].remap = true; + } + + unsigned short regIdGen = 0; + for (int i = 0; i < nreg; ++i) + { + if (!regions[i].remap) + continue; + unsigned short oldId = regions[i].id; + unsigned short newId = ++regIdGen; + for (int j = i; j < nreg; ++j) + { + if (regions[j].id == oldId) + { + regions[j].id = newId; + regions[j].remap = false; + } + } + } + maxRegionId = regIdGen; + + // Remap regions. + for (int i = 0; i < chf.spanCount; ++i) + { + if ((srcReg[i] & RC_BORDER_REG) == 0) + srcReg[i] = regions[srcReg[i]].id; + } + + // Return regions that we found to be overlapping. + for (int i = 0; i < nreg; ++i) + if (regions[i].overlap) + overlaps.push_back(regions[i].id); + + return true; +} + + +static void addUniqueConnection(rcRegion& reg, int n) +{ + for (int i = 0; i < reg.connections.size(); ++i) + if (reg.connections[i] == n) + return; + reg.connections.push_back(n); +} + +static bool mergeAndFilterLayerRegions(rcContext* ctx, int minRegionArea, + unsigned short& maxRegionId, + rcCompactHeightfield& chf, + unsigned short* srcReg) +{ + const int w = chf.width; + const int h = chf.height; + + const int nreg = maxRegionId+1; + rcTempVector regions; + + // Construct regions + if (!regions.reserve(nreg)) { + ctx->log(RC_LOG_ERROR, "mergeAndFilterLayerRegions: Out of memory 'regions' (%d).", nreg); + return false; + } + for (int i = 0; i < nreg; ++i) + regions.push_back(rcRegion((unsigned short) i)); + + // Find region neighbours and overlapping regions. + rcTempVector lregs(32); + for (int y = 0; y < h; ++y) + { + for (int x = 0; x < w; ++x) + { + const rcCompactCell& c = chf.cells[x+y*w]; + + lregs.clear(); + + for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i) + { + const rcCompactSpan& s = chf.spans[i]; + const unsigned char area = chf.areas[i]; + const unsigned short ri = srcReg[i]; + if (ri == 0 || ri >= nreg) continue; + rcRegion& reg = regions[ri]; + + reg.spanCount++; + reg.areaType = area; + + reg.ymin = rcMin(reg.ymin, s.y); + reg.ymax = rcMax(reg.ymax, s.y); + + // Collect all region layers. + lregs.push_back(ri); + + // Update neighbours + for (int dir = 0; dir < 4; ++dir) + { + if (rcGetCon(s, dir) != RC_NOT_CONNECTED) + { + const int ax = x + rcGetDirOffsetX(dir); + const int ay = y + rcGetDirOffsetY(dir); + const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir); + const unsigned short rai = srcReg[ai]; + if (rai > 0 && rai < nreg && rai != ri) + addUniqueConnection(reg, rai); + if (rai & RC_BORDER_REG) + reg.connectsToBorder = true; + } + } + + } + + // Update overlapping regions. + for (int i = 0; i < lregs.size()-1; ++i) + { + for (int j = i+1; j < lregs.size(); ++j) + { + if (lregs[i] != lregs[j]) + { + rcRegion& ri = regions[lregs[i]]; + rcRegion& rj = regions[lregs[j]]; + addUniqueFloorRegion(ri, lregs[j]); + addUniqueFloorRegion(rj, lregs[i]); + } + } + } + + } + } + + // Create 2D layers from regions. + unsigned short layerId = 1; + + for (int i = 0; i < nreg; ++i) + regions[i].id = 0; + + // Merge montone regions to create non-overlapping areas. + rcTempVector stack(32); + for (int i = 1; i < nreg; ++i) + { + rcRegion& root = regions[i]; + // Skip already visited. + if (root.id != 0) + continue; + + // Start search. + root.id = layerId; + + stack.clear(); + stack.push_back(i); + + while (stack.size() > 0) + { + // Pop front + rcRegion& reg = regions[stack[0]]; + for (int j = 0; j < stack.size()-1; ++j) + stack[j] = stack[j+1]; + stack.resize(stack.size()-1); + + const int ncons = (int)reg.connections.size(); + for (int j = 0; j < ncons; ++j) + { + const int nei = reg.connections[j]; + rcRegion& regn = regions[nei]; + // Skip already visited. + if (regn.id != 0) + continue; + // Skip if different area type, do not connect regions with different area type. + if (reg.areaType != regn.areaType) + continue; + // Skip if the neighbour is overlapping root region. + bool overlap = false; + for (int k = 0; k < root.floors.size(); k++) + { + if (root.floors[k] == nei) + { + overlap = true; + break; + } + } + if (overlap) + continue; + + // Deepen + stack.push_back(nei); + + // Mark layer id + regn.id = layerId; + // Merge current layers to root. + for (int k = 0; k < regn.floors.size(); ++k) + addUniqueFloorRegion(root, regn.floors[k]); + root.ymin = rcMin(root.ymin, regn.ymin); + root.ymax = rcMax(root.ymax, regn.ymax); + root.spanCount += regn.spanCount; + regn.spanCount = 0; + root.connectsToBorder = root.connectsToBorder || regn.connectsToBorder; + } + } + + layerId++; + } + + // Remove small regions + for (int i = 0; i < nreg; ++i) + { + if (regions[i].spanCount > 0 && regions[i].spanCount < minRegionArea && !regions[i].connectsToBorder) + { + unsigned short reg = regions[i].id; + for (int j = 0; j < nreg; ++j) + if (regions[j].id == reg) + regions[j].id = 0; + } + } + + // Compress region Ids. + for (int i = 0; i < nreg; ++i) + { + regions[i].remap = false; + if (regions[i].id == 0) continue; // Skip nil regions. + if (regions[i].id & RC_BORDER_REG) continue; // Skip external regions. + regions[i].remap = true; + } + + unsigned short regIdGen = 0; + for (int i = 0; i < nreg; ++i) + { + if (!regions[i].remap) + continue; + unsigned short oldId = regions[i].id; + unsigned short newId = ++regIdGen; + for (int j = i; j < nreg; ++j) + { + if (regions[j].id == oldId) + { + regions[j].id = newId; + regions[j].remap = false; + } + } + } + maxRegionId = regIdGen; + + // Remap regions. + for (int i = 0; i < chf.spanCount; ++i) + { + if ((srcReg[i] & RC_BORDER_REG) == 0) + srcReg[i] = regions[srcReg[i]].id; + } + + return true; +} + + + +/// @par +/// +/// This is usually the second to the last step in creating a fully built +/// compact heightfield. This step is required before regions are built +/// using #rcBuildRegions or #rcBuildRegionsMonotone. +/// +/// After this step, the distance data is available via the rcCompactHeightfield::maxDistance +/// and rcCompactHeightfield::dist fields. +/// +/// @see rcCompactHeightfield, rcBuildRegions, rcBuildRegionsMonotone +bool rcBuildDistanceField(rcContext* ctx, rcCompactHeightfield& chf) +{ + rcAssert(ctx); + + rcScopedTimer timer(ctx, RC_TIMER_BUILD_DISTANCEFIELD); + + if (chf.dist) + { + rcFree(chf.dist); + chf.dist = 0; + } + + unsigned short* src = (unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount, RC_ALLOC_TEMP); + if (!src) + { + ctx->log(RC_LOG_ERROR, "rcBuildDistanceField: Out of memory 'src' (%d).", chf.spanCount); + return false; + } + unsigned short* dst = (unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount, RC_ALLOC_TEMP); + if (!dst) + { + ctx->log(RC_LOG_ERROR, "rcBuildDistanceField: Out of memory 'dst' (%d).", chf.spanCount); + rcFree(src); + return false; + } + + unsigned short maxDist = 0; + + { + rcScopedTimer timerDist(ctx, RC_TIMER_BUILD_DISTANCEFIELD_DIST); + + calculateDistanceField(chf, src, maxDist); + chf.maxDistance = maxDist; + } + + { + rcScopedTimer timerBlur(ctx, RC_TIMER_BUILD_DISTANCEFIELD_BLUR); + + // Blur + if (boxBlur(chf, 1, src, dst) != src) + rcSwap(src, dst); + + // Store distance. + chf.dist = src; + } + + rcFree(dst); + + return true; +} + +static void paintRectRegion(int minx, int maxx, int miny, int maxy, unsigned short regId, + rcCompactHeightfield& chf, unsigned short* srcReg) +{ + const int w = chf.width; + for (int y = miny; y < maxy; ++y) + { + for (int x = minx; x < maxx; ++x) + { + const rcCompactCell& c = chf.cells[x+y*w]; + for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i) + { + if (chf.areas[i] != RC_NULL_AREA) + srcReg[i] = regId; + } + } + } +} + + +static const unsigned short RC_NULL_NEI = 0xffff; + +struct rcSweepSpan +{ + unsigned short rid; // row id + unsigned short id; // region id + unsigned short ns; // number samples + unsigned short nei; // neighbour id +}; + +/// @par +/// +/// Non-null regions will consist of connected, non-overlapping walkable spans that form a single contour. +/// Contours will form simple polygons. +/// +/// If multiple regions form an area that is smaller than @p minRegionArea, then all spans will be +/// re-assigned to the zero (null) region. +/// +/// Partitioning can result in smaller than necessary regions. @p mergeRegionArea helps +/// reduce unnecessarily small regions. +/// +/// See the #rcConfig documentation for more information on the configuration parameters. +/// +/// The region data will be available via the rcCompactHeightfield::maxRegions +/// and rcCompactSpan::reg fields. +/// +/// @warning The distance field must be created using #rcBuildDistanceField before attempting to build regions. +/// +/// @see rcCompactHeightfield, rcCompactSpan, rcBuildDistanceField, rcBuildRegionsMonotone, rcConfig +bool rcBuildRegionsMonotone(rcContext* ctx, rcCompactHeightfield& chf, + const int borderSize, const int minRegionArea, const int mergeRegionArea) +{ + rcAssert(ctx); + + rcScopedTimer timer(ctx, RC_TIMER_BUILD_REGIONS); + + const int w = chf.width; + const int h = chf.height; + unsigned short id = 1; + + rcScopedDelete srcReg((unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount, RC_ALLOC_TEMP)); + if (!srcReg) + { + ctx->log(RC_LOG_ERROR, "rcBuildRegionsMonotone: Out of memory 'src' (%d).", chf.spanCount); + return false; + } + memset(srcReg,0,sizeof(unsigned short)*chf.spanCount); + + const int nsweeps = rcMax(chf.width,chf.height); + rcScopedDelete sweeps((rcSweepSpan*)rcAlloc(sizeof(rcSweepSpan)*nsweeps, RC_ALLOC_TEMP)); + if (!sweeps) + { + ctx->log(RC_LOG_ERROR, "rcBuildRegionsMonotone: Out of memory 'sweeps' (%d).", nsweeps); + return false; + } + + + // Mark border regions. + if (borderSize > 0) + { + // Make sure border will not overflow. + const int bw = rcMin(w, borderSize); + const int bh = rcMin(h, borderSize); + // Paint regions + paintRectRegion(0, bw, 0, h, id|RC_BORDER_REG, chf, srcReg); id++; + paintRectRegion(w-bw, w, 0, h, id|RC_BORDER_REG, chf, srcReg); id++; + paintRectRegion(0, w, 0, bh, id|RC_BORDER_REG, chf, srcReg); id++; + paintRectRegion(0, w, h-bh, h, id|RC_BORDER_REG, chf, srcReg); id++; + } + + chf.borderSize = borderSize; + + rcTempVector prev(256); + + // Sweep one line at a time. + for (int y = borderSize; y < h-borderSize; ++y) + { + // Collect spans from this row. + prev.resize(id+1); + memset(&prev[0],0,sizeof(int)*id); + unsigned short rid = 1; + + for (int x = borderSize; x < w-borderSize; ++x) + { + const rcCompactCell& c = chf.cells[x+y*w]; + + for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i) + { + const rcCompactSpan& s = chf.spans[i]; + if (chf.areas[i] == RC_NULL_AREA) continue; + + // -x + unsigned short previd = 0; + if (rcGetCon(s, 0) != RC_NOT_CONNECTED) + { + const int ax = x + rcGetDirOffsetX(0); + const int ay = y + rcGetDirOffsetY(0); + const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 0); + if ((srcReg[ai] & RC_BORDER_REG) == 0 && chf.areas[i] == chf.areas[ai]) + previd = srcReg[ai]; + } + + if (!previd) + { + previd = rid++; + sweeps[previd].rid = previd; + sweeps[previd].ns = 0; + sweeps[previd].nei = 0; + } + + // -y + if (rcGetCon(s,3) != RC_NOT_CONNECTED) + { + const int ax = x + rcGetDirOffsetX(3); + const int ay = y + rcGetDirOffsetY(3); + const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 3); + if (srcReg[ai] && (srcReg[ai] & RC_BORDER_REG) == 0 && chf.areas[i] == chf.areas[ai]) + { + unsigned short nr = srcReg[ai]; + if (!sweeps[previd].nei || sweeps[previd].nei == nr) + { + sweeps[previd].nei = nr; + sweeps[previd].ns++; + prev[nr]++; + } + else + { + sweeps[previd].nei = RC_NULL_NEI; + } + } + } + + srcReg[i] = previd; + } + } + + // Create unique ID. + for (int i = 1; i < rid; ++i) + { + if (sweeps[i].nei != RC_NULL_NEI && sweeps[i].nei != 0 && + prev[sweeps[i].nei] == (int)sweeps[i].ns) + { + sweeps[i].id = sweeps[i].nei; + } + else + { + sweeps[i].id = id++; + } + } + + // Remap IDs + for (int x = borderSize; x < w-borderSize; ++x) + { + const rcCompactCell& c = chf.cells[x+y*w]; + + for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i) + { + if (srcReg[i] > 0 && srcReg[i] < rid) + srcReg[i] = sweeps[srcReg[i]].id; + } + } + } + + + { + rcScopedTimer timerFilter(ctx, RC_TIMER_BUILD_REGIONS_FILTER); + + // Merge regions and filter out small regions. + rcTempVector overlaps; + chf.maxRegions = id; + if (!mergeAndFilterRegions(ctx, minRegionArea, mergeRegionArea, chf.maxRegions, chf, srcReg, overlaps)) + return false; + + // Monotone partitioning does not generate overlapping regions. + } + + // Store the result out. + for (int i = 0; i < chf.spanCount; ++i) + chf.spans[i].reg = srcReg[i]; + + return true; +} + +/// @par +/// +/// Non-null regions will consist of connected, non-overlapping walkable spans that form a single contour. +/// Contours will form simple polygons. +/// +/// If multiple regions form an area that is smaller than @p minRegionArea, then all spans will be +/// re-assigned to the zero (null) region. +/// +/// Watershed partitioning can result in smaller than necessary regions, especially in diagonal corridors. +/// @p mergeRegionArea helps reduce unnecessarily small regions. +/// +/// See the #rcConfig documentation for more information on the configuration parameters. +/// +/// The region data will be available via the rcCompactHeightfield::maxRegions +/// and rcCompactSpan::reg fields. +/// +/// @warning The distance field must be created using #rcBuildDistanceField before attempting to build regions. +/// +/// @see rcCompactHeightfield, rcCompactSpan, rcBuildDistanceField, rcBuildRegionsMonotone, rcConfig +bool rcBuildRegions(rcContext* ctx, rcCompactHeightfield& chf, + const int borderSize, const int minRegionArea, const int mergeRegionArea) +{ + rcAssert(ctx); + + rcScopedTimer timer(ctx, RC_TIMER_BUILD_REGIONS); + + const int w = chf.width; + const int h = chf.height; + + rcScopedDelete buf((unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount*2, RC_ALLOC_TEMP)); + if (!buf) + { + ctx->log(RC_LOG_ERROR, "rcBuildRegions: Out of memory 'tmp' (%d).", chf.spanCount*4); + return false; + } + + ctx->startTimer(RC_TIMER_BUILD_REGIONS_WATERSHED); + + const int LOG_NB_STACKS = 3; + const int NB_STACKS = 1 << LOG_NB_STACKS; + rcTempVector lvlStacks[NB_STACKS]; + for (int i=0; i stack; + stack.reserve(256); + + unsigned short* srcReg = buf; + unsigned short* srcDist = buf+chf.spanCount; + + memset(srcReg, 0, sizeof(unsigned short)*chf.spanCount); + memset(srcDist, 0, sizeof(unsigned short)*chf.spanCount); + + unsigned short regionId = 1; + unsigned short level = (chf.maxDistance+1) & ~1; + + // TODO: Figure better formula, expandIters defines how much the + // watershed "overflows" and simplifies the regions. Tying it to + // agent radius was usually good indication how greedy it could be. +// const int expandIters = 4 + walkableRadius * 2; + const int expandIters = 8; + + if (borderSize > 0) + { + // Make sure border will not overflow. + const int bw = rcMin(w, borderSize); + const int bh = rcMin(h, borderSize); + + // Paint regions + paintRectRegion(0, bw, 0, h, regionId|RC_BORDER_REG, chf, srcReg); regionId++; + paintRectRegion(w-bw, w, 0, h, regionId|RC_BORDER_REG, chf, srcReg); regionId++; + paintRectRegion(0, w, 0, bh, regionId|RC_BORDER_REG, chf, srcReg); regionId++; + paintRectRegion(0, w, h-bh, h, regionId|RC_BORDER_REG, chf, srcReg); regionId++; + } + + chf.borderSize = borderSize; + + int sId = -1; + while (level > 0) + { + level = level >= 2 ? level-2 : 0; + sId = (sId+1) & (NB_STACKS-1); + +// ctx->startTimer(RC_TIMER_DIVIDE_TO_LEVELS); + + if (sId == 0) + sortCellsByLevel(level, chf, srcReg, NB_STACKS, lvlStacks, 1); + else + appendStacks(lvlStacks[sId-1], lvlStacks[sId], srcReg); // copy left overs from last level + +// ctx->stopTimer(RC_TIMER_DIVIDE_TO_LEVELS); + + { + rcScopedTimer timerExpand(ctx, RC_TIMER_BUILD_REGIONS_EXPAND); + + // Expand current regions until no empty connected cells found. + expandRegions(expandIters, level, chf, srcReg, srcDist, lvlStacks[sId], false); + } + + { + rcScopedTimer timerFloor(ctx, RC_TIMER_BUILD_REGIONS_FLOOD); + + // Mark new regions with IDs. + for (int j = 0; j= 0 && srcReg[i] == 0) + { + if (floodRegion(x, y, i, level, regionId, chf, srcReg, srcDist, stack)) + { + if (regionId == 0xFFFF) + { + ctx->log(RC_LOG_ERROR, "rcBuildRegions: Region ID overflow"); + return false; + } + + regionId++; + } + } + } + } + } + + // Expand current regions until no empty connected cells found. + expandRegions(expandIters*8, 0, chf, srcReg, srcDist, stack, true); + + ctx->stopTimer(RC_TIMER_BUILD_REGIONS_WATERSHED); + + { + rcScopedTimer timerFilter(ctx, RC_TIMER_BUILD_REGIONS_FILTER); + + // Merge regions and filter out small regions. + rcTempVector overlaps; + chf.maxRegions = regionId; + if (!mergeAndFilterRegions(ctx, minRegionArea, mergeRegionArea, chf.maxRegions, chf, srcReg, overlaps)) + return false; + + // If overlapping regions were found during merging, split those regions. + if (overlaps.size() > 0) + { + ctx->log(RC_LOG_ERROR, "rcBuildRegions: %d overlapping regions.", overlaps.size()); + } + } + + // Write the result out. + for (int i = 0; i < chf.spanCount; ++i) + chf.spans[i].reg = srcReg[i]; + + return true; +} + + +bool rcBuildLayerRegions(rcContext* ctx, rcCompactHeightfield& chf, + const int borderSize, const int minRegionArea) +{ + rcAssert(ctx); + + rcScopedTimer timer(ctx, RC_TIMER_BUILD_REGIONS); + + const int w = chf.width; + const int h = chf.height; + unsigned short id = 1; + + rcScopedDelete srcReg((unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount, RC_ALLOC_TEMP)); + if (!srcReg) + { + ctx->log(RC_LOG_ERROR, "rcBuildLayerRegions: Out of memory 'src' (%d).", chf.spanCount); + return false; + } + memset(srcReg,0,sizeof(unsigned short)*chf.spanCount); + + const int nsweeps = rcMax(chf.width,chf.height); + rcScopedDelete sweeps((rcSweepSpan*)rcAlloc(sizeof(rcSweepSpan)*nsweeps, RC_ALLOC_TEMP)); + if (!sweeps) + { + ctx->log(RC_LOG_ERROR, "rcBuildLayerRegions: Out of memory 'sweeps' (%d).", nsweeps); + return false; + } + + + // Mark border regions. + if (borderSize > 0) + { + // Make sure border will not overflow. + const int bw = rcMin(w, borderSize); + const int bh = rcMin(h, borderSize); + // Paint regions + paintRectRegion(0, bw, 0, h, id|RC_BORDER_REG, chf, srcReg); id++; + paintRectRegion(w-bw, w, 0, h, id|RC_BORDER_REG, chf, srcReg); id++; + paintRectRegion(0, w, 0, bh, id|RC_BORDER_REG, chf, srcReg); id++; + paintRectRegion(0, w, h-bh, h, id|RC_BORDER_REG, chf, srcReg); id++; + } + + chf.borderSize = borderSize; + + rcTempVector prev(256); + + // Sweep one line at a time. + for (int y = borderSize; y < h-borderSize; ++y) + { + // Collect spans from this row. + prev.resize(id+1); + memset(&prev[0],0,sizeof(int)*id); + unsigned short rid = 1; + + for (int x = borderSize; x < w-borderSize; ++x) + { + const rcCompactCell& c = chf.cells[x+y*w]; + + for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i) + { + const rcCompactSpan& s = chf.spans[i]; + if (chf.areas[i] == RC_NULL_AREA) continue; + + // -x + unsigned short previd = 0; + if (rcGetCon(s, 0) != RC_NOT_CONNECTED) + { + const int ax = x + rcGetDirOffsetX(0); + const int ay = y + rcGetDirOffsetY(0); + const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 0); + if ((srcReg[ai] & RC_BORDER_REG) == 0 && chf.areas[i] == chf.areas[ai]) + previd = srcReg[ai]; + } + + if (!previd) + { + previd = rid++; + sweeps[previd].rid = previd; + sweeps[previd].ns = 0; + sweeps[previd].nei = 0; + } + + // -y + if (rcGetCon(s,3) != RC_NOT_CONNECTED) + { + const int ax = x + rcGetDirOffsetX(3); + const int ay = y + rcGetDirOffsetY(3); + const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 3); + if (srcReg[ai] && (srcReg[ai] & RC_BORDER_REG) == 0 && chf.areas[i] == chf.areas[ai]) + { + unsigned short nr = srcReg[ai]; + if (!sweeps[previd].nei || sweeps[previd].nei == nr) + { + sweeps[previd].nei = nr; + sweeps[previd].ns++; + prev[nr]++; + } + else + { + sweeps[previd].nei = RC_NULL_NEI; + } + } + } + + srcReg[i] = previd; + } + } + + // Create unique ID. + for (int i = 1; i < rid; ++i) + { + if (sweeps[i].nei != RC_NULL_NEI && sweeps[i].nei != 0 && + prev[sweeps[i].nei] == (int)sweeps[i].ns) + { + sweeps[i].id = sweeps[i].nei; + } + else + { + sweeps[i].id = id++; + } + } + + // Remap IDs + for (int x = borderSize; x < w-borderSize; ++x) + { + const rcCompactCell& c = chf.cells[x+y*w]; + + for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i) + { + if (srcReg[i] > 0 && srcReg[i] < rid) + srcReg[i] = sweeps[srcReg[i]].id; + } + } + } + + + { + rcScopedTimer timerFilter(ctx, RC_TIMER_BUILD_REGIONS_FILTER); + + // Merge monotone regions to layers and remove small regions. + chf.maxRegions = id; + if (!mergeAndFilterLayerRegions(ctx, minRegionArea, chf.maxRegions, chf, srcReg)) + return false; + } + + + // Store the result out. + for (int i = 0; i < chf.spanCount; ++i) + chf.spans[i].reg = srcReg[i]; + + return true; +} diff --git a/native/wto-nav/wto_nav_format.h b/native/wto-nav/wto_nav_format.h new file mode 100644 index 0000000..b955b01 --- /dev/null +++ b/native/wto-nav/wto_nav_format.h @@ -0,0 +1,143 @@ +/* + * Shared binary format definitions for WTOffline ground AI navigation data: + * - `.wtogeo`: offline intermediate geometry dump (extractor -> Recast baker) + * - `.wtonav`: runtime navigation pack (baked Detour meshes + covers + tactical grid) + * + * All coordinates are in Dagor world space (left-handed, Y up, metres). + */ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define WTO_GEO_MAGIC "WTOGEO\0\1" +#define WTO_GEO_VERSION 1u + +#define WTO_NAV_MAGIC "WTONAV\0\1" +#define WTO_NAV_VERSION 1u + +#define WTO_NAV_TIER_COUNT 3u +#define WTO_NAV_TIER_NARROW 0u /* Tracked width <= 2.9 m (agentRadius 1.65 m) */ +#define WTO_NAV_TIER_STANDARD 1u /* Tracked width <= 3.6 m (agentRadius 2.05 m) */ +#define WTO_NAV_TIER_WIDE 2u /* Wide/heavy tracked > 3.6 m (agentRadius 2.45 m) */ + +/* Detour polygon Area IDs (0 = RC_NULL_AREA / unwalkable). */ +enum WtoPolyArea { + WTO_AREA_UNWALKABLE = 0, + WTO_AREA_ROAD = 1, + WTO_AREA_BRIDGE = 2, + WTO_AREA_GROUND = 3, + WTO_AREA_ROUGH = 4, + WTO_AREA_FOREST = 5, + WTO_AREA_CRUSHABLE = 6, + WTO_AREA_SHALLOW_WATER = 7, + WTO_AREA_CHOKEPOINT = 8, + WTO_AREA_EXPOSED = 9, + WTO_AREA_DEEP_WATER = 10, + WTO_AREA_NO_GO = 11 +}; + +/* Detour polygon flags for runtime dtQueryFilter filtering. */ +enum WtoPolyFlag { + WTO_FLAG_WALK = 0x01, + WTO_FLAG_SHALLOW_WATER = 0x02, + WTO_FLAG_DEEP_WATER = 0x04, + WTO_FLAG_CHOKEPOINT = 0x08, + WTO_FLAG_BLOCKED = 0x10 +}; + +/* Obstacle classification written into `.wtogeo` by the extractor. */ +enum WtoObstacleClass { + WTO_OBS_HARD_SOLID = 0, /* Buildings, rocks, cliffs, bunkers, concrete walls */ + WTO_OBS_BRIDGE_DECK = 1, /* Walkable bridge decks and ramps */ + WTO_OBS_CRUSHABLE = 2, /* Wooden fences, hedges, low-HP destructibles */ + WTO_OBS_TREE_THICK = 3, /* Thick immovable tree trunks (r >= 0.25 m) */ + WTO_OBS_TREE_THIN = 4 /* Thin tree trunks / saplings (high-cost forest) */ +}; + +/* Baked tank cover classifications. */ +enum WtoCoverKind { + WTO_COVER_FULL = 1, /* Blocks hull + turret (reload, repair, corner peek) */ + WTO_COVER_HULLDOWN = 2 /* Blocks hull, turret clear with forward firing arc */ +}; + +#pragma pack(push, 1) + +/* Intermediate geometry bundle header (`.wtogeo`). */ +typedef struct WtoGeoHeader { + char magic[8]; /* WTO_GEO_MAGIC */ + uint32_t version; /* WTO_GEO_VERSION */ + uint32_t flags; + uint8_t everSha1[20]; /* Built-in SHA-1 from DBLD eVER block */ + float waterLevel; /* Level water_level in metres (-1e6 if none) */ + float boundsMin[2]; /* World XZ crop min (battle area union + margin) */ + float boundsMax[2]; /* World XZ crop max */ + uint32_t hmWidth; /* Cropped heightmap grid columns (X) */ + uint32_t hmHeight; /* Cropped heightmap grid rows (Z) */ + float hmCellSize; /* Metres per heightmap sample */ + float hmOrigin[2]; /* World XZ of cropped sample (0, 0) */ + uint32_t obsVertCount; /* Number of float3 obstacle vertices */ + uint32_t obsTriCount; /* Number of obstacle triangles (uint32[3] + uint8 class) */ +} WtoGeoHeader; + +/* Baked tank cover point (48 bytes). */ +typedef struct WtoCoverPoint { + float pos[3]; /* World XYZ parking position behind cover */ + float coverDir[2]; /* Unit XZ vector pointing FROM pos TOWARD the blocked threat */ + float retreatDir[2]; /* Unit XZ safe reverse/retreat direction away from cover */ + float peekLeft[3]; /* World XYZ left corner peek spot (valid if hasPeekLeft) */ + float peekRight[3]; /* World XYZ right corner peek spot (valid if hasPeekRight) */ + float halfAngleDeg; /* Effective covered half-angle around coverDir */ + float heightM; /* Measured hard-obstacle height above ground at cover */ + float widthM; /* Continuous hard-obstacle width */ + uint8_t kind; /* WtoCoverKind */ + uint8_t hasPeekLeft; /* 1 if peekLeft is valid and navigable */ + uint8_t hasPeekRight; /* 1 if peekRight is valid and navigable */ + uint8_t reserved; +} WtoCoverPoint; + +/* Low-resolution (8 m) tactical grid cell (4 bytes). */ +typedef struct WtoTacticalCell { + uint8_t exposure; /* 0..255: static visibility exposure from enemy side */ + uint8_t clearanceHalfM; /* Distance to nearest hard obstacle in 0.5 m units (0..127.5 m) */ + uint8_t corridorTeam1; /* 0..255: Team 1 replay prior (128 = neutral) */ + uint8_t corridorTeam2; /* 0..255: Team 2 replay prior (128 = neutral) */ +} WtoTacticalCell; + +/* Runtime navigation pack header (`.wtonav`, uncompressed payload header). */ +typedef struct WtoNavHeader { + char magic[8]; /* WTO_NAV_MAGIC */ + uint32_t version; /* WTO_NAV_VERSION */ + uint32_t flags; + uint8_t everSha1[20]; /* Source level eVER SHA-1 fingerprint */ + float bmin[3]; /* World AABB min */ + float bmax[3]; /* World AABB max */ + float waterLevel; + uint32_t tierCount; /* WTO_NAV_TIER_COUNT (3) */ + uint32_t tierOffsets[WTO_NAV_TIER_COUNT]; + uint32_t tierSizes[WTO_NAV_TIER_COUNT]; + uint32_t coverOffset; + uint32_t coverCount; + uint32_t tacOffset; + uint32_t tacCols; + uint32_t tacRows; + float tacCellM; + float tacOrigin[2]; +} WtoNavHeader; + +/* Per-tier Detour blob layout at tierOffsets[t]: + * dtNavMeshParams (exact upstream struct) + * uint32_t tileCount + * repeated tileCount times: + * uint32_t tileDataSize + * uint8_t tileData[tileDataSize] + */ + +#pragma pack(pop) + +#ifdef __cplusplus +} +#endif diff --git a/tools/navgen/bake/bake.cpp b/tools/navgen/bake/bake.cpp new file mode 100644 index 0000000..8c1ef07 --- /dev/null +++ b/tools/navgen/bake/bake.cpp @@ -0,0 +1,1259 @@ +/* + * Offline Recast + Detour + Voxel Cover baker for WTOffline ground AI. + * + * Reads: + * - `.wtogeo` (Dagor world heightmap + classified collision triangles) + * - `.pois.json` (union battle area, team spawns, capture zones) + * Produces: + * - `.wtonav` (3-tier tiled Detour meshes + baked tank covers + 8m tactical grid) + * - `.preview.bin` (compact raster + covers + sample Detour paths for PNG inspection) + */ +#include "wto_nav_format.h" + +#include "Recast.h" +#include "DetourNavMesh.h" +#include "DetourNavMeshBuilder.h" +#include "DetourNavMeshQuery.h" +#include "DetourCommon.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static constexpr float kPi = 3.14159265358979323846f; +static constexpr float kDegToRad = kPi / 180.0f; + +struct Vec3 { float x, y, z; }; + +struct ObsTri { + uint32_t i0, i1, i2; + uint8_t cls; +}; + +struct PoiPt { + std::string name; + float x, y, z, radius; +}; + +struct PoisData { + std::vector t1Spawns; + std::vector t2Spawns; + std::vector caps; +}; + +struct TierSpec { + const char *name; + float agentRadius; + float agentHeight; + float maxSlopeDeg; + float maxClimb; +}; + +static const TierSpec kTiers[WTO_NAV_TIER_COUNT] = { + { "T0_narrow", 1.65f, 2.6f, 30.0f, 0.65f }, + { "T1_standard", 2.05f, 2.6f, 28.0f, 0.65f }, + { "T2_wide", 2.45f, 2.6f, 22.0f, 0.55f }, +}; + +static constexpr float kCellSize = 0.50f; +static constexpr float kCellHeight = 0.25f; +static constexpr int kTileSize = 256; /* 128.0 m per tile */ +static constexpr float kTileWorldSize = kTileSize * kCellSize; +static constexpr float kShallowWaterMaxM = 0.60f; +static constexpr float kShallowWaterMinM = 0.05f; +static constexpr float kRoughSlopeDeg = 18.0f; + +struct GeoData { + WtoGeoHeader hdr{}; + std::vector heights; + std::vector obsVerts; + std::vector obsTris; + float minY = 1e9f; + float maxY = -1e9f; + + float sampleHeight(float wx, float wz) const { + float fx = (wx - hdr.hmOrigin[0]) / hdr.hmCellSize; + float fz = (wz - hdr.hmOrigin[1]) / hdr.hmCellSize; + int x0 = std::clamp((int)std::floor(fx), 0, (int)hdr.hmWidth - 2); + int z0 = std::clamp((int)std::floor(fz), 0, (int)hdr.hmHeight - 2); + float tx = std::clamp(fx - x0, 0.0f, 1.0f); + float tz = std::clamp(fz - z0, 0.0f, 1.0f); + float h00 = heights[(size_t)z0 * hdr.hmWidth + x0]; + float h10 = heights[(size_t)z0 * hdr.hmWidth + x0 + 1]; + float h01 = heights[(size_t)(z0 + 1) * hdr.hmWidth + x0]; + float h11 = heights[(size_t)(z0 + 1) * hdr.hmWidth + x0 + 1]; + float h0 = h00 + (h10 - h00) * tx; + float h1 = h01 + (h11 - h01) * tx; + return h0 + (h1 - h0) * tz; + } +}; + +static bool loadGeo(const std::string &path, GeoData &out) { + std::ifstream in(path, std::ios::binary); + if (!in) return false; + in.read(reinterpret_cast(&out.hdr), sizeof(WtoGeoHeader)); + if (!in || std::memcmp(out.hdr.magic, WTO_GEO_MAGIC, 8) != 0 || out.hdr.version != WTO_GEO_VERSION) { + std::fprintf(stderr, "Invalid .wtogeo header: %s\n", path.c_str()); + return false; + } + size_t hmCount = (size_t)out.hdr.hmWidth * out.hdr.hmHeight; + out.heights.resize(hmCount); + in.read(reinterpret_cast(out.heights.data()), hmCount * sizeof(float)); + out.obsVerts.resize(out.hdr.obsVertCount); + in.read(reinterpret_cast(out.obsVerts.data()), out.hdr.obsVertCount * sizeof(Vec3)); + out.obsTris.resize(out.hdr.obsTriCount); + for (uint32_t i = 0; i < out.hdr.obsTriCount; ++i) { + uint32_t idx[3]; + uint8_t cls = 0; + in.read(reinterpret_cast(idx), sizeof(idx)); + in.read(reinterpret_cast(&cls), 1); + out.obsTris[i] = { idx[0], idx[1], idx[2], cls }; + } + if (!in) return false; + + for (float h : out.heights) { + if (h < out.minY) out.minY = h; + if (h > out.maxY) out.maxY = h; + } + for (const auto &v : out.obsVerts) { + if (std::isfinite(v.y)) { + if (v.y < out.minY) out.minY = v.y; + if (v.y > out.maxY) out.maxY = v.y; + } + } + if (out.hdr.waterLevel > -1e5f) { + out.minY = std::min(out.minY, out.hdr.waterLevel - 2.0f); + out.maxY = std::max(out.maxY, out.hdr.waterLevel + 2.0f); + } + out.minY -= 2.0f; + out.maxY += 6.0f; + return true; +} + +/* Minimal JSON array extractor for `.pois.json` (team1Spawns / team2Spawns / captureZones). */ +static void parsePoiArray(const std::string &json, const std::string &key, std::vector &out) { + std::string needle = "\"" + key + "\""; + size_t pos = json.find(needle); + if (pos == std::string::npos) return; + size_t lb = json.find('[', pos); + if (lb == std::string::npos) return; + int depth = 0; + size_t i = lb; + for (; i < json.size(); ++i) { + if (json[i] == '[') depth++; + else if (json[i] == ']') { depth--; if (depth == 0) break; } + } + std::string slice = json.substr(lb, i - lb + 1); + auto readNum = [](const std::string &obj, const char *field, float def) -> float { + std::string fn = std::string("\"") + field + "\""; + size_t p = obj.find(fn); + if (p == std::string::npos) return def; + p = obj.find(':', p); + if (p == std::string::npos) return def; + return std::strtof(obj.c_str() + p + 1, nullptr); + }; + auto readStr = [](const std::string &obj, const char *field) -> std::string { + std::string fn = std::string("\"") + field + "\""; + size_t p = obj.find(fn); + if (p == std::string::npos) return ""; + p = obj.find(':', p); + size_t q1 = obj.find('"', p); + size_t q2 = (q1 != std::string::npos) ? obj.find('"', q1 + 1) : std::string::npos; + return (q1 != std::string::npos && q2 != std::string::npos) ? obj.substr(q1 + 1, q2 - q1 - 1) : ""; + }; + size_t cur = 0; + while (true) { + size_t ob = slice.find('{', cur); + if (ob == std::string::npos) break; + size_t cb = slice.find('}', ob); + if (cb == std::string::npos) break; + std::string obj = slice.substr(ob, cb - ob + 1); + PoiPt pt; + pt.name = readStr(obj, "name"); + pt.x = readNum(obj, "x", 0.0f); + pt.y = readNum(obj, "y", 0.0f); + pt.z = readNum(obj, "z", 0.0f); + pt.radius = readNum(obj, "radius", 15.0f); + out.push_back(pt); + cur = cb + 1; + } +} + +static bool loadPois(const std::string &path, PoisData &out) { + std::ifstream in(path); + if (!in) return false; + std::string content((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + parsePoiArray(content, "team1Spawns", out.t1Spawns); + parsePoiArray(content, "team2Spawns", out.t2Spawns); + parsePoiArray(content, "captureZones", out.caps); + return true; +} + +static inline float triNormalYRightHanded(const Vec3 &a, const Vec3 &b, const Vec3 &c) { + float e1x = b.x - a.x, e1y = b.y - a.y, e1z = b.z - a.z; + float e2x = c.x - a.x, e2y = c.y - a.y, e2z = c.z - a.z; + float nx = e1y * e2z - e1z * e2y; + float ny = e1z * e2x - e1x * e2z; + float nz = e1x * e2y - e1y * e2x; + float len = std::sqrt(nx * nx + ny * ny + nz * nz); + return len > 1e-6f ? (ny / len) : 0.0f; +} + +/* Query whether a hard solid span exists in rcHeightfield at (wx, wz) intersecting [yLo, yHi]. */ +static bool hfHasSolidInBand(const rcHeightfield &hf, float wx, float wz, float yLo, float yHi, float *outTopY = nullptr) { + int gx = (int)std::floor((wx - hf.bmin[0]) / hf.cs); + int gz = (int)std::floor((wz - hf.bmin[2]) / hf.cs); + if (gx < 0 || gz < 0 || gx >= hf.width || gz >= hf.height) return false; + int sminBand = (int)std::floor((yLo - hf.bmin[1]) / hf.ch); + int smaxBand = (int)std::ceil((yHi - hf.bmin[1]) / hf.ch); + float maxTop = -1e9f; + bool hit = false; + for (const rcSpan *s = hf.spans[gx + gz * hf.width]; s; s = s->next) { + if ((int)s->smax >= sminBand && (int)s->smin <= smaxBand) { + hit = true; + float topY = hf.bmin[1] + s->smax * hf.ch; + if (topY > maxTop) maxTop = topY; + } + } + if (hit && outTopY) *outTopY = maxTop; + return hit; +} + +/* Raycast along XZ inside tile's hard-obstacle heightfield to check occlusion in [yLo, yHi]. */ +static bool hfTraceBand(const rcHeightfield &hardHf, const GeoData &geo, + float ox, float oz, float dx, float dz, + float maxDist, float yLo, float yHi, float *outTopY = nullptr) { + float step = hardHf.cs * 0.85f; + for (float d = 0.6f; d <= maxDist; d += step) { + float px = ox + dx * d; + float pz = oz + dz * d; + float topY = -1e9f; + if (hfHasSolidInBand(hardHf, px, pz, yLo, yHi, &topY)) { + if (outTopY) *outTopY = topY; + return true; + } + /* Terrain ridge / cliff rise above yLo also acts as natural hard earth cover! */ + float gy = geo.sampleHeight(px, pz); + if (gy >= yLo + 0.35f) { + if (outTopY) *outTopY = gy; + return true; + } + } + return false; +} + +struct BuiltTile { + int tx = 0; + int tz = 0; + unsigned char *data = nullptr; + int dataSize = 0; +}; + +struct TileBakeResult { + BuiltTile tile; + std::vector covers; +}; + +static TileBakeResult buildSingleTile( + const GeoData &geo, + const std::vector &triBucket, + const TierSpec &tier, + int tx, int tz, + float mapMinX, float mapMinZ, + bool bakeCovers +) { + TileBakeResult res; + res.tile.tx = tx; + res.tile.tz = tz; + + rcContext ctx(false); + rcConfig cfg{}; + cfg.cs = kCellSize; + cfg.ch = kCellHeight; + cfg.walkableSlopeAngle = tier.maxSlopeDeg; + cfg.walkableHeight = (int)std::ceil(tier.agentHeight / cfg.ch); + cfg.walkableClimb = (int)std::floor(tier.maxClimb / cfg.ch); + cfg.walkableRadius = (int)std::ceil(tier.agentRadius / cfg.cs); + cfg.maxEdgeLen = (int)(24.0f / cfg.cs); + cfg.maxSimplificationError = 1.8f; + cfg.minRegionArea = 32; /* ~8.0 m^2 (smaller than 1 tank footprint) */ + cfg.mergeRegionArea = 400; + cfg.maxVertsPerPoly = 6; + cfg.tileSize = kTileSize; + cfg.borderSize = cfg.walkableRadius + 3; + cfg.width = cfg.tileSize + cfg.borderSize * 2; + cfg.height = cfg.tileSize + cfg.borderSize * 2; + cfg.detailSampleDist = 12.0f * cfg.cs; + cfg.detailSampleMaxError = 2.0f * cfg.ch; + + float borderWorld = cfg.borderSize * cfg.cs; + cfg.bmin[0] = mapMinX + tx * kTileWorldSize - borderWorld; + cfg.bmin[1] = geo.minY; + cfg.bmin[2] = mapMinZ + tz * kTileWorldSize - borderWorld; + cfg.bmax[0] = mapMinX + (tx + 1) * kTileWorldSize + borderWorld; + cfg.bmax[1] = geo.maxY; + cfg.bmax[2] = mapMinZ + (tz + 1) * kTileWorldSize + borderWorld; + + rcHeightfield *solid = rcAllocHeightfield(); + if (!solid || !rcCreateHeightfield(&ctx, *solid, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs, cfg.ch)) { + rcFreeHeightField(solid); + return res; + } + + rcHeightfield *hardHf = nullptr; + if (bakeCovers) { + hardHf = rcAllocHeightfield(); + if (!hardHf || !rcCreateHeightfield(&ctx, *hardHf, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs, cfg.ch)) { + rcFreeHeightField(hardHf); + hardHf = nullptr; + } + } + + /* 1. Rasterize overlapping heightmap cells directly (zero global terrain tri copy) */ + const float hmCs = geo.hdr.hmCellSize; + const float cosMaxSlope = std::cos(tier.maxSlopeDeg * kDegToRad); + const float cosRoughSlope = std::cos(kRoughSlopeDeg * kDegToRad); + const float waterY = geo.hdr.waterLevel; + const bool hasWater = waterY > -1e5f; + + int hx0 = std::clamp((int)std::floor((cfg.bmin[0] - geo.hdr.hmOrigin[0]) / hmCs) - 1, 0, (int)geo.hdr.hmWidth - 2); + int hz0 = std::clamp((int)std::floor((cfg.bmin[2] - geo.hdr.hmOrigin[1]) / hmCs) - 1, 0, (int)geo.hdr.hmHeight - 2); + int hx1 = std::clamp((int)std::ceil((cfg.bmax[0] - geo.hdr.hmOrigin[0]) / hmCs) + 1, hx0 + 1, (int)geo.hdr.hmWidth - 1); + int hz1 = std::clamp((int)std::ceil((cfg.bmax[2] - geo.hdr.hmOrigin[1]) / hmCs) + 1, hz0 + 1, (int)geo.hdr.hmHeight - 1); + + auto classifyTerrainTri = [&](const Vec3 &a, const Vec3 &b, const Vec3 &c) -> unsigned char { + float ny = triNormalYRightHanded(a, b, c); + if (ny < cosMaxSlope) return RC_NULL_AREA; + float cy = (a.y + b.y + c.y) * (1.0f / 3.0f); + if (hasWater) { + float depth = waterY - cy; + if (depth > kShallowWaterMaxM) return WTO_AREA_DEEP_WATER; + if (depth > kShallowWaterMinM) return WTO_AREA_SHALLOW_WATER; + } + if (ny < cosRoughSlope) return WTO_AREA_ROUGH; + return WTO_AREA_GROUND; + }; + + for (int gz = hz0; gz < hz1; ++gz) { + float z0 = geo.hdr.hmOrigin[1] + gz * hmCs; + float z1 = z0 + hmCs; + const float *row0 = &geo.heights[(size_t)gz * geo.hdr.hmWidth]; + const float *row1 = &geo.heights[(size_t)(gz + 1) * geo.hdr.hmWidth]; + for (int gx = hx0; gx < hx1; ++gx) { + float x0 = geo.hdr.hmOrigin[0] + gx * hmCs; + float x1 = x0 + hmCs; + Vec3 v00{ x0, row0[gx], z0 }; + Vec3 v10{ x1, row0[gx + 1], z0 }; + Vec3 v01{ x0, row1[gx], z1 }; + Vec3 v11{ x1, row1[gx + 1], z1 }; + /* CCW when viewed from +Y -> right-handed +Y normal */ + unsigned char a1 = classifyTerrainTri(v00, v01, v10); + unsigned char a2 = classifyTerrainTri(v10, v01, v11); + rcRasterizeTriangle(&ctx, &v00.x, &v01.x, &v10.x, a1, *solid, cfg.walkableClimb); + rcRasterizeTriangle(&ctx, &v10.x, &v01.x, &v11.x, a2, *solid, cfg.walkableClimb); + } + } + + /* 2. Rasterize obstacle triangles from this tile's spatial bucket */ + struct SoftMark { float minX, minY, minZ, maxX, maxY, maxZ; uint8_t area; }; + std::vector softMarks; + for (uint32_t ti : triBucket) { + const ObsTri &t = geo.obsTris[ti]; + const Vec3 &v0 = geo.obsVerts[t.i0]; + const Vec3 &v1 = geo.obsVerts[t.i1]; + const Vec3 &v2 = geo.obsVerts[t.i2]; + if (t.cls == WTO_OBS_HARD_SOLID || t.cls == WTO_OBS_TREE_THICK) { + rcRasterizeTriangle(&ctx, &v0.x, &v1.x, &v2.x, RC_NULL_AREA, *solid, cfg.walkableClimb); + if (hardHf && t.cls == WTO_OBS_HARD_SOLID) { + rcRasterizeTriangle(&ctx, &v0.x, &v1.x, &v2.x, 1, *hardHf, 1); + } + } else if (t.cls == WTO_OBS_BRIDGE_DECK) { + float ny = triNormalYRightHanded(v0, v1, v2); + if (std::fabs(ny) >= cosMaxSlope) { + if (ny >= 0.0f) rcRasterizeTriangle(&ctx, &v0.x, &v1.x, &v2.x, WTO_AREA_BRIDGE, *solid, cfg.walkableClimb); + else rcRasterizeTriangle(&ctx, &v0.x, &v2.x, &v1.x, WTO_AREA_BRIDGE, *solid, cfg.walkableClimb); + } else { + rcRasterizeTriangle(&ctx, &v0.x, &v1.x, &v2.x, RC_NULL_AREA, *solid, cfg.walkableClimb); + } + } else if (t.cls == WTO_OBS_CRUSHABLE || t.cls == WTO_OBS_TREE_THIN) { + SoftMark sm; + sm.minX = std::min({ v0.x, v1.x, v2.x }); + sm.maxX = std::max({ v0.x, v1.x, v2.x }); + sm.minY = std::min({ v0.y, v1.y, v2.y }); + sm.maxY = std::max({ v0.y, v1.y, v2.y }); + sm.minZ = std::min({ v0.z, v1.z, v2.z }); + sm.maxZ = std::max({ v0.z, v1.z, v2.z }); + sm.area = (t.cls == WTO_OBS_CRUSHABLE) ? WTO_AREA_CRUSHABLE : WTO_AREA_FOREST; + softMarks.push_back(sm); + } + } + + rcFilterLowHangingWalkableObstacles(&ctx, cfg.walkableClimb, *solid); + rcFilterLedgeSpans(&ctx, cfg.walkableHeight, cfg.walkableClimb, *solid); + rcFilterWalkableLowHeightSpans(&ctx, cfg.walkableHeight, *solid); + + rcCompactHeightfield *chf = rcAllocCompactHeightfield(); + if (!chf || !rcBuildCompactHeightfield(&ctx, cfg.walkableHeight, cfg.walkableClimb, *solid, *chf)) { + rcFreeHeightField(solid); + rcFreeHeightField(hardHf); + rcFreeCompactHeightfield(chf); + return res; + } + rcFreeHeightField(solid); + solid = nullptr; + + /* Erode walkable area by tank radius (guaranteed full hull clearance from hard obstacles!) */ + if (!rcErodeWalkableArea(&ctx, cfg.walkableRadius, *chf)) { + rcFreeHeightField(hardHf); + rcFreeCompactHeightfield(chf); + return res; + } + + /* Tag crushable fences & thin forest areas directly onto overlapping walkable cells (O(N), fast!) */ + for (const auto &sm : softMarks) { + int gx0 = std::clamp((int)std::floor((sm.minX - 0.4f - cfg.bmin[0]) / cfg.cs), 0, chf->width - 1); + int gx1 = std::clamp((int)std::floor((sm.maxX + 0.4f - cfg.bmin[0]) / cfg.cs), 0, chf->width - 1); + int gz0 = std::clamp((int)std::floor((sm.minZ - 0.4f - cfg.bmin[2]) / cfg.cs), 0, chf->height - 1); + int gz1 = std::clamp((int)std::floor((sm.maxZ + 0.4f - cfg.bmin[2]) / cfg.cs), 0, chf->height - 1); + for (int gz = gz0; gz <= gz1; ++gz) { + for (int gx = gx0; gx <= gx1; ++gx) { + const rcCompactCell &c = chf->cells[gx + gz * chf->width]; + for (int si = (int)c.index, ni = (int)(c.index + c.count); si < ni; ++si) { + if (chf->areas[si] == WTO_AREA_GROUND || chf->areas[si] == WTO_AREA_ROUGH) { + float sy = cfg.bmin[1] + chf->spans[si].y * cfg.ch; + if (sy >= sm.minY - 1.5f && sy <= sm.maxY + 0.5f) { + chf->areas[si] = sm.area; + } + } + } + } + } + } + + /* 3. Bake tank-qualified covers directly from eroded Tier-1 walkable boundary + hardHf */ + if (bakeCovers && hardHf) { + const int b = cfg.borderSize; + const int innerEnd = b + cfg.tileSize; + static const float kDirs[8][2] = { + { 1.0f, 0.0f }, { 0.7071f, 0.7071f }, { 0.0f, 1.0f }, { -0.7071f, 0.7071f }, + { -1.0f, 0.0f }, { -0.7071f, -0.7071f }, { 0.0f, -1.0f }, { 0.7071f, -0.7071f } + }; + for (int z = b; z < innerEnd; z += 4) { + for (int x = b; x < innerEnd; x += 4) { + const rcCompactCell &c = chf->cells[x + z * chf->width]; + for (int si = (int)c.index, ni = (int)(c.index + c.count); si < ni; ++si) { + unsigned char area = chf->areas[si]; + if (area == RC_NULL_AREA || area == WTO_AREA_DEEP_WATER || area == WTO_AREA_SHALLOW_WATER) continue; + /* Check if any 4-neighbor (at distance 1..2 cells) was eroded to RC_NULL_AREA or disconnected */ + const rcCompactSpan &s = chf->spans[si]; + bool isBoundary = false; + for (int d = 0; d < 4; ++d) { + int con = rcGetCon(s, d); + if (con == RC_NOT_CONNECTED) { isBoundary = true; break; } + int nx = x + rcGetDirOffsetX(d); + int nz = z + rcGetDirOffsetY(d); + int nsi = (int)chf->cells[nx + nz * chf->width].index + con; + if (chf->areas[nsi] == RC_NULL_AREA) { isBoundary = true; break; } + } + if (!isBoundary) continue; + + float wx = cfg.bmin[0] + (x + 0.5f) * cfg.cs; + float wy = cfg.bmin[1] + s.y * cfg.ch; + float wz = cfg.bmin[2] + (z + 0.5f) * cfg.cs; + + /* Find strongest hard-obstacle direction within 2.0..5.2 m */ + int bestDir = -1; + float bestWidth = 0.0f; + float bestHeight = 0.0f; + bool bestTurretBlocked = false; + + for (int di = 0; di < 8; ++di) { + float dx = kDirs[di][0], dz = kDirs[di][1]; + float px = -dz, pz = dx; /* tangent */ + int hullHits = 0; + int turretHits = 0; + float hSum = 0.0f; + /* 5 lateral samples across 3.6 m hull width (-1.8, -0.9, 0, +0.9, +1.8) */ + for (int li = -2; li <= 2; ++li) { + float off = li * 0.9f; + float sx = wx + px * off; + float sz = wz + pz * off; + float topY = wy; + if (hfTraceBand(*hardHf, geo, sx, sz, dx, dz, 5.2f, wy + 0.65f, wy + 1.80f, &topY)) { + hullHits++; + hSum += std::max(0.0f, topY - wy); + if (hfTraceBand(*hardHf, geo, sx, sz, dx, dz, 5.2f, wy + 2.05f, wy + 2.85f)) { + turretHits++; + } + } + } + if (hullHits < 4) continue; /* Require >= 80% hull width blocked (eliminates thin posts & narrow rocks) */ + float avgH = hSum / (float)hullHits; + if (avgH < 1.55f) continue; /* Eliminate low rocks (< 1.55 m) */ + + /* Check extra lateral span for continuous obstacle width */ + float wMeters = 3.6f; + if (hfTraceBand(*hardHf, geo, wx + px * 2.6f, wz + pz * 2.6f, dx, dz, 5.2f, wy + 0.65f, wy + 1.80f)) wMeters += 1.0f; + if (hfTraceBand(*hardHf, geo, wx - px * 2.6f, wz - pz * 2.6f, dx, dz, 5.2f, wy + 0.65f, wy + 1.80f)) wMeters += 1.0f; + + if (wMeters > bestWidth || (wMeters == bestWidth && avgH > bestHeight)) { + bestDir = di; + bestWidth = wMeters; + bestHeight = avgH; + bestTurretBlocked = (turretHits >= 3); + } + } + + if (bestDir < 0) continue; + float dx = kDirs[bestDir][0], dz = kDirs[bestDir][1]; + float px = -dz, pz = dx; + + WtoCoverPoint cp{}; + cp.pos[0] = wx; cp.pos[1] = wy; cp.pos[2] = wz; + cp.coverDir[0] = dx; cp.coverDir[1] = dz; + cp.retreatDir[0] = -dx; cp.retreatDir[1] = -dz; + cp.halfAngleDeg = bestWidth >= 5.0f ? 42.0f : 32.0f; + cp.heightM = bestHeight; + cp.widthM = bestWidth; + + if (bestTurretBlocked) { + cp.kind = WTO_COVER_FULL; + /* Probe corner peek left/right at 4.2 m */ + for (int side = -1; side <= 1; side += 2) { + float kx = wx + px * (side * 4.2f); + float kz = wz + pz * (side * 4.2f); + int kgx = (int)std::floor((kx - cfg.bmin[0]) / cfg.cs); + int kgz = (int)std::floor((kz - cfg.bmin[2]) / cfg.cs); + if (kgx >= 0 && kgz >= 0 && kgx < chf->width && kgz < chf->height) { + const rcCompactCell &kc = chf->cells[kgx + kgz * chf->width]; + bool walkablePeek = false; + float ky = wy; + for (int ksi = (int)kc.index, kni = (int)(kc.index + kc.count); ksi < kni; ++ksi) { + if (chf->areas[ksi] != RC_NULL_AREA && chf->areas[ksi] != WTO_AREA_DEEP_WATER) { + float sy = cfg.bmin[1] + chf->spans[ksi].y * cfg.ch; + if (std::fabs(sy - wy) <= 1.2f) { walkablePeek = true; ky = sy; break; } + } + } + if (walkablePeek && !hfTraceBand(*hardHf, geo, kx, kz, dx, dz, 14.0f, ky + 1.8f, ky + 2.6f)) { + if (side < 0) { + cp.hasPeekLeft = 1; + cp.peekLeft[0] = kx; cp.peekLeft[1] = ky; cp.peekLeft[2] = kz; + } else { + cp.hasPeekRight = 1; + cp.peekRight[0] = kx; cp.peekRight[1] = ky; cp.peekRight[2] = kz; + } + } + } + } + res.covers.push_back(cp); + } else { + /* Hull-down candidate: verify forward 22 m clear at turret height */ + if (!hfTraceBand(*hardHf, geo, wx, wz, dx, dz, 22.0f, wy + 2.15f, wy + 2.75f)) { + cp.kind = WTO_COVER_HULLDOWN; + res.covers.push_back(cp); + } + } + } + } + } + } + rcFreeHeightField(hardHf); + hardHf = nullptr; + + /* Smooth isolated single-voxel slope/area noise slivers before region building */ + rcMedianFilterWalkableArea(&ctx, *chf); + rcMedianFilterWalkableArea(&ctx, *chf); + + if (!rcBuildDistanceField(&ctx, *chf) || + !rcBuildRegions(&ctx, *chf, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea)) { + rcFreeCompactHeightfield(chf); + return res; + } + + rcContourSet *cset = rcAllocContourSet(); + if (!cset || !rcBuildContours(&ctx, *chf, cfg.maxSimplificationError, cfg.maxEdgeLen, *cset)) { + rcFreeCompactHeightfield(chf); + rcFreeContourSet(cset); + return res; + } + + rcPolyMesh *pmesh = rcAllocPolyMesh(); + if (!pmesh || !rcBuildPolyMesh(&ctx, *cset, cfg.maxVertsPerPoly, *pmesh)) { + rcFreeCompactHeightfield(chf); + rcFreeContourSet(cset); + rcFreePolyMesh(pmesh); + return res; + } + + rcPolyMeshDetail *dmesh = rcAllocPolyMeshDetail(); + if (!dmesh || !rcBuildPolyMeshDetail(&ctx, *pmesh, *chf, cfg.detailSampleDist, cfg.detailSampleMaxError, *dmesh)) { + rcFreeCompactHeightfield(chf); + rcFreeContourSet(cset); + rcFreePolyMesh(pmesh); + rcFreePolyMeshDetail(dmesh); + return res; + } + + rcFreeCompactHeightfield(chf); + rcFreeContourSet(cset); + + if (pmesh->npolys == 0) { + rcFreePolyMesh(pmesh); + rcFreePolyMeshDetail(dmesh); + return res; + } + + /* Assign initial polygon flags from Area ID */ + for (int i = 0; i < pmesh->npolys; ++i) { + unsigned char a = pmesh->areas[i]; + if (a == WTO_AREA_DEEP_WATER) pmesh->flags[i] = WTO_FLAG_DEEP_WATER; + else if (a == WTO_AREA_SHALLOW_WATER) pmesh->flags[i] = WTO_FLAG_WALK | WTO_FLAG_SHALLOW_WATER; + else if (a == WTO_AREA_NO_GO) pmesh->flags[i] = WTO_FLAG_BLOCKED; + else if (a != RC_NULL_AREA) pmesh->flags[i] = WTO_FLAG_WALK; + else pmesh->flags[i] = 0; + } + + dtNavMeshCreateParams params{}; + params.verts = pmesh->verts; + params.vertCount = pmesh->nverts; + params.polys = pmesh->polys; + params.polyAreas = pmesh->areas; + params.polyFlags = pmesh->flags; + params.polyCount = pmesh->npolys; + params.nvp = pmesh->nvp; + params.detailMeshes = dmesh->meshes; + params.detailVerts = dmesh->verts; + params.detailVertsCount = dmesh->nverts; + params.detailTris = dmesh->tris; + params.detailTriCount = dmesh->ntris; + params.walkableHeight = tier.agentHeight; + params.walkableRadius = tier.agentRadius; + params.walkableClimb = tier.maxClimb; + params.tileX = tx; + params.tileY = tz; + params.tileLayer = 0; + rcVcopy(params.bmin, pmesh->bmin); + rcVcopy(params.bmax, pmesh->bmax); + params.cs = cfg.cs; + params.ch = cfg.ch; + params.buildBvTree = true; + + unsigned char *navData = nullptr; + int navDataSize = 0; + if (dtCreateNavMeshData(¶ms, &navData, &navDataSize)) { + res.tile.data = navData; + res.tile.dataSize = navDataSize; + } + + rcFreePolyMesh(pmesh); + rcFreePolyMeshDetail(dmesh); + return res; +} + +static dtNavMesh *assembleNavMesh(const dtNavMeshParams &nmParams, const std::vector &tiles) { + dtNavMesh *mesh = dtAllocNavMesh(); + if (!mesh || dtStatusFailed(mesh->init(&nmParams))) { + dtFreeNavMesh(mesh); + return nullptr; + } + for (const auto &t : tiles) { + if (!t.data || t.dataSize <= 0) continue; + unsigned char *copy = (unsigned char *)dtAlloc(t.dataSize, DT_ALLOC_PERM); + std::memcpy(copy, t.data, t.dataSize); + if (dtStatusFailed(mesh->addTile(copy, t.dataSize, DT_TILE_FREE_DATA, 0, nullptr))) { + dtFree(copy); + } + } + return mesh; +} + +/* Flood-fill walkable polygons from all mission spawns and block disconnected interior islands + * (hollow building interiors, flat roofs, sealed courtyards) so queries never snap inside them. */ +static int pruneUnreachableIslands(dtNavMesh *mesh, dtNavMeshQuery *query, const GeoData &geo, const PoisData &pois) { + dtQueryFilter wf; + wf.setIncludeFlags(WTO_FLAG_WALK); + wf.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED); + const float ext[3] = { 16.0f, 16.0f, 16.0f }; + + std::unordered_set visited; + std::queue q; + auto seed = [&](const PoiPt &pt) { + float p[3] = { pt.x, geo.sampleHeight(pt.x, pt.z), pt.z }; + dtPolyRef ref = 0; float npt[3]; + if (dtStatusSucceed(query->findNearestPoly(p, ext, &wf, &ref, npt)) && ref) { + if (visited.insert(ref).second) q.push(ref); + } + }; + for (const auto &s : pois.t1Spawns) seed(s); + for (const auto &s : pois.t2Spawns) seed(s); + if (visited.empty()) return 0; + + const dtNavMesh *cm = mesh; + while (!q.empty()) { + dtPolyRef cur = q.front(); + q.pop(); + const dtMeshTile *tile = nullptr; + const dtPoly *poly = nullptr; + if (dtStatusFailed(cm->getTileAndPolyByRef(cur, &tile, &poly))) continue; + for (unsigned int li = poly->firstLink; li != DT_NULL_LINK; li = tile->links[li].next) { + dtPolyRef nref = tile->links[li].ref; + if (!nref) continue; + const dtMeshTile *nt = nullptr; + const dtPoly *np = nullptr; + if (dtStatusFailed(cm->getTileAndPolyByRef(nref, &nt, &np))) continue; + if ((np->flags & WTO_FLAG_WALK) == 0 || (np->flags & (WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED)) != 0) continue; + if (visited.insert(nref).second) q.push(nref); + } + } + + int pruned = 0; + for (int i = 0; i < cm->getMaxTiles(); ++i) { + const dtMeshTile *tile = cm->getTile(i); + if (!tile || !tile->header) continue; + dtPolyRef base = cm->getPolyRefBase(tile); + for (int p = 0; p < tile->header->polyCount; ++p) { + const dtPoly &poly = tile->polys[p]; + if ((poly.flags & WTO_FLAG_WALK) == 0 || (poly.flags & WTO_FLAG_DEEP_WATER) != 0) continue; + dtPolyRef ref = base | (dtPolyRef)p; + if (visited.find(ref) == visited.end()) { + mesh->setPolyArea(ref, WTO_AREA_NO_GO); + mesh->setPolyFlags(ref, WTO_FLAG_BLOCKED); + pruned++; + } + } + } + return pruned; +} + +static void markChokepoints(dtNavMesh *mesh, dtNavMeshQuery *query, float chokeDistM) { + dtQueryFilter filter; + filter.setIncludeFlags(WTO_FLAG_WALK); + filter.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED); + const dtNavMesh *cmesh = mesh; + for (int i = 0; i < cmesh->getMaxTiles(); ++i) { + const dtMeshTile *tile = cmesh->getTile(i); + if (!tile || !tile->header) continue; + dtPolyRef base = cmesh->getPolyRefBase(tile); + for (int p = 0; p < tile->header->polyCount; ++p) { + const dtPoly &poly = tile->polys[p]; + if (poly.getType() == DT_POLYTYPE_OFFMESH_CONNECTION) continue; + uint8_t area = poly.getArea(); + if (area == WTO_AREA_DEEP_WATER || area == WTO_AREA_SHALLOW_WATER) continue; + float cx = 0, cy = 0, cz = 0; + for (int v = 0; v < poly.vertCount; ++v) { + const float *vp = &tile->verts[poly.verts[v] * 3]; + cx += vp[0]; cy += vp[1]; cz += vp[2]; + } + float inv = 1.0f / (float)poly.vertCount; + float pos[3] = { cx * inv, cy * inv, cz * inv }; + dtPolyRef ref = base | (dtPolyRef)p; + float hitDist = 999.0f; + float hitPos[3], hitNorm[3]; + if (dtStatusSucceed(query->findDistanceToWall(ref, pos, chokeDistM + 1.0f, &filter, &hitDist, hitPos, hitNorm))) { + if (hitDist < chokeDistM) { + mesh->setPolyArea(ref, WTO_AREA_CHOKEPOINT); + mesh->setPolyFlags(ref, poly.flags | WTO_FLAG_CHOKEPOINT); + } + } + } + } +} + +static std::vector filterAndDedupeCovers( + const std::vector &raw, + dtNavMeshQuery *q1 +) { + dtQueryFilter filter; + filter.setIncludeFlags(WTO_FLAG_WALK); + filter.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED); + const float ext[3] = { 3.0f, 4.0f, 3.0f }; + + /* Sort by quality: hulldown & corner-peek full covers first, then wider/taller covers */ + std::vector order(raw.size()); + for (size_t i = 0; i < raw.size(); ++i) order[i] = i; + std::sort(order.begin(), order.end(), [&](size_t a, size_t b) { + auto score = [](const WtoCoverPoint &c) { + float s = c.widthM * 2.0f + std::min(c.heightM, 4.0f); + if (c.kind == WTO_COVER_HULLDOWN) s += 3.0f; + if (c.hasPeekLeft || c.hasPeekRight) s += 2.5f; + return s; + }; + return score(raw[a]) > score(raw[b]); + }); + + std::vector kept; + kept.reserve(2048); + static const float kRetreatAngles[3] = { 0.0f, 0.45f, -0.45f }; + + for (size_t idx : order) { + WtoCoverPoint cp = raw[idx]; + bool dup = false; + for (const auto &k : kept) { + float dx = k.pos[0] - cp.pos[0]; + float dz = k.pos[2] - cp.pos[2]; + if (dx * dx + dz * dz < 49.0f) { /* 7 m dedupe radius */ + float dot = k.coverDir[0] * cp.coverDir[0] + k.coverDir[1] * cp.coverDir[1]; + if (dot > 0.78f && k.kind == cp.kind) { dup = true; break; } + } + } + if (dup) continue; + + /* Verify parking spot is on T1 navmesh and has >= 8 m safe retreat corridor */ + dtPolyRef startRef = 0; + float nearest[3]; + if (dtStatusFailed(q1->findNearestPoly(cp.pos, ext, &filter, &startRef, nearest)) || !startRef) continue; + float snapSq = (nearest[0] - cp.pos[0]) * (nearest[0] - cp.pos[0]) + (nearest[2] - cp.pos[2]) * (nearest[2] - cp.pos[2]); + if (snapSq > 9.0f) continue; + cp.pos[0] = nearest[0]; cp.pos[1] = nearest[1]; cp.pos[2] = nearest[2]; + + bool retreatOk = false; + float baseAng = std::atan2(-cp.coverDir[1], -cp.coverDir[0]); + for (float da : kRetreatAngles) { + float rx = std::cos(baseAng + da); + float rz = std::sin(baseAng + da); + float endPt[3] = { cp.pos[0] + rx * 8.5f, cp.pos[1], cp.pos[2] + rz * 8.5f }; + float t = 0.0f; + float hitNorm[3]; + dtPolyRef polys[32]; + int npolys = 0; + if (dtStatusSucceed(q1->raycast(startRef, cp.pos, endPt, &filter, &t, hitNorm, polys, &npolys, 32))) { + if (t >= 0.92f) { + cp.retreatDir[0] = rx; + cp.retreatDir[1] = rz; + retreatOk = true; + break; + } + } + } + if (!retreatOk) continue; + kept.push_back(cp); + } + return kept; +} + +static void serializeTier(const dtNavMeshParams ¶ms, const std::vector &tiles, std::vector &out) { + auto append = [&](const void *p, size_t n) { + size_t o = out.size(); + out.resize(o + n); + std::memcpy(out.data() + o, p, n); + }; + append(¶ms, sizeof(params)); + uint32_t validCount = 0; + for (const auto &t : tiles) if (t.data && t.dataSize > 0) validCount++; + append(&validCount, sizeof(validCount)); + for (const auto &t : tiles) { + if (!t.data || t.dataSize <= 0) continue; + uint32_t sz = (uint32_t)t.dataSize; + append(&sz, sizeof(sz)); + append(t.data, t.dataSize); + } +} + +int main(int argc, char **argv) { + std::string geoPath, poisPath, outNavPath, outPreviewPath; + for (int i = 1; i + 1 < argc; i += 2) { + std::string a = argv[i]; + if (a == "--geo") geoPath = argv[i + 1]; + else if (a == "--pois") poisPath = argv[i + 1]; + else if (a == "--out") outNavPath = argv[i + 1]; + else if (a == "--preview") outPreviewPath = argv[i + 1]; + } + if (geoPath.empty() || poisPath.empty() || outNavPath.empty()) { + std::fprintf(stderr, "Usage: wto_navgen_bake --geo --pois --out [--preview ]\n"); + return 2; + } + + auto t0 = std::chrono::steady_clock::now(); + GeoData geo; + if (!loadGeo(geoPath, geo)) return 1; + PoisData pois; + if (!loadPois(poisPath, pois)) { + std::fprintf(stderr, "Failed to read POIs: %s\n", poisPath.c_str()); + return 1; + } + + float mapMinX = geo.hdr.boundsMin[0]; + float mapMinZ = geo.hdr.boundsMin[1]; + float mapMaxX = geo.hdr.boundsMax[0]; + float mapMaxZ = geo.hdr.boundsMax[1]; + int tilesX = (int)std::ceil((mapMaxX - mapMinX) / kTileWorldSize); + int tilesZ = (int)std::ceil((mapMaxZ - mapMinZ) / kTileWorldSize); + int totalTiles = tilesX * tilesZ; + std::printf("Bake %s: %.0fx%.0fm (%dx%d = %d tiles) obsTris=%u\n", + geoPath.c_str(), mapMaxX - mapMinX, mapMaxZ - mapMinZ, tilesX, tilesZ, totalTiles, geo.hdr.obsTriCount); + + /* Bucket obstacle triangles once into overlapping tiles */ + const float pad = 4.5f; + std::vector> buckets((size_t)totalTiles); + for (uint32_t ti = 0; ti < geo.hdr.obsTriCount; ++ti) { + const auto &t = geo.obsTris[ti]; + const Vec3 &v0 = geo.obsVerts[t.i0]; + const Vec3 &v1 = geo.obsVerts[t.i1]; + const Vec3 &v2 = geo.obsVerts[t.i2]; + float tminX = std::min({ v0.x, v1.x, v2.x }) - pad; + float tmaxX = std::max({ v0.x, v1.x, v2.x }) + pad; + float tminZ = std::min({ v0.z, v1.z, v2.z }) - pad; + float tmaxZ = std::max({ v0.z, v1.z, v2.z }) + pad; + int tx0 = std::clamp((int)std::floor((tminX - mapMinX) / kTileWorldSize), 0, tilesX - 1); + int tx1 = std::clamp((int)std::floor((tmaxX - mapMinX) / kTileWorldSize), 0, tilesX - 1); + int tz0 = std::clamp((int)std::floor((tminZ - mapMinZ) / kTileWorldSize), 0, tilesZ - 1); + int tz1 = std::clamp((int)std::floor((tmaxZ - mapMinZ) / kTileWorldSize), 0, tilesZ - 1); + for (int tz = tz0; tz <= tz1; ++tz) { + for (int tx = tx0; tx <= tx1; ++tx) { + buckets[(size_t)tz * tilesX + tx].push_back(ti); + } + } + } + + dtNavMeshParams nmParams{}; + nmParams.orig[0] = mapMinX; + nmParams.orig[1] = geo.minY; + nmParams.orig[2] = mapMinZ; + nmParams.tileWidth = kTileWorldSize; + nmParams.tileHeight = kTileWorldSize; + int tileBits = dtIlog2(dtNextPow2((unsigned int)totalTiles)); + if (tileBits > 16) tileBits = 16; + nmParams.maxTiles = 1 << tileBits; + nmParams.maxPolys = 1 << (22 - tileBits); + + dtNavMesh *meshes[WTO_NAV_TIER_COUNT] = {}; + dtNavMeshQuery *queries[WTO_NAV_TIER_COUNT] = {}; + std::vector tierTiles[WTO_NAV_TIER_COUNT]; + std::vector rawCovers; + + unsigned int nWorkers = std::max(1u, std::thread::hardware_concurrency()); + + for (uint32_t tierIdx = 0; tierIdx < WTO_NAV_TIER_COUNT; ++tierIdx) { + const bool doCovers = (tierIdx == WTO_NAV_TIER_STANDARD); + tierTiles[tierIdx].resize((size_t)totalTiles); + std::atomic nextTile{ 0 }; + std::mutex covMtx; + + std::vector workers; + for (unsigned int w = 0; w < nWorkers; ++w) { + workers.emplace_back([&]() { + std::vector localCov; + while (true) { + int idx = nextTile.fetch_add(1); + if (idx >= totalTiles) break; + int tx = idx % tilesX; + int tz = idx / tilesX; + auto br = buildSingleTile(geo, buckets[(size_t)idx], kTiers[tierIdx], tx, tz, mapMinX, mapMinZ, doCovers); + tierTiles[tierIdx][(size_t)idx] = br.tile; + if (doCovers && !br.covers.empty()) { + localCov.insert(localCov.end(), br.covers.begin(), br.covers.end()); + } + } + if (doCovers && !localCov.empty()) { + std::lock_guard lk(covMtx); + rawCovers.insert(rawCovers.end(), localCov.begin(), localCov.end()); + } + }); + } + for (auto &th : workers) th.join(); + + meshes[tierIdx] = assembleNavMesh(nmParams, tierTiles[tierIdx]); + queries[tierIdx] = dtAllocNavMeshQuery(); + queries[tierIdx]->init(meshes[tierIdx], 65535); + + int builtCnt = 0, polyCnt = 0; + for (const auto &bt : tierTiles[tierIdx]) if (bt.data) builtCnt++; + const dtNavMesh *cm = meshes[tierIdx]; + for (int i = 0; i < cm->getMaxTiles(); ++i) { + const dtMeshTile *tl = cm->getTile(i); + if (tl && tl->header) polyCnt += tl->header->polyCount; + } + int pruned = pruneUnreachableIslands(meshes[tierIdx], queries[tierIdx], geo, pois); + if (tierIdx == WTO_NAV_TIER_STANDARD) { + markChokepoints(meshes[tierIdx], queries[tierIdx], 3.8f); + } + std::printf(" %s (r=%.2fm): tiles=%d/%d polys=%d prunedIslands=%d\n", + kTiers[tierIdx].name, kTiers[tierIdx].agentRadius, builtCnt, totalTiles, polyCnt, pruned); + } + + /* Dedupe + retreat-verify tank covers on Tier 1 */ + std::vector covers = filterAndDedupeCovers(rawCovers, queries[WTO_NAV_TIER_STANDARD]); + int fullCnt = 0, hdCnt = 0, peekCnt = 0; + for (const auto &c : covers) { + if (c.kind == WTO_COVER_FULL) fullCnt++; else hdCnt++; + if (c.hasPeekLeft || c.hasPeekRight) peekCnt++; + } + std::printf(" Covers: raw=%zu -> verified=%zu (full=%d, hulldown=%d, withPeek=%d)\n", + rawCovers.size(), covers.size(), fullCnt, hdCnt, peekCnt); + + /* Build 8m tactical grid (clearance + simple terrain-horizon exposure) */ + const float tacCellM = 8.0f; + uint32_t tacCols = (uint32_t)std::ceil((mapMaxX - mapMinX) / tacCellM); + uint32_t tacRows = (uint32_t)std::ceil((mapMaxZ - mapMinZ) / tacCellM); + std::vector tacGrid((size_t)tacCols * tacRows); + { + dtQueryFilter wf; + wf.setIncludeFlags(WTO_FLAG_WALK); + wf.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED); + const float ext[3] = { 4.5f, 6.0f, 4.5f }; + dtNavMeshQuery *q1 = queries[WTO_NAV_TIER_STANDARD]; + for (uint32_t rz = 0; rz < tacRows; ++rz) { + float wz = mapMinZ + (rz + 0.5f) * tacCellM; + for (uint32_t cx = 0; cx < tacCols; ++cx) { + float wx = mapMinX + (cx + 0.5f) * tacCellM; + float gy = geo.sampleHeight(wx, wz); + float pt[3] = { wx, gy, wz }; + WtoTacticalCell cell{ 128, 0, 128, 128 }; + dtPolyRef ref = 0; + float npt[3]; + if (dtStatusSucceed(q1->findNearestPoly(pt, ext, &wf, &ref, npt)) && ref) { + float dist = 32.0f, hp[3], hn[3]; + if (dtStatusSucceed(q1->findDistanceToWall(ref, npt, 32.0f, &wf, &dist, hp, hn))) { + cell.clearanceHalfM = (uint8_t)std::clamp((int)std::round(dist * 2.0f), 0, 255); + } + /* Horizon exposure: sample 8 azimuths at 40m..240m against heightmap */ + int openRays = 0; + for (int a = 0; a < 8; ++a) { + float ang = a * (kPi * 0.25f); + float dx = std::cos(ang), dz = std::sin(ang); + bool blocked = false; + for (float d = 40.0f; d <= 240.0f; d += 40.0f) { + float sx = wx + dx * d, sz = wz + dz * d; + if (sx < mapMinX || sx > mapMaxX || sz < mapMinZ || sz > mapMaxZ) break; + if (geo.sampleHeight(sx, sz) > gy + 3.2f) { blocked = true; break; } + } + if (!blocked) openRays++; + } + cell.exposure = (uint8_t)((openRays * 255) / 8); + } + tacGrid[(size_t)rz * tacCols + cx] = cell; + } + } + } + + /* Connectivity audit: all spawns -> all capture zones on T0, T1, T2 */ + struct SamplePath { std::vector pts; }; + std::vector samplePaths; + { + dtQueryFilter pf; + pf.setIncludeFlags(WTO_FLAG_WALK); + pf.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED); + pf.setAreaCost(WTO_AREA_ROAD, 0.75f); + pf.setAreaCost(WTO_AREA_BRIDGE, 0.90f); + pf.setAreaCost(WTO_AREA_GROUND, 1.00f); + pf.setAreaCost(WTO_AREA_ROUGH, 1.65f); + pf.setAreaCost(WTO_AREA_FOREST, 2.10f); + pf.setAreaCost(WTO_AREA_CRUSHABLE, 2.40f); + pf.setAreaCost(WTO_AREA_SHALLOW_WATER, 2.60f); + pf.setAreaCost(WTO_AREA_CHOKEPOINT, 1.80f); + const float snapExt[3] = { 12.0f, 12.0f, 12.0f }; + + std::vector allSpawns = pois.t1Spawns; + allSpawns.insert(allSpawns.end(), pois.t2Spawns.begin(), pois.t2Spawns.end()); + + for (uint32_t ti = 0; ti < WTO_NAV_TIER_COUNT; ++ti) { + int totalPairs = 0, fullOk = 0, partialOk = 0, snapFail = 0; + dtNavMeshQuery *q = queries[ti]; + for (size_t si = 0; si < allSpawns.size(); ++si) { + float sp[3] = { allSpawns[si].x, geo.sampleHeight(allSpawns[si].x, allSpawns[si].z), allSpawns[si].z }; + dtPolyRef sRef = 0; float sNear[3]; + bool sOk = dtStatusSucceed(q->findNearestPoly(sp, snapExt, &pf, &sRef, sNear)) && sRef; + for (size_t ci = 0; ci < pois.caps.size(); ++ci) { + totalPairs++; + float cp[3] = { pois.caps[ci].x, geo.sampleHeight(pois.caps[ci].x, pois.caps[ci].z), pois.caps[ci].z }; + dtPolyRef cRef = 0; float cNear[3]; + bool cOk = dtStatusSucceed(q->findNearestPoly(cp, snapExt, &pf, &cRef, cNear)) && cRef; + if (!sOk || !cOk) { snapFail++; continue; } + dtPolyRef polys[4096]; + int npolys = 0; + dtStatus st = q->findPath(sRef, cRef, sNear, cNear, &pf, polys, &npolys, 4096); + if (dtStatusSucceed(st) && npolys > 0 && polys[npolys - 1] == cRef) { + fullOk++; + if (ti == WTO_NAV_TIER_STANDARD && samplePaths.size() < 12 && (si % std::max(1, allSpawns.size() / 6) == 0)) { + float straight[512 * 3]; + int nstraight = 0; + if (dtStatusSucceed(q->findStraightPath(sNear, cNear, polys, npolys, straight, nullptr, nullptr, &nstraight, 512)) && nstraight >= 2) { + SamplePath spath; + spath.pts.assign(straight, straight + nstraight * 3); + samplePaths.push_back(std::move(spath)); + } + } + } else if (dtStatusSucceed(st) && npolys > 0) { + partialOk++; + if (ti == WTO_NAV_TIER_STANDARD && partialOk <= 4) { + std::printf(" [partial] %s (%.0f,%.0f) -> %s (%.0f,%.0f) npolys=%d outOfNodes=%d\n", + allSpawns[si].name.c_str(), allSpawns[si].x, allSpawns[si].z, + pois.caps[ci].name.c_str(), pois.caps[ci].x, pois.caps[ci].z, + npolys, (st & DT_OUT_OF_NODES) ? 1 : 0); + } + } + } + } + std::printf(" Connectivity %s: full=%d/%d (%.1f%%) partial=%d snapFail=%d\n", + kTiers[ti].name, fullOk, totalPairs, + totalPairs > 0 ? (100.0f * fullOk / totalPairs) : 100.0f, + partialOk, snapFail); + } + } + + /* Serialize final `.wtonav` binary */ + std::vector tierBlobs[WTO_NAV_TIER_COUNT]; + for (uint32_t ti = 0; ti < WTO_NAV_TIER_COUNT; ++ti) { + /* Re-copy modified tiles (with chokepoint flags on T1) directly from assembled dtNavMesh */ + const dtNavMesh *cm = meshes[ti]; + std::vector finalTiles; + for (int i = 0; i < cm->getMaxTiles(); ++i) { + const dtMeshTile *tl = cm->getTile(i); + if (tl && tl->header && tl->data && tl->dataSize > 0) { + BuiltTile bt; + bt.data = tl->data; + bt.dataSize = tl->dataSize; + finalTiles.push_back(bt); + } + } + serializeTier(nmParams, finalTiles, tierBlobs[ti]); + } + + WtoNavHeader nh{}; + std::memcpy(nh.magic, WTO_NAV_MAGIC, 8); + nh.version = WTO_NAV_VERSION; + std::memcpy(nh.everSha1, geo.hdr.everSha1, 20); + nh.bmin[0] = mapMinX; nh.bmin[1] = geo.minY; nh.bmin[2] = mapMinZ; + nh.bmax[0] = mapMaxX; nh.bmax[1] = geo.maxY; nh.bmax[2] = mapMaxZ; + nh.waterLevel = geo.hdr.waterLevel; + nh.tierCount = WTO_NAV_TIER_COUNT; + + uint32_t curOff = (uint32_t)sizeof(WtoNavHeader); + for (uint32_t ti = 0; ti < WTO_NAV_TIER_COUNT; ++ti) { + nh.tierOffsets[ti] = curOff; + nh.tierSizes[ti] = (uint32_t)tierBlobs[ti].size(); + curOff += nh.tierSizes[ti]; + } + nh.coverOffset = curOff; + nh.coverCount = (uint32_t)covers.size(); + curOff += (uint32_t)(covers.size() * sizeof(WtoCoverPoint)); + nh.tacOffset = curOff; + nh.tacCols = tacCols; + nh.tacRows = tacRows; + nh.tacCellM = tacCellM; + nh.tacOrigin[0] = mapMinX; + nh.tacOrigin[1] = mapMinZ; + + { + std::ofstream out(outNavPath, std::ios::binary); + out.write(reinterpret_cast(&nh), sizeof(nh)); + for (uint32_t ti = 0; ti < WTO_NAV_TIER_COUNT; ++ti) { + out.write(reinterpret_cast(tierBlobs[ti].data()), tierBlobs[ti].size()); + } + if (!covers.empty()) { + out.write(reinterpret_cast(covers.data()), covers.size() * sizeof(WtoCoverPoint)); + } + if (!tacGrid.empty()) { + out.write(reinterpret_cast(tacGrid.data()), tacGrid.size() * sizeof(WtoTacticalCell)); + } + std::printf(" Wrote %s (%.2f MB uncompressed)\n", outNavPath.c_str(), (double)(curOff + tacGrid.size() * sizeof(WtoTacticalCell)) / (1024.0 * 1024.0)); + } + + /* Write compact raster preview data for PNG visual inspection */ + if (!outPreviewPath.empty()) { + const uint32_t pw = 1024, ph = 1024; + std::vector pHeight((size_t)pw * ph); + std::vector pFlags((size_t)pw * ph, 0); + /* Bit 0: T0 walkable, Bit 1: T1 walkable, Bit 2: T2 walkable, Bit 3: shallow water, + * Bit 4: deep water, Bit 5: chokepoint, Bit 6: crushable/forest, Bit 7: bridge */ + dtQueryFilter anyF; + anyF.setIncludeFlags(0xFFFF); + anyF.setExcludeFlags(0); + const float ext[3] = { 0.8f, 6.0f, 0.8f }; + + std::atomic nextRow{ 0 }; + std::vector pWorkers; + for (unsigned int w = 0; w < nWorkers; ++w) { + pWorkers.emplace_back([&]() { + dtNavMeshQuery *lq[WTO_NAV_TIER_COUNT]; + for (uint32_t ti = 0; ti < WTO_NAV_TIER_COUNT; ++ti) { + lq[ti] = dtAllocNavMeshQuery(); + lq[ti]->init(meshes[ti], 256); + } + while (true) { + uint32_t rz = nextRow.fetch_add(1); + if (rz >= ph) break; + float wz = mapMinZ + ((rz + 0.5f) / ph) * (mapMaxZ - mapMinZ); + for (uint32_t rx = 0; rx < pw; ++rx) { + float wx = mapMinX + ((rx + 0.5f) / pw) * (mapMaxX - mapMinX); + float gy = geo.sampleHeight(wx, wz); + pHeight[(size_t)rz * pw + rx] = gy; + uint8_t fl = 0; + float pt[3] = { wx, gy, wz }; + for (uint32_t ti = 0; ti < WTO_NAV_TIER_COUNT; ++ti) { + dtPolyRef ref = 0; + float npt[3]; + if (dtStatusSucceed(lq[ti]->findNearestPoly(pt, ext, &anyF, &ref, npt)) && ref) { + float d2 = (npt[0] - wx) * (npt[0] - wx) + (npt[2] - wz) * (npt[2] - wz); + if (d2 <= 1.0f) { + unsigned char area = 0; + meshes[ti]->getPolyArea(ref, &area); + if (area == WTO_AREA_DEEP_WATER) fl |= 16; + else { + fl |= (1u << ti); + if (ti == WTO_NAV_TIER_STANDARD) { + if (area == WTO_AREA_SHALLOW_WATER) fl |= 8; + else if (area == WTO_AREA_CHOKEPOINT) fl |= 32; + else if (area == WTO_AREA_CRUSHABLE || area == WTO_AREA_FOREST) fl |= 64; + else if (area == WTO_AREA_BRIDGE) fl |= 128; + } + } + } + } + } + pFlags[(size_t)rz * pw + rx] = fl; + } + } + for (uint32_t ti = 0; ti < WTO_NAV_TIER_COUNT; ++ti) dtFreeNavMeshQuery(lq[ti]); + }); + } + for (auto &th : pWorkers) th.join(); + + std::ofstream pout(outPreviewPath, std::ios::binary); + pout.write("WTOPREV1", 8); + pout.write(reinterpret_cast(&pw), 4); + pout.write(reinterpret_cast(&ph), 4); + pout.write(reinterpret_cast(&mapMinX), 4); + pout.write(reinterpret_cast(&mapMinZ), 4); + pout.write(reinterpret_cast(&mapMaxX), 4); + pout.write(reinterpret_cast(&mapMaxZ), 4); + pout.write(reinterpret_cast(&geo.hdr.waterLevel), 4); + pout.write(reinterpret_cast(pHeight.data()), pHeight.size() * sizeof(float)); + pout.write(reinterpret_cast(pFlags.data()), pFlags.size()); + uint32_t cCnt = (uint32_t)covers.size(); + pout.write(reinterpret_cast(&cCnt), 4); + if (cCnt > 0) pout.write(reinterpret_cast(covers.data()), cCnt * sizeof(WtoCoverPoint)); + pout.write(reinterpret_cast(&tacCols), 4); + pout.write(reinterpret_cast(&tacRows), 4); + if (!tacGrid.empty()) pout.write(reinterpret_cast(tacGrid.data()), tacGrid.size() * sizeof(WtoTacticalCell)); + uint32_t pCnt = (uint32_t)samplePaths.size(); + pout.write(reinterpret_cast(&pCnt), 4); + for (const auto &sp : samplePaths) { + uint32_t npts = (uint32_t)(sp.pts.size() / 3); + pout.write(reinterpret_cast(&npts), 4); + pout.write(reinterpret_cast(sp.pts.data()), sp.pts.size() * sizeof(float)); + } + } + + for (uint32_t ti = 0; ti < WTO_NAV_TIER_COUNT; ++ti) { + dtFreeNavMeshQuery(queries[ti]); + dtFreeNavMesh(meshes[ti]); + for (auto &bt : tierTiles[ti]) dtFree(bt.data); + } + + auto elapsed = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + std::printf("Done in %.2fs\n", elapsed); + return 0; +} diff --git a/tools/navgen/bake/build.ps1 b/tools/navgen/bake/build.ps1 new file mode 100644 index 0000000..d1c3f88 --- /dev/null +++ b/tools/navgen/bake/build.ps1 @@ -0,0 +1,32 @@ +<# + Build tools/navgen/bake/wto_navgen_bake.exe using MSVC x64 C++ (Visual Studio). + Links vendored upstream Recast + Detour (zlib license) from native/third_party/recastnavigation. +#> +param([string]$Out = (Join-Path $PSScriptRoot '..\..\..\build\navgen')) +$ErrorActionPreference = 'Stop' + +$vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe' +$vs = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath +if (-not $vs) { throw 'Visual Studio with x64 C++ tools was not found' } +$vcvars = Join-Path $vs 'VC\Auxiliary\Build\vcvars64.bat' + +$root = Resolve-Path (Join-Path $PSScriptRoot '..\..\..') +$rc = Join-Path $root 'native\third_party\recastnavigation\Recast' +$dt = Join-Path $root 'native\third_party\recastnavigation\Detour' +$navInc = Join-Path $root 'native\wto-nav' +New-Item -ItemType Directory -Force $Out | Out-Null +$obj = Join-Path $Out 'obj' +New-Item -ItemType Directory -Force $obj | Out-Null + +$sources = @( + (Join-Path $PSScriptRoot 'bake.cpp') +) + (Get-ChildItem "$rc\Source\*.cpp").FullName + (Get-ChildItem "$dt\Source\*.cpp").FullName +$quoted = $sources | ForEach-Object { '"' + $_ + '"' } + +$exe = Join-Path $Out 'wto_navgen_bake.exe' +$cmd = "`"$vcvars`" >nul && cl /nologo /O2 /EHsc /std:c++17 /MT /W3 /D_CRT_SECURE_NO_WARNINGS " + + "/I`"$rc\Include`" /I`"$dt\Include`" /I`"$navInc`" " + + "/Fo`"$obj\\`" $($quoted -join ' ') /Fe`"$exe`"" +cmd /c $cmd +if ($LASTEXITCODE -ne 0) { throw "cl failed with exit code $LASTEXITCODE" } +Write-Output $exe diff --git a/tools/navgen/extract/Cargo.lock b/tools/navgen/extract/Cargo.lock new file mode 100644 index 0000000..6361db0 --- /dev/null +++ b/tools/navgen/extract/Cargo.lock @@ -0,0 +1,534 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "anstream" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85c097ce94629611e0a15ef1078a2fe2ce3b4a0f4b44708e85eeb09dd5f188eb" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c7a9e344b352bef7873e51ff425c2f90d5aa2a252db2b84289c93ff30beb3d7" + +[[package]] +name = "anstyle-parse" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0571a23d2188b4aae7adc1df454cc81d6232cf37674fa717ac119f6c74d0dc1" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a5cf9d05ffa9c878c447b33b069605e890ebcd36d2761f86367873c2ecaa7f" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c2d00c1b2d84cef823d89d4da02ad8ff1e76c969e029da990b40f16dc834221" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "anyhow" +version = "1.0.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" + +[[package]] +name = "bcn-decode" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3d5cf71fc14b37654892fc02d25b45ddca03d4245e352510e3c55bdc5cda1f" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "byteorder" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34fb07aac3b9f547c7af8dc897dfe73c10847b6c71130c364bdd7891d979c816" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "clap" +version = "4.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "colorchoice" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f7f11958434c85b6efac08f8299dc08bd263184ce080232e2168940cda4368e" + +[[package]] +name = "crc32fast" +version = "1.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "lewton" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "777b48df9aaab155475a83a7df3070395ea1ac6902f5cd062b8f2b028075c030" +dependencies = [ + "byteorder", + "tinyvec", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "lztans" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bad6ebd0a522f78e2889049a78d31ec62cd646a37524215fa00ea548b20bed0" + +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "ruzstd" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7c1c839d570d835527c9a5e4db7cb2198683a988cb9d7293fc8674e6bd58fc8" +dependencies = [ + "twox-hash", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "foldhash", + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "twox-hash" +version = "2.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "windows-link" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4e57b2aae53a240c62b65069a63eaf8d5fa747f5d0d8e670c5210a98847bce4" + +[[package]] +name = "windows-sys" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eed2df9f5f458664c87437f6758f0d93085b06433bf66b2b84c23c19f3d2012c" +dependencies = [ + "windows-link", +] + +[[package]] +name = "wt-formats" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cc92320ebb10137ea72419d36b91febc1aa597af3ee762d75282d3980575d89" +dependencies = [ + "bcn-decode", + "flate2", + "lztans", + "png", + "ruzstd", +] + +[[package]] +name = "wt-unpack" +version = "0.5.1" +source = "git+https://github.com/patodois/wt-unpack?rev=01d5b7603ae35e261a676d9b7b644c521dd303a0#01d5b7603ae35e261a676d9b7b644c521dd303a0" +dependencies = [ + "anyhow", + "clap", + "lewton", + "lztans", + "md-5", + "memmap2", + "png", + "ruzstd", + "serde_json", + "wt-formats", +] + +[[package]] +name = "wto-navgen-extract" +version = "0.1.0" +dependencies = [ + "anyhow", + "serde", + "serde_json", + "wt-formats", + "wt-unpack", +] + +[[package]] +name = "zlib-rs" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/tools/navgen/extract/Cargo.toml b/tools/navgen/extract/Cargo.toml new file mode 100644 index 0000000..204ac04 --- /dev/null +++ b/tools/navgen/extract/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "wto-navgen-extract" +version = "0.1.0" +edition = "2021" +description = "Offline Dagor level geometry and collision extractor for WTOffline tank navigation" + +[dependencies] +anyhow = "1" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +wt-formats = "0.1.0" +wt-unpack = { git = "https://github.com/patodois/wt-unpack", rev = "01d5b7603ae35e261a676d9b7b644c521dd303a0" } + +[profile.release] +opt-level = 3 +lto = "thin" diff --git a/tools/navgen/extract/src/main.rs b/tools/navgen/extract/src/main.rs new file mode 100644 index 0000000..8d51c1f --- /dev/null +++ b/tools/navgen/extract/src/main.rs @@ -0,0 +1,550 @@ +use std::collections::{HashMap, HashSet}; +use std::fs::{self, File}; +use std::io::{BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::time::Instant; + +use anyhow::{bail, Context, Result}; +use serde::Deserialize; +use wt_formats::grp::GrpPack; +use wt_unpack::blk::{self, Value}; +use wt_unpack::collision::{Collision, CollisionNode, NodeKind, COLLISION}; +use wt_unpack::level::{Heightmap, Level}; +use wt_unpack::rendinst::ResourceIndex; +use wt_unpack::vromfs::Vromfs; + +const WTO_GEO_MAGIC: &[u8; 8] = b"WTOGEO\0\x01"; +const WTO_GEO_VERSION: u32 = 1; + +const OBS_HARD_SOLID: u8 = 0; +const OBS_BRIDGE_DECK: u8 = 1; +const OBS_CRUSHABLE: u8 = 2; +const OBS_TREE_THICK: u8 = 3; +const OBS_TREE_THIN: u8 = 4; + +#[derive(Debug, Deserialize)] +struct LevelPois { + level: String, + #[serde(rename = "levelPath")] + level_path: String, + #[serde(rename = "boundsMin")] + bounds_min: [f32; 2], + #[serde(rename = "boundsMax")] + bounds_max: [f32; 2], +} + +#[derive(Debug, Clone)] +struct PoolMeta { + is_bridge: bool, + is_crushable: bool, + is_soft_foliage: bool, +} + +#[derive(Debug)] +struct CachedCollision { + max_radius: f32, + tris: Vec<([f32; 3], [f32; 3], [f32; 3], u8)>, +} + +fn parse_args() -> Result<(PathBuf, PathBuf, PathBuf)> { + let mut game: Option = None; + let mut pois: Option = None; + let mut out: Option = None; + let mut args = std::env::args().skip(1); + while let Some(a) = args.next() { + match a.as_str() { + "--game" => game = args.next().map(PathBuf::from), + "--pois" => pois = args.next().map(PathBuf::from), + "--out" => out = args.next().map(PathBuf::from), + other => bail!("unknown argument: {other}"), + } + } + Ok(( + game.context("missing --game ")?, + pois.context("missing --pois ")?, + out.context("missing --out ")?, + )) +} + +struct AcesMeta { + water_level: f32, + /// Authoritative tank-crushable impulse threshold from `config/rendinst_dmg.blk` (lowercase name -> destructionImpulse). + destr_impulse: HashMap, +} + +fn read_aces_meta(game: &Path, level_name: &str) -> AcesMeta { + let mut meta = AcesMeta { water_level: -1.0e6, destr_impulse: HashMap::new() }; + let aces_path = game.join("aces.vromfs.bin"); + let Ok(raw) = fs::read(&aces_path) else { return meta; }; + let Ok(arc) = Vromfs::parse(&raw) else { return meta; }; + let shared = arc + .files + .iter() + .find(|f| f.name == wt_unpack::vromfs::SHARED_NAMEMAP_NAME) + .and_then(|nm| blk::SharedContext::from_namemap(&nm.data).ok()) + .map(|(mut ctx, dict_name)| { + if let Some(df) = arc.files.iter().find(|f| f.name.eq_ignore_ascii_case(&dict_name)) { + ctx.dict = Some(df.data.clone()); + } + ctx + }); + + let target = format!("levels/{}.blk", level_name.to_lowercase()); + if let Some(entry) = arc.files.iter().find(|f| f.name.eq_ignore_ascii_case(&target)) { + if let Ok(doc) = blk::parse(&entry.data, shared.as_ref()) { + for (name, value) in &doc.params { + if name.eq_ignore_ascii_case("water_level") { + match value { + Value::Real(v) => meta.water_level = *v, + Value::Int(v) => meta.water_level = *v as f32, + _ => {} + } + } + } + } + } + + if let Some(dmg_entry) = arc.files.iter().find(|f| f.name.eq_ignore_ascii_case("config/rendinst_dmg.blk")) { + if let Ok(doc) = blk::parse(&dmg_entry.data, shared.as_ref()) { + for b in &doc.blocks { + let mut rname: Option<&str> = None; + let mut impulse: Option = None; + for (k, v) in &b.params { + if k.eq_ignore_ascii_case("name") { + if let Value::Str(s) = v { rname = Some(s.as_str()); } + } else if k.eq_ignore_ascii_case("destructionImpulse") { + match v { + Value::Real(x) => impulse = Some(*x), + Value::Int(x) => impulse = Some(*x as f32), + _ => {} + } + } + } + if let (Some(n), Some(imp)) = (rname, impulse) { + meta.destr_impulse.insert(n.to_lowercase(), imp); + } + } + } + } + meta +} + +fn classify_pool(name: &str, destr_impulse: Option) -> PoolMeta { + let lower = name.to_lowercase(); + let is_bridge = lower.contains("bridge") + || lower.contains("viaduct") + || lower.contains("overpass") + || lower.contains("pontoon") + || lower.contains("jetty") + || lower.contains("pier"); + + let always_hard = lower.contains("rock") + || lower.contains("cliff") + || lower.contains("bunker") + || lower.contains("house") + || lower.contains("building") + || lower.contains("castle") + || lower.contains("tower") + || lower.contains("church") + || lower.contains("factory") + || lower.contains("hangar") + || lower.contains("wagon") + || lower.contains("train") + || lower.contains("locomotive") + || lower.contains("container") + || lower.contains("tank_wreck") + || is_bridge; + + let is_soft_foliage = !always_hard + && (lower.starts_with("bush_") + || lower.contains("_bush_") + || lower.starts_with("shrub_") + || lower.contains("_shrub_") + || lower.contains("grass") + || lower.contains("reed") + || lower.contains("flower") + || lower.contains("fern")); + + // Authoritative War Thunder physics: objects in `config/rendinst_dmg.blk` with low + // `destructionImpulse` (<= 45,000 N*s) are crushed on contact by moving tanks (wooden fences, + // lamp posts, hedges, benches, sheds, destructible thin walls, small trees). + let is_crushable = !always_hard + && match destr_impulse { + Some(imp) if imp > 0.0 && imp <= 45_000.0 => true, + _ => lower.contains("fence_wood") + || lower.contains("wooden_fence") + || lower.contains("hedge") + || lower.contains("sign_") + || lower.contains("bench") + || lower.contains("hay"), + }; + + PoolMeta { is_bridge, is_crushable, is_soft_foliage } +} + +fn transform_point(tm: &[[f32; 3]; 4], p: [f32; 3]) -> [f32; 3] { + [ + tm[0][0] * p[0] + tm[1][0] * p[1] + tm[2][0] * p[2] + tm[3][0], + tm[0][1] * p[0] + tm[1][1] * p[1] + tm[2][1] * p[2] + tm[3][1], + tm[0][2] * p[0] + tm[1][2] * p[1] + tm[2][2] * p[2] + tm[3][2], + ] +} + +fn det3(tm: &[[f32; 3]; 4]) -> f32 { + let [a, b, c] = [tm[0], tm[1], tm[2]]; + a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + + a[2] * (b[0] * c[1] - b[1] * c[0]) +} + +fn box_tris(n: &CollisionNode) -> Vec<([f32; 3], [f32; 3], [f32; 3])> { + let [lo, hi] = n.bbox; + let c = |i: usize| { + n.to_object([ + if i & 1 == 0 { lo[0] } else { hi[0] }, + if i & 2 == 0 { lo[1] } else { hi[1] }, + if i & 4 == 0 { lo[2] } else { hi[2] }, + ]) + }; + let pts: Vec<[f32; 3]> = (0..8).map(c).collect(); + let quads = [[0, 2, 3, 1], [4, 5, 7, 6], [0, 1, 5, 4], [2, 6, 7, 3], [0, 4, 6, 2], [1, 3, 7, 5]]; + let mut tris = Vec::with_capacity(12); + for q in quads { + tris.push((pts[q[0]], pts[q[1]], pts[q[2]])); + tris.push((pts[q[0]], pts[q[2]], pts[q[3]])); + } + tris +} + +fn capsule_tris(a: [f32; 3], b: [f32; 3], r: f32) -> Vec<([f32; 3], [f32; 3], [f32; 3])> { + let dx = b[0] - a[0]; + let dy = b[1] - a[1]; + let dz = b[2] - a[2]; + let len = (dx * dx + dy * dy + dz * dz).sqrt(); + let axis = if len > 1e-4 { [dx / len, dy / len, dz / len] } else { [0.0, 1.0, 0.0] }; + let up = if axis[1].abs() < 0.9 { [0.0, 1.0, 0.0] } else { [1.0, 0.0, 0.0] }; + let cross = |u: [f32; 3], v: [f32; 3]| { + [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]] + }; + let norm = |v: [f32; 3]| { + let l = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt().max(1e-6); + [v[0] / l, v[1] / l, v[2] / l] + }; + let u = norm(cross(axis, up)); + let v = norm(cross(axis, u)); + + let segs = 6usize; + let mut ring_a = Vec::with_capacity(segs); + let mut ring_b = Vec::with_capacity(segs); + for i in 0..segs { + let ang = (i as f32) * std::f32::consts::TAU / (segs as f32); + let (ca, sa) = (ang.cos() * r, ang.sin() * r); + let off = [u[0] * ca + v[0] * sa, u[1] * ca + v[1] * sa, u[2] * ca + v[2] * sa]; + ring_a.push([a[0] + off[0], a[1] + off[1], a[2] + off[2]]); + ring_b.push([b[0] + off[0], b[1] + off[1], b[2] + off[2]]); + } + let mut tris = Vec::with_capacity(segs * 2); + for i in 0..segs { + let j = (i + 1) % segs; + tris.push((ring_a[i], ring_a[j], ring_b[j])); + tris.push((ring_a[i], ring_b[j], ring_b[i])); + } + tris +} + +fn tri_normal_y(a: [f32; 3], b: [f32; 3], c: [f32; 3]) -> f32 { + let e1 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; + let e2 = [c[0] - a[0], c[1] - a[1], c[2] - a[2]]; + let nx = e1[1] * e2[2] - e1[2] * e2[1]; + let ny = e1[2] * e2[0] - e1[0] * e2[2]; + let nz = e1[0] * e2[1] - e1[1] * e2[0]; + let len = (nx * nx + ny * ny + nz * nz).sqrt(); + if len > 1e-6 { (ny / len).abs() } else { 0.0 } +} + +fn build_cached_collision(c: &Collision, meta: &PoolMeta) -> Option { + if meta.is_soft_foliage { + return None; + } + let mut tris = Vec::new(); + for n in &c.nodes { + // Vehicles only collide with physics_collidable nodes (behavior bit 1). + if !n.physics_collidable() { + continue; + } + let mat_soft = !n.materials.is_empty() + && n.materials.iter().all(|m| { + let ml = m.to_lowercase(); + ml.contains("bush") || ml.contains("foliage") || ml.contains("leaves") || ml.contains("glass") + }); + if mat_soft { + continue; + } + let scale = det3(&n.tm).abs().cbrt(); + match n.kind { + NodeKind::Mesh | NodeKind::Convex => { + if n.indices.len() < 3 { + continue; + } + for t in n.indices.chunks_exact(3) { + let p0 = n.to_object(n.positions[t[0] as usize]); + let p1 = n.to_object(n.positions[t[1] as usize]); + let p2 = n.to_object(n.positions[t[2] as usize]); + let cls = if meta.is_bridge && tri_normal_y(p0, p1, p2) >= 0.72 { + OBS_BRIDGE_DECK + } else if meta.is_crushable { + OBS_CRUSHABLE + } else { + OBS_HARD_SOLID + }; + tris.push((p0, p1, p2, cls)); + } + } + NodeKind::Box => { + for (p0, p1, p2) in box_tris(n) { + let cls = if meta.is_bridge && tri_normal_y(p0, p1, p2) >= 0.72 { + OBS_BRIDGE_DECK + } else if meta.is_crushable { + OBS_CRUSHABLE + } else { + OBS_HARD_SOLID + }; + tris.push((p0, p1, p2, cls)); + } + } + NodeKind::Capsule => { + if let Some(cap) = n.capsule { + let a = n.to_object(cap.a); + let b = n.to_object(cap.b); + let r = (cap.radius * scale).max(0.08); + let cls = if r >= 0.28 { OBS_TREE_THICK } else { OBS_TREE_THIN }; + for (p0, p1, p2) in capsule_tris(a, b, r) { + tris.push((p0, p1, p2, cls)); + } + } + } + NodeKind::Points | NodeKind::Sphere => {} + } + } + if tris.is_empty() { + return None; + } + let bmin = c.bbox[0]; + let bmax = c.bbox[1]; + let max_r = [bmin[0].abs().max(bmax[0].abs()), bmin[2].abs().max(bmax[2].abs())] + .iter() + .copied() + .fold(0.0f32, f32::max) + * 1.42; + Some(CachedCollision { max_radius: max_r.max(4.0), tris }) +} + +fn crop_heightmap(hm: &Heightmap, min_x: f32, min_z: f32, max_x: f32, max_z: f32) -> (u32, u32, [f32; 2], Vec) { + let cs = hm.cell_size; + let x0 = (((min_x - hm.origin[0]) / cs).floor() as i32).clamp(0, (hm.width as i32) - 2) as u32; + let z0 = (((min_z - hm.origin[1]) / cs).floor() as i32).clamp(0, (hm.height as i32) - 2) as u32; + let x1 = (((max_x - hm.origin[0]) / cs).ceil() as i32).clamp((x0 as i32) + 1, (hm.width as i32) - 1) as u32; + let z1 = (((max_z - hm.origin[1]) / cs).ceil() as i32).clamp((z0 as i32) + 1, (hm.height as i32) - 1) as u32; + let cw = x1 - x0 + 1; + let ch = z1 - z0 + 1; + let mut heights = Vec::with_capacity((cw * ch) as usize); + for z in z0..=z1 { + let row = (z as usize) * (hm.width as usize); + for x in x0..=x1 { + heights.push(hm.metres(hm.data[row + x as usize])); + } + } + let origin = [hm.origin[0] + (x0 as f32) * cs, hm.origin[1] + (z0 as f32) * cs]; + (cw, ch, origin, heights) +} + +fn main() -> Result<()> { + let t0 = Instant::now(); + let (game_dir, pois_path, out_path) = parse_args()?; + let pois: LevelPois = serde_json::from_str( + &fs::read_to_string(&pois_path).with_context(|| format!("reading {}", pois_path.display()))?, + )?; + + let level_file = game_dir.join(&pois.level_path); + let raw = fs::read(&level_file).with_context(|| format!("reading {}", level_file.display()))?; + let level = Level::parse(&raw).with_context(|| format!("parsing {}", level_file.display()))?; + + let ever_sha1 = level.export_info()?.and_then(|e| e.sha1).unwrap_or([0u8; 20]); + let aces_meta = read_aces_meta(&game_dir, &pois.level); + let water_level = aces_meta.water_level; + + if let Some(pm) = level.phys_map_info()? { + println!( + " LMp2: {}x{} scale={:.2}m origin=({:.0},{:.0}) mats={:?}", + pm.size[0], + pm.size[1], + pm.metres_per_texel, + pm.world_origin[0], + pm.world_origin[1], + &pm.materials[..pm.materials.len().min(10)] + ); + } + + let hm = level.heightmap()?.with_context(|| format!("{} has no HM2 heightmap", pois.level))?; + let (cw, ch, crop_origin, heights) = crop_heightmap( + &hm, + pois.bounds_min[0], + pois.bounds_min[1], + pois.bounds_max[0], + pois.bounds_max[1], + ); + let crop_max_x = crop_origin[0] + ((cw - 1) as f32) * hm.cell_size; + let crop_max_z = crop_origin[1] + ((ch - 1) as f32) * hm.cell_size; + println!( + "{}: HM2 full={}x{} cs={:.2}m -> crop={}x{} [{:.0}..{:.0}]x[{:.0}..{:.0}] water={:.2}m", + pois.level, + hm.width, + hm.height, + hm.cell_size, + cw, + ch, + crop_origin[0], + crop_max_x, + crop_origin[1], + crop_max_z, + water_level + ); + + // Collect distinct placed RendInst pools from RIGz + let layers = level.rendinst_layers()?; + let mut pool_names: HashSet = HashSet::new(); + for layer in &layers { + for (pool, cnt) in layer.pools.iter().zip(layer.counts()) { + if cnt > 0 { + pool_names.insert(pool.name.clone()); + } + } + } + + let res_index = ResourceIndex::build(&game_dir, &[COLLISION])?; + + // Group collision loads by .grp file so each pack is read once + let mut by_pack: HashMap> = HashMap::new(); + let mut no_collision = 0usize; + for name in &pool_names { + let res_name = format!("{name}_collision"); + if let Some(p) = res_index.find(COLLISION, &res_name) { + by_pack.entry(p.to_path_buf()).or_default().push((name.clone(), res_name)); + } else { + no_collision += 1; + } + } + + let mut cached_cols: HashMap = HashMap::new(); + for (pack_path, items) in &by_pack { + let Ok(bytes) = fs::read(pack_path) else { continue }; + let Ok(pack) = GrpPack::parse(&bytes) else { continue }; + for (pool_name, res_name) in items { + let Some(res) = pack.find(res_name, COLLISION) else { continue }; + let Ok(col) = Collision::parse(res_name, pack.data(res)) else { continue }; + let imp = aces_meta.destr_impulse.get(&pool_name.to_lowercase()).copied(); + let meta = classify_pool(pool_name, imp); + if let Some(cc) = build_cached_collision(&col, &meta) { + cached_cols.insert(pool_name.clone(), cc); + } + } + } + + // Stream placed collision triangles inside the cropped battle area + let pad = 16.0; + let mut verts: Vec<[f32; 3]> = Vec::with_capacity(200_000); + let mut tris: Vec<([u32; 3], u8)> = Vec::with_capacity(100_000); + let mut inst_used = 0usize; + let mut cls_counts = [0usize; 5]; + + for layer in &layers { + let instances = layer.instances()?; + for inst in instances { + let Some(pool) = layer.pools.get(inst.pool) else { continue }; + let Some(cc) = cached_cols.get(&pool.name) else { continue }; + let pos = inst.tm[3]; + // Quick XZ culling using instance scale + object bounding radius + let sx = (inst.tm[0][0].powi(2) + inst.tm[0][1].powi(2) + inst.tm[0][2].powi(2)).sqrt(); + let sz = (inst.tm[2][0].powi(2) + inst.tm[2][1].powi(2) + inst.tm[2][2].powi(2)).sqrt(); + let rad = cc.max_radius * sx.max(sz).max(1.0); + if pos[0] + rad < crop_origin[0] - pad + || pos[0] - rad > crop_max_x + pad + || pos[2] + rad < crop_origin[1] - pad + || pos[2] - rad > crop_max_z + pad + { + continue; + } + inst_used += 1; + for &(p0, p1, p2, cls) in &cc.tris { + let w0 = transform_point(&inst.tm, p0); + let w1 = transform_point(&inst.tm, p1); + let w2 = transform_point(&inst.tm, p2); + let base = verts.len() as u32; + verts.push(w0); + verts.push(w1); + verts.push(w2); + tris.push(([base, base + 1, base + 2], cls)); + if (cls as usize) < cls_counts.len() { + cls_counts[cls as usize] += 1; + } + } + } + } + + println!( + " RIGz: pools={} cols={} noCol={} instancesInBounds={} obsTris={} [hard={} bridge={} crush={} treeThick={} treeThin={}] ({:.2}s)", + pool_names.len(), + cached_cols.len(), + no_collision, + inst_used, + tris.len(), + cls_counts[0], + cls_counts[1], + cls_counts[2], + cls_counts[3], + cls_counts[4], + t0.elapsed().as_secs_f32() + ); + + if let Some(parent) = out_path.parent() { + fs::create_dir_all(parent)?; + } + let mut w = BufWriter::new(File::create(&out_path)?); + // WtoGeoHeader (must match native/wto-nav/wto_nav_format.h byte-for-byte) + w.write_all(WTO_GEO_MAGIC)?; + w.write_all(&WTO_GEO_VERSION.to_le_bytes())?; + w.write_all(&0u32.to_le_bytes())?; // flags + w.write_all(&ever_sha1)?; + w.write_all(&water_level.to_le_bytes())?; + w.write_all(&crop_origin[0].to_le_bytes())?; + w.write_all(&crop_origin[1].to_le_bytes())?; + w.write_all(&crop_max_x.to_le_bytes())?; + w.write_all(&crop_max_z.to_le_bytes())?; + w.write_all(&cw.to_le_bytes())?; + w.write_all(&ch.to_le_bytes())?; + w.write_all(&hm.cell_size.to_le_bytes())?; + w.write_all(&crop_origin[0].to_le_bytes())?; + w.write_all(&crop_origin[1].to_le_bytes())?; + w.write_all(&(verts.len() as u32).to_le_bytes())?; + w.write_all(&(tris.len() as u32).to_le_bytes())?; + + // Heightmap float32 samples + for h in &heights { + w.write_all(&h.to_le_bytes())?; + } + // Obstacle vertices (float32 x 3) + for v in &verts { + w.write_all(&v[0].to_le_bytes())?; + w.write_all(&v[1].to_le_bytes())?; + w.write_all(&v[2].to_le_bytes())?; + } + // Obstacle triangles (uint32 x 3 + uint8 class) + for (idx, cls) in &tris { + w.write_all(&idx[0].to_le_bytes())?; + w.write_all(&idx[1].to_le_bytes())?; + w.write_all(&idx[2].to_le_bytes())?; + w.write_all(&[*cls])?; + } + w.flush()?; + println!(" wrote {} ({:.1} MB)", out_path.display(), fs::metadata(&out_path)?.len() as f64 / (1024.0 * 1024.0)); + Ok(()) +} diff --git a/tools/navgen/mission-bounds.mts b/tools/navgen/mission-bounds.mts new file mode 100644 index 0000000..4ea682a --- /dev/null +++ b/tools/navgen/mission-bounds.mts @@ -0,0 +1,278 @@ +/** + * Extract union battle-area bounds, tank spawn points, and capture zones for ground + * levels from `char.vromfs.bin` (`config/mislist.blk`) and `mis.vromfs.bin` (recursively + * resolving `imports/import_record` mission templates). + * + * Usage: + * node --experimental-strip-types tools/navgen/mission-bounds.mts \ + * --game "J:\GAME\WTLab\client-2.61.0.58" \ + * --out "build\nav-work" \ + * --levels avg_berlin,avg_poland,avg_hurtgen + */ +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { readArchive, getFile, NAME_MAP_PATH } from '../../packages/vromfs/src/index.ts'; +import { decodeBlk, parseSharedNameMap, findBlock, findParam, type BlkBlock, type SharedNameContext } from '../../packages/blk/src/index.ts'; + +interface PoiPoint { + readonly name: string; + readonly x: number; + readonly y: number; + readonly z: number; + readonly radius: number; + readonly mission: string; +} + +interface LevelPois { + readonly level: string; + readonly levelPath: string; + readonly missions: readonly string[]; + readonly boundsMin: readonly [number, number]; + readonly boundsMax: readonly [number, number]; + readonly team1Spawns: readonly PoiPoint[]; + readonly team2Spawns: readonly PoiPoint[]; + readonly captureZones: readonly PoiPoint[]; +} + +function parseArgs(argv: string[]) { + let gameDir = ''; + let outDir = ''; + let levelsFilter: Set | null = null; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]!; + if (a === '--game') gameDir = argv[++i] ?? ''; + else if (a === '--out') outDir = argv[++i] ?? ''; + else if (a === '--levels') { + const raw = argv[++i] ?? ''; + levelsFilter = new Set(raw.split(',').map((s) => s.trim().toLowerCase()).filter(Boolean)); + } + } + if (!gameDir || !outDir) { + throw new Error('Usage: --game --out [--levels avg_berlin,avg_poland,avg_hurtgen]'); + } + return { gameDir: resolve(gameDir), outDir: resolve(outDir), levelsFilter }; +} + +function openPack(packPath: string) { + const arc = readArchive(readFileSync(packPath)); + const dicts = [...arc.files.keys()].filter((k) => k.endsWith('.dict')); + const dictionary = dicts.length ? arc.files.get(dicts[0]!) : undefined; + const names = arc.files.has(NAME_MAP_PATH) ? parseSharedNameMap(getFile(arc, NAME_MAP_PATH), dictionary).names : []; + const shared: SharedNameContext = { names, dictionary }; + const lowerMap = new Map(); + for (const k of arc.files.keys()) lowerMap.set(k.toLowerCase(), k); + return { + arc, + lowerMap, + has(rel: string): boolean { return lowerMap.has(rel.toLowerCase()); }, + readBlk(rel: string): BlkBlock { + const actual = lowerMap.get(rel.toLowerCase()); + if (!actual) throw new Error(`missing ${rel} in ${packPath}`); + return decodeBlk(getFile(arc, actual), shared); + }, + }; +} + +function val(b: BlkBlock | undefined, name: string): any { + const p = b ? findParam(b, name) : undefined; + return p ? (p.value as any).value : undefined; +} + +function listParams(b: BlkBlock | undefined, name: string): any[] { + if (!b) return []; + return b.params.filter((p) => p.name === name).map((p) => (p.value as any).value); +} + +function collectAreasRecursive( + misPack: ReturnType, + blkPath: string, + visited: Set, + outAreas: BlkBlock[], +) { + const key = blkPath.toLowerCase(); + if (visited.has(key) || !misPack.has(key)) return; + visited.add(key); + let blk: BlkBlock; + try { blk = misPack.readBlk(key); } catch { return; } + + const areas = findBlock(blk, 'areas'); + if (areas) { + for (const sub of areas.blocks) outAreas.push(sub); + } + const imports = findBlock(blk, 'imports'); + if (imports) { + for (const rec of imports.blocks) { + if (rec.name !== 'import_record') continue; + const impAreas = val(rec, 'importAreas'); + if (impAreas === false) continue; + const file = String(val(rec, 'file') ?? '').replace(/\\/g, '/').replace(/^\/+/, ''); + if (file) collectAreasRecursive(misPack, file, visited, outAreas); + } + } +} + +function areaCornersXZ(area: BlkBlock): { minX: number; maxX: number; minZ: number; maxZ: number; cx: number; cy: number; cz: number; rad: number } | null { + const tm = val(area, 'tm'); + if (Array.isArray(tm) && tm.length === 12) { + const cx = Number(tm[9]); + const cy = Number(tm[10]); + const cz = Number(tm[11]); + // Box extents in Dagor area tm: half-axes are 0.5 * axis vector length for Box, full radius for Sphere/Cylinder + const typeStr = String(val(area, 'type') ?? ''); + const axX = Math.abs(tm[0]) + Math.abs(tm[3]) + Math.abs(tm[6]); + const axZ = Math.abs(tm[2]) + Math.abs(tm[5]) + Math.abs(tm[8]); + const halfX = typeStr === 'Sphere' || typeStr === 'Cylinder' ? Math.hypot(tm[0], tm[1], tm[2]) : 0.5 * axX; + const halfZ = typeStr === 'Sphere' || typeStr === 'Cylinder' ? Math.hypot(tm[6], tm[7], tm[8]) : 0.5 * axZ; + const rad = Math.max(8, 0.5 * (halfX + halfZ)); + return { minX: cx - halfX, maxX: cx + halfX, minZ: cz - halfZ, maxZ: cz + halfZ, cx, cy, cz, rad }; + } + const obj = findBlock(area, 'props'); + const pos = val(area, 'pos') ?? val(obj, 'pos'); + if (Array.isArray(pos) && pos.length >= 3) { + const rad = Number(val(area, 'radius') ?? 15); + return { minX: pos[0] - rad, maxX: pos[0] + rad, minZ: pos[2] - rad, maxZ: pos[2] + rad, cx: pos[0], cy: pos[1], cz: pos[2], rad }; + } + return null; +} + +function dedupePois(pts: PoiPoint[], minDistM: number): PoiPoint[] { + const out: PoiPoint[] = []; + const d2 = minDistM * minDistM; + for (const p of pts) { + if (out.some((o) => (o.x - p.x) ** 2 + (o.z - p.z) ** 2 < d2)) continue; + out.push(p); + } + return out; +} + +function main() { + const { gameDir, outDir, levelsFilter } = parseArgs(process.argv.slice(2)); + mkdirSync(outDir, { recursive: true }); + + const charPack = openPack(join(gameDir, 'char.vromfs.bin')); + const misPack = openPack(join(gameDir, 'mis.vromfs.bin')); + + const mislist = charPack.readBlk('config/mislist.blk'); + const skirmish = findBlock(mislist, 'skirmish'); + if (!skirmish) throw new Error('config/mislist.blk missing skirmish'); + + const pathByLowerName = new Map(); + for (const k of misPack.arc.files.keys()) { + if (!k.toLowerCase().startsWith('gamedata/missions/') || !k.toLowerCase().endsWith('.blk')) continue; + const base = k.slice(k.lastIndexOf('/') + 1, -4).toLowerCase(); + pathByLowerName.set(base, k); + } + + const targetCats = new Set(['air_ground_Dom', 'air_ground_Conq', 'air_ground_Bttl']); + const missionNames = new Set(); + for (const cat of skirmish.blocks) { + if (targetCats.has(cat.name)) { + for (const m of listParams(cat, 'm')) { + if (!String(m).toLowerCase().includes('newbie')) missionNames.add(String(m)); + } + } else if (cat.name === 'test') { + for (const m of listParams(cat, 'm')) { + if (/^great_war_/i.test(String(m))) missionNames.add(String(m)); + } + } + } + + interface Acc { + levelPath: string; + missions: string[]; + minX: number; maxX: number; minZ: number; maxZ: number; + hasBattleBox: boolean; + t1Spawns: PoiPoint[]; + t2Spawns: PoiPoint[]; + caps: PoiPoint[]; + } + const byLevel = new Map(); + + for (const mName of missionNames) { + const mPath = pathByLowerName.get(mName.toLowerCase()); + if (!mPath) continue; + const doc = misPack.readBlk(mPath); + const ms = findBlock(doc, 'mission_settings'); + const mis = findBlock(ms, 'mission'); + if (val(mis, 'isTanksAllowed') === false) continue; + const levelPath = String(val(mis, 'level') ?? ''); + if (!levelPath) continue; + const levelKey = levelPath.replace(/^levels\//i, '').replace(/\.bin$/i, '').toLowerCase(); + if (levelsFilter && !levelsFilter.has(levelKey)) continue; + + let acc = byLevel.get(levelKey); + if (!acc) { + acc = { + levelPath, missions: [], + minX: Infinity, maxX: -Infinity, minZ: Infinity, maxZ: -Infinity, + hasBattleBox: false, t1Spawns: [], t2Spawns: [], caps: [], + }; + byLevel.set(levelKey, acc); + } + acc.missions.push(mName); + + const areas: BlkBlock[] = []; + collectAreasRecursive(misPack, mPath, new Set(), areas); + + for (const a of areas) { + const n = a.name.toLowerCase(); + // Ignore aircraft/heli spawns & zones + if (/air|heli|bomber|fighter|carrier|ship|boat|naval|sea/.test(n)) continue; + const box = areaCornersXZ(a); + if (!box) continue; + + if (n.includes('battle_area') && !n.includes('air') && !n.includes('ship')) { + const w = box.maxX - box.minX; + const h = box.maxZ - box.minZ; + if (w >= 300 && w <= 8000 && h >= 300 && h <= 8000) { + acc.minX = Math.min(acc.minX, box.minX); + acc.maxX = Math.max(acc.maxX, box.maxX); + acc.minZ = Math.min(acc.minZ, box.minZ); + acc.maxZ = Math.max(acc.maxZ, box.maxZ); + acc.hasBattleBox = true; + } + } else if (n.includes('capture_area') || n.includes('capture_zone') || n.includes('cap_zone')) { + if (!n.includes('brief') && box.rad >= 5 && box.rad <= 250) { + acc.caps.push({ name: a.name, x: box.cx, y: box.cy, z: box.cz, radius: box.rad, mission: mName }); + } + } else if (n.includes('tankspawn') || (n.includes('spawn') && /t1|t2|team1|team2|tank/.test(n))) { + if (n.includes('brief')) continue; + if (n.includes('t1_') || n.includes('team1') || n.includes('_t1')) { + acc.t1Spawns.push({ name: a.name, x: box.cx, y: box.cy, z: box.cz, radius: box.rad, mission: mName }); + } else if (n.includes('t2_') || n.includes('team2') || n.includes('_t2')) { + acc.t2Spawns.push({ name: a.name, x: box.cx, y: box.cy, z: box.cz, radius: box.rad, mission: mName }); + } + } + } + } + + for (const [levelKey, acc] of byLevel) { + const t1 = dedupePois(acc.t1Spawns, 90); + const t2 = dedupePois(acc.t2Spawns, 90); + const caps = dedupePois(acc.caps, 30); + // Ensure all spawns & caps are covered inside bounds (with 160m margin) + for (const p of [...t1, ...t2, ...caps]) { + acc.minX = Math.min(acc.minX, p.x - 160); + acc.maxX = Math.max(acc.maxX, p.x + 160); + acc.minZ = Math.min(acc.minZ, p.z - 160); + acc.maxZ = Math.max(acc.maxZ, p.z + 160); + } + // Expand battle-area union by 120m safety padding + const margin = 120; + const out: LevelPois = { + level: levelKey, + levelPath: acc.levelPath, + missions: acc.missions.sort(), + boundsMin: [Math.floor(acc.minX - margin), Math.floor(acc.minZ - margin)], + boundsMax: [Math.ceil(acc.maxX + margin), Math.ceil(acc.maxZ + margin)], + team1Spawns: t1, + team2Spawns: t2, + captureZones: caps, + }; + const outPath = join(outDir, `${levelKey}.pois.json`); + writeFileSync(outPath, `${JSON.stringify(out, null, 2)}\n`, 'utf8'); + console.log(`${levelKey}: missions=${out.missions.length} bounds=[${out.boundsMin[0]}..${out.boundsMax[0]}] x [${out.boundsMin[1]}..${out.boundsMax[1]}] (${out.boundsMax[0] - out.boundsMin[0]}m x ${out.boundsMax[1] - out.boundsMin[1]}m) t1Spawns=${t1.length} t2Spawns=${t2.length} caps=${caps.length}`); + } +} + +main(); diff --git a/tools/navgen/render-preview.py b/tools/navgen/render-preview.py new file mode 100644 index 0000000..d83112d --- /dev/null +++ b/tools/navgen/render-preview.py @@ -0,0 +1,252 @@ +"""Render top-down PNG inspection maps (`*_nav.png` and `*_cover.png`) from `.preview.bin` + `.pois.json`. +Zero external dependencies (Python stdlib `struct` + `zlib` only). +""" +import argparse +import json +import math +import os +import struct +import zlib + + +def write_png(path: str, width: int, height: int, rgb: bytearray) -> None: + def chunk(tag: bytes, data: bytes) -> bytes: + crc = zlib.crc32(tag + data) & 0xFFFFFFFF + return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", crc) + + raw = bytearray() + stride = width * 3 + for y in range(height): + raw.append(0) + row = y * stride + raw.extend(rgb[row : row + stride]) + ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0) + png = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(bytes(raw), 6)) + chunk(b"IEND", b"") + os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) + with open(path, "wb") as f: + f.write(png) + + +def set_px(rgb: bytearray, w: int, h: int, x: int, y: int, r: int, g: int, b: int) -> None: + if 0 <= x < w and 0 <= y < h: + idx = (y * w + x) * 3 + rgb[idx] = r + rgb[idx + 1] = g + rgb[idx + 2] = b + + +def draw_line(rgb: bytearray, w: int, h: int, x0: int, y0: int, x1: int, y1: int, col, thick: int = 1) -> None: + dx = abs(x1 - x0) + dy = abs(y1 - y0) + sx = 1 if x0 < x1 else -1 + sy = 1 if y0 < y1 else -1 + err = dx - dy + r, g, b = col + while True: + for oy in range(-thick // 2, thick // 2 + 1): + for ox in range(-thick // 2, thick // 2 + 1): + set_px(rgb, w, h, x0 + ox, y0 + oy, r, g, b) + if x0 == x1 and y0 == y1: + break + e2 = 2 * err + if e2 > -dy: + err -= dy + x0 += sx + if e2 < dx: + err += dx + y0 += sy + + +def draw_circle(rgb: bytearray, w: int, h: int, cx: int, cy: int, rad: int, col, fill: bool = False) -> None: + r, g, b = col + r2 = rad * rad + for dy in range(-rad, rad + 1): + for dx in range(-rad, rad + 1): + d2 = dx * dx + dy * dy + if fill and d2 <= r2: + set_px(rgb, w, h, cx + dx, cy + dy, r, g, b) + elif not fill and abs(d2 - r2) <= max(2, rad * 2): + set_px(rgb, w, h, cx + dx, cy + dy, r, g, b) + + +def draw_square(rgb: bytearray, w: int, h: int, cx: int, cy: int, half: int, col) -> None: + r, g, b = col + for dy in range(-half, half + 1): + for dx in range(-half, half + 1): + set_px(rgb, w, h, cx + dx, cy + dy, r, g, b) + + +def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("--preview", required=True) + ap.add_argument("--pois", required=True) + ap.add_argument("--out-dir", required=True) + ap.add_argument("--name", required=True) + args = ap.parse_args() + + with open(args.preview, "rb") as f: + data = f.read() + with open(args.pois, "r", encoding="utf-8") as f: + pois = json.load(f) + + assert data[:8] == b"WTOPREV1", "bad preview magic" + off = 8 + pw, ph, min_x, min_z, max_x, max_z, water_y = struct.unpack_from(" 0 and tac_rows > 0 else 0 + if fl & 16: + cr, cg, cb = 20, 48, 95 + elif fl & 2: + cr = min(255, int(base * 0.85 + exp_v * 0.18)) + cg = min(255, int(base * 0.90 + 20)) + cb = min(255, int(base * 0.85)) + else: + cr, cg, cb = 26, 26, 30 + cov_rgb[idx] = cr + cov_rgb[idx + 1] = cg + cov_rgb[idx + 2] = cb + + # Overlay sample Detour paths (bright cyan) on nav map + for path in paths: + for i in range(len(path) - 1): + x0, y0 = world_to_px(*path[i]) + x1, y1 = world_to_px(*path[i + 1]) + draw_line(nav_rgb, pw, ph, x0, y0, x1, y1, (0, 245, 255), thick=2) + + # Overlay spawns & capture zones on BOTH maps + for rgb in (nav_rgb, cov_rgb): + for sp in pois.get("team1Spawns", []): + x, y = world_to_px(sp["x"], sp["z"]) + draw_square(rgb, pw, ph, x, y, 5, (40, 130, 255)) + draw_square(rgb, pw, ph, x, y, 2, (255, 255, 255)) + for sp in pois.get("team2Spawns", []): + x, y = world_to_px(sp["x"], sp["z"]) + draw_square(rgb, pw, ph, x, y, 5, (255, 65, 65)) + draw_square(rgb, pw, ph, x, y, 2, (255, 255, 255)) + for cap in pois.get("captureZones", []): + x, y = world_to_px(cap["x"], cap["z"]) + rad_px = max(8, int(cap.get("radius", 25.0) / max(1.0, max_x - min_x) * pw)) + draw_circle(rgb, pw, ph, x, y, rad_px, (255, 215, 0), fill=False) + draw_circle(rgb, pw, ph, x, y, 4, (255, 230, 40), fill=True) + + # Overlay covers on cover map: Blue=FULL, Green=HULLDOWN, Yellow=PEEK + for c in covers: + px_w, py_w, pz_w = c[0], c[1], c[2] + dx, dz = c[3], c[4] + peek_l = (c[7], c[9]) + peek_r = (c[10], c[12]) + kind = c[16] + has_pl, has_pr = c[17], c[18] + x, y = world_to_px(px_w, pz_w) + col = (60, 165, 255) if kind == 1 else (55, 240, 100) + draw_circle(cov_rgb, pw, ph, x, y, 2, col, fill=True) + # Direction tick pointing toward blocked threat + x2, y2 = world_to_px(px_w + dx * 8.0, pz_w + dz * 8.0) + draw_line(cov_rgb, pw, ph, x, y, x2, y2, col, thick=1) + if has_pl: + lx, ly = world_to_px(*peek_l) + draw_circle(cov_rgb, pw, ph, lx, ly, 1, (255, 240, 60), fill=True) + if has_pr: + rx2, ry2 = world_to_px(*peek_r) + draw_circle(cov_rgb, pw, ph, rx2, ry2, 1, (255, 240, 60), fill=True) + + nav_out = os.path.join(args.out_dir, f"{args.name}_nav.png") + cov_out = os.path.join(args.out_dir, f"{args.name}_cover.png") + write_png(nav_out, pw, ph, nav_rgb) + write_png(cov_out, pw, ph, cov_rgb) + print(f"Rendered {nav_out} and {cov_out} (covers={len(covers)}, paths={len(paths)})") + + +if __name__ == "__main__": + main() From 4191d59168d13fd7d58d6e1158d73004da62b6b5 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:36:07 +0800 Subject: [PATCH 02/19] feat(navgen): bake road materials and directional cover Decode LMp2 terrain materials and decals into navigable road areas. Preserve usable cover bearings and verify left and right corner approaches independently on the standard tank mesh. Verified with Rust and MSVC builds, TypeScript checks, and offline baking on Berlin, Poland, and Hurtgen for 2.61.0.58. --- apps/server/tuning/ground-ai.jsonc | 8 + native/wto-nav/wto_nav_format.h | 12 +- tools/navgen/bake/bake.cpp | 486 +++++++++++++++------------ tools/navgen/extract/Cargo.lock | 2 + tools/navgen/extract/Cargo.toml | 2 + tools/navgen/extract/src/main.rs | 21 +- tools/navgen/extract/src/phys_map.rs | 318 ++++++++++++++++++ tools/navgen/mission-bounds.mts | 21 +- tools/navgen/render-preview.py | 33 +- 9 files changed, 662 insertions(+), 241 deletions(-) create mode 100644 tools/navgen/extract/src/phys_map.rs diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index 9270c1d..723df8f 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -94,6 +94,14 @@ "ridgeMaxShots": 6 }, + // Offline map baking parameters. These are copied into the generator's per-level POI input. + "coverMap": { + "minCoverHeightM": 1.55, + "peekMinM": 3.5, + "peekMaxM": 6.0, + "retreatMinM": 8.0 + }, + "navigation": { // "vehicle_phys" uses custom inputs with native ownership. "movesys" keeps stock movement. "driveMode": "vehicle_phys", diff --git a/native/wto-nav/wto_nav_format.h b/native/wto-nav/wto_nav_format.h index b955b01..07aa7f5 100644 --- a/native/wto-nav/wto_nav_format.h +++ b/native/wto-nav/wto_nav_format.h @@ -15,6 +15,7 @@ extern "C" { #define WTO_GEO_MAGIC "WTOGEO\0\1" #define WTO_GEO_VERSION 1u +#define WTO_GEO_FLAG_ROAD_MASK 0x01u #define WTO_NAV_MAGIC "WTONAV\0\1" #define WTO_NAV_VERSION 1u @@ -70,7 +71,7 @@ enum WtoCoverKind { typedef struct WtoGeoHeader { char magic[8]; /* WTO_GEO_MAGIC */ uint32_t version; /* WTO_GEO_VERSION */ - uint32_t flags; + uint32_t flags; /* WTO_GEO_FLAG_* */ uint8_t everSha1[20]; /* Built-in SHA-1 from DBLD eVER block */ float waterLevel; /* Level water_level in metres (-1e6 if none) */ float boundsMin[2]; /* World XZ crop min (battle area union + margin) */ @@ -83,7 +84,14 @@ typedef struct WtoGeoHeader { uint32_t obsTriCount; /* Number of obstacle triangles (uint32[3] + uint8 class) */ } WtoGeoHeader; -/* Baked tank cover point (48 bytes). */ +/* Optional trailer after obstacle triangles, followed by size*size uint8 road mask cells. */ +typedef struct WtoGeoRoadMask { + uint32_t size; + float origin[2]; /* World XZ of the first LMp2 cell */ + float cellSize; +} WtoGeoRoadMask; + +/* Baked tank cover point (68 bytes). */ typedef struct WtoCoverPoint { float pos[3]; /* World XYZ parking position behind cover */ float coverDir[2]; /* Unit XZ vector pointing FROM pos TOWARD the blocked threat */ diff --git a/tools/navgen/bake/bake.cpp b/tools/navgen/bake/bake.cpp index 8c1ef07..2dcfb63 100644 --- a/tools/navgen/bake/bake.cpp +++ b/tools/navgen/bake/bake.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include @@ -47,7 +48,15 @@ struct PoiPt { float x, y, z, radius; }; +struct CoverBake { + float minCoverHeightM; + float peekMinM; + float peekMaxM; + float retreatMinM; +}; + struct PoisData { + CoverBake cover{}; std::vector t1Spawns; std::vector t2Spawns; std::vector caps; @@ -74,15 +83,29 @@ static constexpr float kTileWorldSize = kTileSize * kCellSize; static constexpr float kShallowWaterMaxM = 0.60f; static constexpr float kShallowWaterMinM = 0.05f; static constexpr float kRoughSlopeDeg = 18.0f; +static constexpr float kCoverScanM = 5.2f; +static constexpr float kPeekSightM = 14.0f; +static constexpr float kHullDownSightM = 22.0f; +static constexpr float kCoverHeightToleranceM = 1.2f; struct GeoData { WtoGeoHeader hdr{}; std::vector heights; + WtoGeoRoadMask roads{}; + std::vector roadCells; std::vector obsVerts; std::vector obsTris; float minY = 1e9f; float maxY = -1e9f; + bool isRoad(float wx, float wz) const { + if (roadCells.empty()) return false; + float x = (wx - roads.origin[0]) / roads.cellSize; + float z = (wz - roads.origin[1]) / roads.cellSize; + if (x < 0.0f || z < 0.0f || x >= roads.size || z >= roads.size) return false; + return roadCells[(size_t)z * roads.size + (size_t)x] != 0; + } + float sampleHeight(float wx, float wz) const { float fx = (wx - hdr.hmOrigin[0]) / hdr.hmCellSize; float fz = (wz - hdr.hmOrigin[1]) / hdr.hmCellSize; @@ -121,6 +144,15 @@ static bool loadGeo(const std::string &path, GeoData &out) { in.read(reinterpret_cast(&cls), 1); out.obsTris[i] = { idx[0], idx[1], idx[2], cls }; } + if (out.hdr.flags & WTO_GEO_FLAG_ROAD_MASK) { + in.read(reinterpret_cast(&out.roads), sizeof(WtoGeoRoadMask)); + // Same allocation limit as the extractor. + if (!in || out.roads.size == 0 || out.roads.size > 8192 || + !(out.roads.cellSize > 0.0f) || !std::isfinite(out.roads.cellSize) || + !std::isfinite(out.roads.origin[0]) || !std::isfinite(out.roads.origin[1])) return false; + out.roadCells.resize((size_t)out.roads.size * out.roads.size); + in.read(reinterpret_cast(out.roadCells.data()), out.roadCells.size()); + } if (!in) return false; for (float h : out.heights) { @@ -142,6 +174,17 @@ static bool loadGeo(const std::string &path, GeoData &out) { return true; } +static float readJsonNumber(const std::string &json, const char *key, float fallback) { + size_t pos = json.find(std::string("\"") + key + "\""); + if (pos == std::string::npos) return fallback; + pos = json.find(':', pos); + if (pos == std::string::npos) return fallback; + const char *start = json.c_str() + pos + 1; + char *end = nullptr; + float value = std::strtof(start, &end); + return end != start && std::isfinite(value) ? value : fallback; +} + /* Minimal JSON array extractor for `.pois.json` (team1Spawns / team2Spawns / captureZones). */ static void parsePoiArray(const std::string &json, const std::string &key, std::vector &out) { std::string needle = "\"" + key + "\""; @@ -156,14 +199,6 @@ static void parsePoiArray(const std::string &json, const std::string &key, std:: else if (json[i] == ']') { depth--; if (depth == 0) break; } } std::string slice = json.substr(lb, i - lb + 1); - auto readNum = [](const std::string &obj, const char *field, float def) -> float { - std::string fn = std::string("\"") + field + "\""; - size_t p = obj.find(fn); - if (p == std::string::npos) return def; - p = obj.find(':', p); - if (p == std::string::npos) return def; - return std::strtof(obj.c_str() + p + 1, nullptr); - }; auto readStr = [](const std::string &obj, const char *field) -> std::string { std::string fn = std::string("\"") + field + "\""; size_t p = obj.find(fn); @@ -182,10 +217,10 @@ static void parsePoiArray(const std::string &json, const std::string &key, std:: std::string obj = slice.substr(ob, cb - ob + 1); PoiPt pt; pt.name = readStr(obj, "name"); - pt.x = readNum(obj, "x", 0.0f); - pt.y = readNum(obj, "y", 0.0f); - pt.z = readNum(obj, "z", 0.0f); - pt.radius = readNum(obj, "radius", 15.0f); + pt.x = readJsonNumber(obj, "x", 0.0f); + pt.y = readJsonNumber(obj, "y", 0.0f); + pt.z = readJsonNumber(obj, "z", 0.0f); + pt.radius = readJsonNumber(obj, "radius", 15.0f); out.push_back(pt); cur = cb + 1; } @@ -195,6 +230,18 @@ static bool loadPois(const std::string &path, PoisData &out) { std::ifstream in(path); if (!in) return false; std::string content((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + out.cover = { + readJsonNumber(content, "minCoverHeightM", -1.0f), + readJsonNumber(content, "peekMinM", -1.0f), + readJsonNumber(content, "peekMaxM", -1.0f), + readJsonNumber(content, "retreatMinM", -1.0f) + }; + if (out.cover.minCoverHeightM <= 0.0f || out.cover.peekMinM <= 0.0f || + out.cover.peekMaxM < out.cover.peekMinM || out.cover.peekMaxM >= kTileWorldSize || + out.cover.retreatMinM <= 0.0f || out.cover.retreatMinM >= kTileWorldSize) { + std::fprintf(stderr, "Invalid cover baking settings in %s. Regenerate it with mission-bounds.mts.\n", path.c_str()); + return false; + } parsePoiArray(content, "team1Spawns", out.t1Spawns); parsePoiArray(content, "team2Spawns", out.t2Spawns); parsePoiArray(content, "captureZones", out.caps); @@ -254,6 +301,129 @@ static bool hfTraceBand(const rcHeightfield &hardHf, const GeoData &geo, return false; } +static int coverBorderCells(const CoverBake &tuning) { + float reach = std::max(kHullDownSightM, std::hypot(tuning.peekMaxM, kPeekSightM)); + return (int)std::ceil(reach / kCellSize) + 1; +} + +static bool isCoverArea(unsigned char area) { + return area != RC_NULL_AREA && area != WTO_AREA_DEEP_WATER && area != WTO_AREA_SHALLOW_WATER; +} + +static bool isCoverBoundary(const rcCompactHeightfield &field, int x, int z, const rcCompactSpan &span) { + for (int dir = 0; dir < 4; ++dir) { + int connection = rcGetCon(span, dir); + if (connection == RC_NOT_CONNECTED) return true; + int nx = x + rcGetDirOffsetX(dir); + int nz = z + rcGetDirOffsetY(dir); + if (field.areas[field.cells[nx + nz * field.width].index + connection] == RC_NULL_AREA) return true; + } + return false; +} + +static bool findCornerPeek( + const rcCompactHeightfield &field, const rcHeightfield &hard, const GeoData &geo, + const CoverBake &tuning, const WtoCoverPoint &cover, float side, float (&point)[3] +) { + const float dx = cover.coverDir[0], dz = cover.coverDir[1]; + for (float distance = tuning.peekMinM; distance <= tuning.peekMaxM; distance += field.cs) { + const float x = cover.pos[0] - dz * side * distance; + const float z = cover.pos[2] + dx * side * distance; + const int gx = (int)std::floor((x - field.bmin[0]) / field.cs); + const int gz = (int)std::floor((z - field.bmin[2]) / field.cs); + if (gx < 0 || gz < 0 || gx >= field.width || gz >= field.height) break; + + const rcCompactCell &cell = field.cells[gx + gz * field.width]; + for (unsigned int i = cell.index; i < cell.index + cell.count; ++i) { + if (!isCoverArea(field.areas[i])) continue; + float y = field.bmin[1] + field.spans[i].y * field.ch; + if (std::fabs(y - cover.pos[1]) > kCoverHeightToleranceM) continue; + if (hfTraceBand(hard, geo, x, z, dx, dz, kPeekSightM, y + 1.8f, y + 2.6f)) continue; + point[0] = x; + point[1] = y; + point[2] = z; + return true; + } + } + return false; +} + +static void bakeTileCovers( + const rcCompactHeightfield &field, const rcHeightfield &hard, const GeoData &geo, + const rcConfig &cfg, const CoverBake &tuning, std::vector &covers +) { + static const float directions[8][2] = { + { 1.0f, 0.0f }, { 0.70710678f, 0.70710678f }, { 0.0f, 1.0f }, { -0.70710678f, 0.70710678f }, + { -1.0f, 0.0f }, { -0.70710678f, -0.70710678f }, { 0.0f, -1.0f }, { 0.70710678f, -0.70710678f } + }; + const int innerEnd = cfg.borderSize + cfg.tileSize; + for (int z = cfg.borderSize; z < innerEnd; ++z) { + for (int x = cfg.borderSize; x < innerEnd; ++x) { + const rcCompactCell &cell = field.cells[x + z * field.width]; + for (unsigned int i = cell.index; i < cell.index + cell.count; ++i) { + const rcCompactSpan &span = field.spans[i]; + if (!isCoverArea(field.areas[i]) || !isCoverBoundary(field, x, z, span)) continue; + Vec3 pos{ cfg.bmin[0] + (x + 0.5f) * cfg.cs, cfg.bmin[1] + span.y * cfg.ch, + cfg.bmin[2] + (z + 0.5f) * cfg.cs }; + + // Every usable bearing goes through the same checks, including opposite faces of one object. + for (const auto &dir : directions) { + float dx = dir[0], dz = dir[1]; + int hullHits = 0, turretHits = 0; + float totalHeight = 0.0f; + for (int column = -2; column <= 2; ++column) { + float offset = column * 0.9f; // Five samples across a 3.6 m hull. + float sx = pos.x - dz * offset, sz = pos.z + dx * offset; + float top = pos.y; + if (!hfTraceBand(hard, geo, sx, sz, dx, dz, kCoverScanM, pos.y + 0.65f, pos.y + 1.80f, &top)) continue; + ++hullHits; + totalHeight += std::max(0.0f, top - pos.y); + turretHits += hfTraceBand(hard, geo, sx, sz, dx, dz, kCoverScanM, pos.y + 2.05f, pos.y + 2.85f); + } + if (hullHits < 4 || totalHeight < tuning.minCoverHeightM * hullHits) continue; + + float width = 3.6f; + for (float off : { -2.6f, 2.6f }) { + if (hfTraceBand(hard, geo, pos.x - dz * off, pos.z + dx * off, dx, dz, + kCoverScanM, pos.y + 0.65f, pos.y + 1.80f)) width += 1.0f; + } + WtoCoverPoint cover{}; + cover.pos[0] = pos.x; cover.pos[1] = pos.y; cover.pos[2] = pos.z; + cover.coverDir[0] = dx; cover.coverDir[1] = dz; + cover.halfAngleDeg = width >= 5.0f ? 42.0f : 32.0f; + cover.heightM = totalHeight / hullHits; + cover.widthM = width; + + if (turretHits >= 3) { + cover.kind = WTO_COVER_FULL; + cover.hasPeekLeft = findCornerPeek(field, hard, geo, tuning, cover, -1.0f, cover.peekLeft); + cover.hasPeekRight = findCornerPeek(field, hard, geo, tuning, cover, 1.0f, cover.peekRight); + } else { + if (hfTraceBand(hard, geo, pos.x, pos.z, dx, dz, kHullDownSightM, pos.y + 2.15f, pos.y + 2.75f)) continue; + cover.kind = WTO_COVER_HULLDOWN; + } + covers.push_back(cover); + } + } + } + } +} + +static void markRoadAreas(rcCompactHeightfield &field, const GeoData &geo) { + if (geo.roadCells.empty()) return; + for (int z = 0; z < field.height; ++z) { + const float wz = field.bmin[2] + (z + 0.5f) * field.cs; + for (int x = 0; x < field.width; ++x) { + const float wx = field.bmin[0] + (x + 0.5f) * field.cs; + if (!geo.isRoad(wx, wz)) continue; + const rcCompactCell &cell = field.cells[x + z * field.width]; + for (unsigned int i = cell.index; i < cell.index + cell.count; ++i) { + if (field.areas[i] == WTO_AREA_GROUND) field.areas[i] = WTO_AREA_ROAD; + } + } + } +} + struct BuiltTile { int tx = 0; int tz = 0; @@ -272,7 +442,7 @@ static TileBakeResult buildSingleTile( const TierSpec &tier, int tx, int tz, float mapMinX, float mapMinZ, - bool bakeCovers + const CoverBake &coverTuning, bool bakeCovers ) { TileBakeResult res; res.tile.tx = tx; @@ -293,6 +463,8 @@ static TileBakeResult buildSingleTile( cfg.maxVertsPerPoly = 6; cfg.tileSize = kTileSize; cfg.borderSize = cfg.walkableRadius + 3; + // Cover and corner rays must see hard collision on the other side of tile boundaries. + if (bakeCovers) cfg.borderSize = std::max(cfg.borderSize, coverBorderCells(coverTuning)); cfg.width = cfg.tileSize + cfg.borderSize * 2; cfg.height = cfg.tileSize + cfg.borderSize * 2; cfg.detailSampleDist = 12.0f * cfg.cs; @@ -442,139 +614,14 @@ static TileBakeResult buildSingleTile( } } - /* 3. Bake tank-qualified covers directly from eroded Tier-1 walkable boundary + hardHf */ - if (bakeCovers && hardHf) { - const int b = cfg.borderSize; - const int innerEnd = b + cfg.tileSize; - static const float kDirs[8][2] = { - { 1.0f, 0.0f }, { 0.7071f, 0.7071f }, { 0.0f, 1.0f }, { -0.7071f, 0.7071f }, - { -1.0f, 0.0f }, { -0.7071f, -0.7071f }, { 0.0f, -1.0f }, { 0.7071f, -0.7071f } - }; - for (int z = b; z < innerEnd; z += 4) { - for (int x = b; x < innerEnd; x += 4) { - const rcCompactCell &c = chf->cells[x + z * chf->width]; - for (int si = (int)c.index, ni = (int)(c.index + c.count); si < ni; ++si) { - unsigned char area = chf->areas[si]; - if (area == RC_NULL_AREA || area == WTO_AREA_DEEP_WATER || area == WTO_AREA_SHALLOW_WATER) continue; - /* Check if any 4-neighbor (at distance 1..2 cells) was eroded to RC_NULL_AREA or disconnected */ - const rcCompactSpan &s = chf->spans[si]; - bool isBoundary = false; - for (int d = 0; d < 4; ++d) { - int con = rcGetCon(s, d); - if (con == RC_NOT_CONNECTED) { isBoundary = true; break; } - int nx = x + rcGetDirOffsetX(d); - int nz = z + rcGetDirOffsetY(d); - int nsi = (int)chf->cells[nx + nz * chf->width].index + con; - if (chf->areas[nsi] == RC_NULL_AREA) { isBoundary = true; break; } - } - if (!isBoundary) continue; - - float wx = cfg.bmin[0] + (x + 0.5f) * cfg.cs; - float wy = cfg.bmin[1] + s.y * cfg.ch; - float wz = cfg.bmin[2] + (z + 0.5f) * cfg.cs; - - /* Find strongest hard-obstacle direction within 2.0..5.2 m */ - int bestDir = -1; - float bestWidth = 0.0f; - float bestHeight = 0.0f; - bool bestTurretBlocked = false; - - for (int di = 0; di < 8; ++di) { - float dx = kDirs[di][0], dz = kDirs[di][1]; - float px = -dz, pz = dx; /* tangent */ - int hullHits = 0; - int turretHits = 0; - float hSum = 0.0f; - /* 5 lateral samples across 3.6 m hull width (-1.8, -0.9, 0, +0.9, +1.8) */ - for (int li = -2; li <= 2; ++li) { - float off = li * 0.9f; - float sx = wx + px * off; - float sz = wz + pz * off; - float topY = wy; - if (hfTraceBand(*hardHf, geo, sx, sz, dx, dz, 5.2f, wy + 0.65f, wy + 1.80f, &topY)) { - hullHits++; - hSum += std::max(0.0f, topY - wy); - if (hfTraceBand(*hardHf, geo, sx, sz, dx, dz, 5.2f, wy + 2.05f, wy + 2.85f)) { - turretHits++; - } - } - } - if (hullHits < 4) continue; /* Require >= 80% hull width blocked (eliminates thin posts & narrow rocks) */ - float avgH = hSum / (float)hullHits; - if (avgH < 1.55f) continue; /* Eliminate low rocks (< 1.55 m) */ - - /* Check extra lateral span for continuous obstacle width */ - float wMeters = 3.6f; - if (hfTraceBand(*hardHf, geo, wx + px * 2.6f, wz + pz * 2.6f, dx, dz, 5.2f, wy + 0.65f, wy + 1.80f)) wMeters += 1.0f; - if (hfTraceBand(*hardHf, geo, wx - px * 2.6f, wz - pz * 2.6f, dx, dz, 5.2f, wy + 0.65f, wy + 1.80f)) wMeters += 1.0f; - - if (wMeters > bestWidth || (wMeters == bestWidth && avgH > bestHeight)) { - bestDir = di; - bestWidth = wMeters; - bestHeight = avgH; - bestTurretBlocked = (turretHits >= 3); - } - } - - if (bestDir < 0) continue; - float dx = kDirs[bestDir][0], dz = kDirs[bestDir][1]; - float px = -dz, pz = dx; - - WtoCoverPoint cp{}; - cp.pos[0] = wx; cp.pos[1] = wy; cp.pos[2] = wz; - cp.coverDir[0] = dx; cp.coverDir[1] = dz; - cp.retreatDir[0] = -dx; cp.retreatDir[1] = -dz; - cp.halfAngleDeg = bestWidth >= 5.0f ? 42.0f : 32.0f; - cp.heightM = bestHeight; - cp.widthM = bestWidth; - - if (bestTurretBlocked) { - cp.kind = WTO_COVER_FULL; - /* Probe corner peek left/right at 4.2 m */ - for (int side = -1; side <= 1; side += 2) { - float kx = wx + px * (side * 4.2f); - float kz = wz + pz * (side * 4.2f); - int kgx = (int)std::floor((kx - cfg.bmin[0]) / cfg.cs); - int kgz = (int)std::floor((kz - cfg.bmin[2]) / cfg.cs); - if (kgx >= 0 && kgz >= 0 && kgx < chf->width && kgz < chf->height) { - const rcCompactCell &kc = chf->cells[kgx + kgz * chf->width]; - bool walkablePeek = false; - float ky = wy; - for (int ksi = (int)kc.index, kni = (int)(kc.index + kc.count); ksi < kni; ++ksi) { - if (chf->areas[ksi] != RC_NULL_AREA && chf->areas[ksi] != WTO_AREA_DEEP_WATER) { - float sy = cfg.bmin[1] + chf->spans[ksi].y * cfg.ch; - if (std::fabs(sy - wy) <= 1.2f) { walkablePeek = true; ky = sy; break; } - } - } - if (walkablePeek && !hfTraceBand(*hardHf, geo, kx, kz, dx, dz, 14.0f, ky + 1.8f, ky + 2.6f)) { - if (side < 0) { - cp.hasPeekLeft = 1; - cp.peekLeft[0] = kx; cp.peekLeft[1] = ky; cp.peekLeft[2] = kz; - } else { - cp.hasPeekRight = 1; - cp.peekRight[0] = kx; cp.peekRight[1] = ky; cp.peekRight[2] = kz; - } - } - } - } - res.covers.push_back(cp); - } else { - /* Hull-down candidate: verify forward 22 m clear at turret height */ - if (!hfTraceBand(*hardHf, geo, wx, wz, dx, dz, 22.0f, wy + 2.15f, wy + 2.75f)) { - cp.kind = WTO_COVER_HULLDOWN; - res.covers.push_back(cp); - } - } - } - } - } - } + if (hardHf) bakeTileCovers(*chf, *hardHf, geo, cfg, coverTuning, res.covers); rcFreeHeightField(hardHf); hardHf = nullptr; /* Smooth isolated single-voxel slope/area noise slivers before region building */ rcMedianFilterWalkableArea(&ctx, *chf); rcMedianFilterWalkableArea(&ctx, *chf); + markRoadAreas(*chf, geo); if (!rcBuildDistanceField(&ctx, *chf) || !rcBuildRegions(&ctx, *chf, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea)) { @@ -771,74 +818,89 @@ static void markChokepoints(dtNavMesh *mesh, dtNavMeshQuery *query, float chokeD } } +static dtPolyRef verifyCoverPosition(dtNavMeshQuery &query, const dtQueryFilter &filter, float (&point)[3]) { + const float extent[3] = { kCellSize, kCoverHeightToleranceM, kCellSize }; + dtPolyRef ref = 0; + float nearest[3]; + bool overPoly = false; + if (dtStatusFailed(query.findNearestPoly(point, extent, &filter, &ref, nearest, &overPoly)) || + !ref || !overPoly || std::fabs(nearest[1] - point[1]) > kCoverHeightToleranceM) return 0; + point[1] = nearest[1]; // Keep the XZ from the collision probe. + return ref; +} + +static bool clearCoverCorridor(dtNavMeshQuery &query, const dtQueryFilter &filter, + dtPolyRef startRef, const float *start, const float *end, dtPolyRef endRef = 0) { + float fraction = 0.0f, normal[3]; + dtPolyRef trail[32]; + int count = 0; + dtStatus status = query.raycast(startRef, start, end, &filter, &fraction, normal, trail, &count, 32); + return dtStatusSucceed(status) && !dtStatusDetail(status, DT_BUFFER_TOO_SMALL) && + fraction >= 1.0f && (!endRef || (count > 0 && trail[count - 1] == endRef)); +} + +static bool verifyCover(WtoCoverPoint &cover, dtNavMeshQuery &query, + const dtQueryFilter &filter, float retreatMinM) { + dtPolyRef startRef = verifyCoverPosition(query, filter, cover.pos); + if (!startRef) return false; + + const float heading = std::atan2(-cover.coverDir[1], -cover.coverDir[0]); + bool hasRetreat = false; + for (float offset : { 0.0f, 0.45f, -0.45f }) { + float rx = std::cos(heading + offset), rz = std::sin(heading + offset); + float end[3] = { cover.pos[0] + rx * retreatMinM, cover.pos[1], cover.pos[2] + rz * retreatMinM }; + if (!clearCoverCorridor(query, filter, startRef, cover.pos, end)) continue; + cover.retreatDir[0] = rx; + cover.retreatDir[1] = rz; + hasRetreat = true; + break; + } + if (!hasRetreat) return false; + + auto validatePeek = [&](float (&point)[3]) { + dtPolyRef endRef = verifyCoverPosition(query, filter, point); + return endRef && clearCoverCorridor(query, filter, startRef, cover.pos, point, endRef); + }; + cover.hasPeekLeft = cover.hasPeekLeft && validatePeek(cover.peekLeft); + cover.hasPeekRight = cover.hasPeekRight && validatePeek(cover.peekRight); + return true; +} + +static unsigned int peekCount(const WtoCoverPoint &cover) { + return cover.hasPeekLeft + cover.hasPeekRight; +} + static std::vector filterAndDedupeCovers( - const std::vector &raw, - dtNavMeshQuery *q1 + const std::vector &raw, dtNavMeshQuery &query, const CoverBake &tuning ) { dtQueryFilter filter; filter.setIncludeFlags(WTO_FLAG_WALK); filter.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED); - const float ext[3] = { 3.0f, 4.0f, 3.0f }; + std::vector usable; + for (WtoCoverPoint cover : raw) { + if (verifyCover(cover, query, filter, tuning.retreatMinM)) usable.push_back(cover); + } - /* Sort by quality: hulldown & corner-peek full covers first, then wider/taller covers */ - std::vector order(raw.size()); - for (size_t i = 0; i < raw.size(); ++i) order[i] = i; - std::sort(order.begin(), order.end(), [&](size_t a, size_t b) { - auto score = [](const WtoCoverPoint &c) { - float s = c.widthM * 2.0f + std::min(c.heightM, 4.0f); - if (c.kind == WTO_COVER_HULLDOWN) s += 3.0f; - if (c.hasPeekLeft || c.hasPeekRight) s += 2.5f; - return s; + std::sort(usable.begin(), usable.end(), [](const WtoCoverPoint &a, const WtoCoverPoint &b) { + auto rank = [](const WtoCoverPoint &c) { + return std::make_tuple(peekCount(c), c.widthM, c.heightM); }; - return score(raw[a]) > score(raw[b]); + if (rank(a) != rank(b)) return rank(a) > rank(b); + return std::tie(a.pos[0], a.pos[1], a.pos[2], a.coverDir[0], a.coverDir[1]) < + std::tie(b.pos[0], b.pos[1], b.pos[2], b.coverDir[0], b.coverDir[1]); }); std::vector kept; - kept.reserve(2048); - static const float kRetreatAngles[3] = { 0.0f, 0.45f, -0.45f }; - - for (size_t idx : order) { - WtoCoverPoint cp = raw[idx]; - bool dup = false; - for (const auto &k : kept) { - float dx = k.pos[0] - cp.pos[0]; - float dz = k.pos[2] - cp.pos[2]; - if (dx * dx + dz * dz < 49.0f) { /* 7 m dedupe radius */ - float dot = k.coverDir[0] * cp.coverDir[0] + k.coverDir[1] * cp.coverDir[1]; - if (dot > 0.78f && k.kind == cp.kind) { dup = true; break; } - } - } - if (dup) continue; - - /* Verify parking spot is on T1 navmesh and has >= 8 m safe retreat corridor */ - dtPolyRef startRef = 0; - float nearest[3]; - if (dtStatusFailed(q1->findNearestPoly(cp.pos, ext, &filter, &startRef, nearest)) || !startRef) continue; - float snapSq = (nearest[0] - cp.pos[0]) * (nearest[0] - cp.pos[0]) + (nearest[2] - cp.pos[2]) * (nearest[2] - cp.pos[2]); - if (snapSq > 9.0f) continue; - cp.pos[0] = nearest[0]; cp.pos[1] = nearest[1]; cp.pos[2] = nearest[2]; - - bool retreatOk = false; - float baseAng = std::atan2(-cp.coverDir[1], -cp.coverDir[0]); - for (float da : kRetreatAngles) { - float rx = std::cos(baseAng + da); - float rz = std::sin(baseAng + da); - float endPt[3] = { cp.pos[0] + rx * 8.5f, cp.pos[1], cp.pos[2] + rz * 8.5f }; - float t = 0.0f; - float hitNorm[3]; - dtPolyRef polys[32]; - int npolys = 0; - if (dtStatusSucceed(q1->raycast(startRef, cp.pos, endPt, &filter, &t, hitNorm, polys, &npolys, 32))) { - if (t >= 0.92f) { - cp.retreatDir[0] = rx; - cp.retreatDir[1] = rz; - retreatOk = true; - break; - } - } - } - if (!retreatOk) continue; - kept.push_back(cp); + const float maxLevelDifference = kTiers[WTO_NAV_TIER_STANDARD].maxClimb; + for (const auto &cover : usable) { + bool duplicate = std::any_of(kept.begin(), kept.end(), [&](const WtoCoverPoint &other) { + if (cover.kind != other.kind || std::fabs(cover.pos[1] - other.pos[1]) > maxLevelDifference) return false; + float dx = other.pos[0] - cover.pos[0], dz = other.pos[2] - cover.pos[2]; + float dot = other.coverDir[0] * cover.coverDir[0] + other.coverDir[1] * cover.coverDir[1]; + // Adjacent samples facing the same way are redundant. Perpendicular and opposite faces remain usable. + return dx * dx + dz * dz < 49.0f && dot > 0.78f; + }); + if (!duplicate) kept.push_back(cover); } return kept; } @@ -895,7 +957,7 @@ int main(int argc, char **argv) { geoPath.c_str(), mapMaxX - mapMinX, mapMaxZ - mapMinZ, tilesX, tilesZ, totalTiles, geo.hdr.obsTriCount); /* Bucket obstacle triangles once into overlapping tiles */ - const float pad = 4.5f; + const float pad = coverBorderCells(pois.cover) * kCellSize; std::vector> buckets((size_t)totalTiles); for (uint32_t ti = 0; ti < geo.hdr.obsTriCount; ++ti) { const auto &t = geo.obsTris[ti]; @@ -950,7 +1012,7 @@ int main(int argc, char **argv) { if (idx >= totalTiles) break; int tx = idx % tilesX; int tz = idx / tilesX; - auto br = buildSingleTile(geo, buckets[(size_t)idx], kTiers[tierIdx], tx, tz, mapMinX, mapMinZ, doCovers); + auto br = buildSingleTile(geo, buckets[(size_t)idx], kTiers[tierIdx], tx, tz, mapMinX, mapMinZ, pois.cover, doCovers); tierTiles[tierIdx][(size_t)idx] = br.tile; if (doCovers && !br.covers.empty()) { localCov.insert(localCov.end(), br.covers.begin(), br.covers.end()); @@ -984,14 +1046,15 @@ int main(int argc, char **argv) { } /* Dedupe + retreat-verify tank covers on Tier 1 */ - std::vector covers = filterAndDedupeCovers(rawCovers, queries[WTO_NAV_TIER_STANDARD]); - int fullCnt = 0, hdCnt = 0, peekCnt = 0; + std::vector covers = filterAndDedupeCovers(rawCovers, *queries[WTO_NAV_TIER_STANDARD], pois.cover); + int fullCnt = 0, hdCnt = 0, peekCnt = 0, bothPeeks = 0; for (const auto &c : covers) { if (c.kind == WTO_COVER_FULL) fullCnt++; else hdCnt++; - if (c.hasPeekLeft || c.hasPeekRight) peekCnt++; + if (peekCount(c) > 0) peekCnt++; + if (peekCount(c) == 2) bothPeeks++; } - std::printf(" Covers: raw=%zu -> verified=%zu (full=%d, hulldown=%d, withPeek=%d)\n", - rawCovers.size(), covers.size(), fullCnt, hdCnt, peekCnt); + std::printf(" Covers: raw=%zu -> verified=%zu (full=%d, hulldown=%d, withPeek=%d, bothPeeks=%d)\n", + rawCovers.size(), covers.size(), fullCnt, hdCnt, peekCnt, bothPeeks); /* Build 8m tactical grid (clearance + simple terrain-horizon exposure) */ const float tacCellM = 8.0f; @@ -1165,12 +1228,12 @@ int main(int argc, char **argv) { if (!outPreviewPath.empty()) { const uint32_t pw = 1024, ph = 1024; std::vector pHeight((size_t)pw * ph); - std::vector pFlags((size_t)pw * ph, 0); + std::vector pFlags((size_t)pw * ph, 0); /* Bit 0: T0 walkable, Bit 1: T1 walkable, Bit 2: T2 walkable, Bit 3: shallow water, - * Bit 4: deep water, Bit 5: chokepoint, Bit 6: crushable/forest, Bit 7: bridge */ + * Bit 4: deep water, Bit 5: chokepoint, Bit 6: crushable/forest, Bit 7: bridge, Bit 8: road */ dtQueryFilter anyF; anyF.setIncludeFlags(0xFFFF); - anyF.setExcludeFlags(0); + anyF.setExcludeFlags(WTO_FLAG_BLOCKED); const float ext[3] = { 0.8f, 6.0f, 0.8f }; std::atomic nextRow{ 0 }; @@ -1190,7 +1253,7 @@ int main(int argc, char **argv) { float wx = mapMinX + ((rx + 0.5f) / pw) * (mapMaxX - mapMinX); float gy = geo.sampleHeight(wx, wz); pHeight[(size_t)rz * pw + rx] = gy; - uint8_t fl = 0; + uint16_t fl = 0; float pt[3] = { wx, gy, wz }; for (uint32_t ti = 0; ti < WTO_NAV_TIER_COUNT; ++ti) { dtPolyRef ref = 0; @@ -1208,6 +1271,7 @@ int main(int argc, char **argv) { else if (area == WTO_AREA_CHOKEPOINT) fl |= 32; else if (area == WTO_AREA_CRUSHABLE || area == WTO_AREA_FOREST) fl |= 64; else if (area == WTO_AREA_BRIDGE) fl |= 128; + else if (area == WTO_AREA_ROAD) fl |= 256; } } } @@ -1222,7 +1286,7 @@ int main(int argc, char **argv) { for (auto &th : pWorkers) th.join(); std::ofstream pout(outPreviewPath, std::ios::binary); - pout.write("WTOPREV1", 8); + pout.write("WTOPREV2", 8); pout.write(reinterpret_cast(&pw), 4); pout.write(reinterpret_cast(&ph), 4); pout.write(reinterpret_cast(&mapMinX), 4); @@ -1231,7 +1295,7 @@ int main(int argc, char **argv) { pout.write(reinterpret_cast(&mapMaxZ), 4); pout.write(reinterpret_cast(&geo.hdr.waterLevel), 4); pout.write(reinterpret_cast(pHeight.data()), pHeight.size() * sizeof(float)); - pout.write(reinterpret_cast(pFlags.data()), pFlags.size()); + pout.write(reinterpret_cast(pFlags.data()), pFlags.size() * sizeof(uint16_t)); uint32_t cCnt = (uint32_t)covers.size(); pout.write(reinterpret_cast(&cCnt), 4); if (cCnt > 0) pout.write(reinterpret_cast(covers.data()), cCnt * sizeof(WtoCoverPoint)); diff --git a/tools/navgen/extract/Cargo.lock b/tools/navgen/extract/Cargo.lock index 6361db0..1d86e87 100644 --- a/tools/navgen/extract/Cargo.lock +++ b/tools/navgen/extract/Cargo.lock @@ -515,6 +515,8 @@ name = "wto-navgen-extract" version = "0.1.0" dependencies = [ "anyhow", + "lztans", + "ruzstd", "serde", "serde_json", "wt-formats", diff --git a/tools/navgen/extract/Cargo.toml b/tools/navgen/extract/Cargo.toml index 204ac04..68fd0df 100644 --- a/tools/navgen/extract/Cargo.toml +++ b/tools/navgen/extract/Cargo.toml @@ -6,6 +6,8 @@ description = "Offline Dagor level geometry and collision extractor for WTOfflin [dependencies] anyhow = "1" +lztans = "0.1.1" +ruzstd = "0.8" serde = { version = "1", features = ["derive"] } serde_json = "1" wt-formats = "0.1.0" diff --git a/tools/navgen/extract/src/main.rs b/tools/navgen/extract/src/main.rs index 8d51c1f..b10bf11 100644 --- a/tools/navgen/extract/src/main.rs +++ b/tools/navgen/extract/src/main.rs @@ -13,8 +13,11 @@ use wt_unpack::level::{Heightmap, Level}; use wt_unpack::rendinst::ResourceIndex; use wt_unpack::vromfs::Vromfs; +mod phys_map; + const WTO_GEO_MAGIC: &[u8; 8] = b"WTOGEO\0\x01"; const WTO_GEO_VERSION: u32 = 1; +const WTO_GEO_FLAG_ROAD_MASK: u32 = 1; const OBS_HARD_SOLID: u8 = 0; const OBS_BRIDGE_DECK: u8 = 1; @@ -372,17 +375,7 @@ fn main() -> Result<()> { let aces_meta = read_aces_meta(&game_dir, &pois.level); let water_level = aces_meta.water_level; - if let Some(pm) = level.phys_map_info()? { - println!( - " LMp2: {}x{} scale={:.2}m origin=({:.0},{:.0}) mats={:?}", - pm.size[0], - pm.size[1], - pm.metres_per_texel, - pm.world_origin[0], - pm.world_origin[1], - &pm.materials[..pm.materials.len().min(10)] - ); - } + let roads = phys_map::RoadMask::read(&level).with_context(|| format!("extracting {} roads", pois.level))?; let hm = level.heightmap()?.with_context(|| format!("{} has no HM2 heightmap", pois.level))?; let (cw, ch, crop_origin, heights) = crop_heightmap( @@ -512,7 +505,8 @@ fn main() -> Result<()> { // WtoGeoHeader (must match native/wto-nav/wto_nav_format.h byte-for-byte) w.write_all(WTO_GEO_MAGIC)?; w.write_all(&WTO_GEO_VERSION.to_le_bytes())?; - w.write_all(&0u32.to_le_bytes())?; // flags + let flags = if roads.is_some() { WTO_GEO_FLAG_ROAD_MASK } else { 0 }; + w.write_all(&flags.to_le_bytes())?; w.write_all(&ever_sha1)?; w.write_all(&water_level.to_le_bytes())?; w.write_all(&crop_origin[0].to_le_bytes())?; @@ -544,6 +538,9 @@ fn main() -> Result<()> { w.write_all(&idx[2].to_le_bytes())?; w.write_all(&[*cls])?; } + if let Some(roads) = roads { + roads.write(&mut w)?; + } w.flush()?; println!(" wrote {} ({:.1} MB)", out_path.display(), fs::metadata(&out_path)?.len() as f64 / (1024.0 * 1024.0)); Ok(()) diff --git a/tools/navgen/extract/src/phys_map.rs b/tools/navgen/extract/src/phys_map.rs new file mode 100644 index 0000000..2e127e0 --- /dev/null +++ b/tools/navgen/extract/src/phys_map.rs @@ -0,0 +1,318 @@ +use std::io::{Read, Write}; + +use anyhow::{bail, ensure, Context, Result}; +use wt_unpack::bytes::Reader; +use wt_unpack::level::Level; + +// Dagor's physMapLoad.cpp and treeBitmap.cpp define the LMp2 block and its bitmap. +const MIP_SIZE: usize = 16; +const MASK_TEXTURE_SIZE: usize = 32; +const MAX_PAYLOAD: usize = 256 * 1024 * 1024; +const MAX_GRID_CELLS: usize = 64 * 1024 * 1024; + +pub struct RoadMask { + size: usize, + origin: [f32; 2], + cell_size: f32, + cells: Vec, +} + +impl RoadMask { + pub fn read(level: &Level<'_>) -> Result> { + let Some(info) = level.phys_map_info()? else { + return Ok(None); + }; + if info.size == [0, 0] { + return Ok(None); + } + let size = info.size[0] as usize; + ensure!( + info.size[0] == info.size[1] && size.is_power_of_two() && size * size <= MAX_GRID_CELLS, + "unsupported LMp2 bitmap size {:?}", + info.size + ); + ensure!( + info.metres_per_texel.is_finite() && info.metres_per_texel > 0.0 + && info.world_origin.iter().all(|p| p.is_finite()), + "invalid LMp2 world transform" + ); + + let is_road: Vec<_> = info + .materials + .iter() + .map(|name| { + matches!( + name.to_ascii_lowercase().as_str(), + "road" | "roadsoil" | "roadsand" | "roadsnow" | "roadmud" + ) + }) + .collect(); + if !is_road.contains(&true) { + return Ok(None); + } + + let block = level.find("LMp2").context("missing LMp2 block")?; + let mut reader = Reader::at(block.data, 8)?; + for _ in &info.materials { + let len = reader.u32()? as usize; + reader.skip(len.next_multiple_of(4))?; + } + let legacy_size = if info.version == 0 { + let width = reader.u32()? as usize; + let height = reader.u32()? as usize; + reader.skip(3 * 4)?; + ensure!(width == height && width.is_power_of_two(), "invalid LMp2 level-1 bitmap size"); + Some(width) + } else { + None + }; + reader.skip(5 * 4)?; // Dimensions, world origin and metres per texel. + let block_header = reader.u32()?; + let packed = reader.bytes((block_header & 0x3fff_ffff) as usize)?; + let payload = unpack(block_header >> 30, packed)?; + let mut reader = Reader::new(&payload); + if let Some(size) = legacy_size { + read_tree(&mut reader, None, &is_road, [0, 0], size)?; + } + + let mut mask = Self { + size, + origin: info.world_origin, + cell_size: info.metres_per_texel, + cells: vec![0; size * size], + }; + read_tree(&mut reader, Some(&mut mask), &is_road, [0, 0], size)?; + let decals = read_decals(&mut reader, info.version)?; + let textures = if info.version == 0 { + &[][..] + } else { + let count = usize::from(reader.u16()?); + reader.bytes(count * MASK_TEXTURE_SIZE * size_of::())? + }; + for decal in &decals { + for group in &decal.groups { + let texture_bytes = MASK_TEXTURE_SIZE * size_of::(); + let start = usize::from(group.texture_id) * texture_bytes; + let texture = textures.get(start..start + texture_bytes); + let road = material_is_road(&is_road, group.material); + for (index, face) in group.faces.chunks_exact(6).enumerate() { + let vertices = indexed_points(face, &decal.vertices)?; + let uvs = texture + .map(|_| indexed_points(&group.uv_faces[index * 6..index * 6 + 6], &decal.uvs)) + .transpose()?; + mask.paint_triangle(vertices, road, texture.zip(uvs)); + } + } + } + let roads = mask.cells.iter().filter(|&&cell| cell != 0).count(); + println!(" LMp2: {size}x{size} at {:.2} m, {roads} road texels", mask.cell_size); + Ok(Some(mask)) + } + + pub fn write(&self, out: &mut impl Write) -> std::io::Result<()> { + out.write_all(&(self.size as u32).to_le_bytes())?; + out.write_all(&self.origin[0].to_le_bytes())?; + out.write_all(&self.origin[1].to_le_bytes())?; + out.write_all(&self.cell_size.to_le_bytes())?; + out.write_all(&self.cells) + } + + fn fill(&mut self, [x, z]: [usize; 2], size: usize, road: u8) { + for row in z..z + size { + let start = row * self.size + x; + self.cells[start..start + size].fill(road); + } + } + + fn paint_triangle( + &mut self, + vertices: [[f32; 2]; 3], + road: u8, + mask: Option<(&[u8], [[f32; 2]; 3])>, + ) { + let [a, b, c] = vertices.map(|[x, z]| { + [(x - self.origin[0]) / self.cell_size, (z - self.origin[1]) / self.cell_size] + }); + let area = edge(a, b, c); + if !area.is_finite() || area.abs() <= f32::EPSILON { + return; + } + let x0 = a[0].min(b[0]).min(c[0]).floor() as usize; + let x1 = (a[0].max(b[0]).max(c[0]).ceil() as usize).min(self.size); + let z0 = a[1].min(b[1]).min(c[1]).floor() as usize; + let z1 = (a[1].max(b[1]).max(c[1]).ceil() as usize).min(self.size); + for z in z0..z1 { + for x in x0..x1 { + let p = [x as f32 + 0.5, z as f32 + 0.5]; + let weights = [edge(b, c, p) / area, edge(c, a, p) / area, edge(a, b, p) / area]; + if weights.iter().all(|weight| *weight >= 0.0) + && mask.is_none_or(|(tex, uv)| mask_covers(tex, uv, weights)) + { + self.cells[z * self.size + x] = road; + } + } + } + } +} + +fn unpack(codec: u32, packed: &[u8]) -> Result> { + match codec { + 1 => { + let decoder = ruzstd::decoding::StreamingDecoder::new(packed).context("LMp2 zstd header")?; + let mut bytes = Vec::new(); + decoder.take(MAX_PAYLOAD as u64 + 1).read_to_end(&mut bytes)?; + ensure!(bytes.len() <= MAX_PAYLOAD, "LMp2 zstd payload is too large"); + Ok(bytes) + } + 2 => { + let mut reader = Reader::new(packed); + let size = reader.u32()? as usize; + ensure!(size <= MAX_PAYLOAD, "LMp2 Oodle payload is too large"); + let mut bytes = vec![0; size]; + lztans::decode(reader.rest(), &mut bytes) + .map_err(|err| anyhow::anyhow!("LMp2 Oodle decode: {err:?}"))?; + Ok(bytes) + } + _ => bail!("unsupported LMp2 block codec {codec}"), + } +} + +fn read_tree( + reader: &mut Reader<'_>, + mut mask: Option<&mut RoadMask>, + is_road: &[bool], + origin: [usize; 2], + size: usize, +) -> Result<()> { + let flags = reader.u8()?; + if reader.u8()? == 0 { + if let Some(mask) = mask { + mask.fill(origin, size, material_is_road(is_road, flags)); + } + return Ok(()); + } + if flags & 0x80 != 0 { + let shift = u32::from(flags & 0x7f) + 1; + ensure!(shift <= size.ilog2(), "invalid LMp2 bitmap subdivision"); + let stride = 1 << shift; + let child_size = size / stride; + for z in 0..stride { + for x in 0..stride { + let child = [origin[0] + x * child_size, origin[1] + z * child_size]; + read_tree(reader, mask.as_deref_mut(), is_road, child, child_size)?; + } + } + return Ok(()); + } + + let mip = (flags & 0x70) >> 4; + ensure!((1..=4).contains(&mip), "invalid LMp2 bitmap mip"); + let texel = 1 << (mip - 1); + ensure!(size == MIP_SIZE * texel || mask.is_none(), "LMp2 bitmap leaf size mismatch"); + let bits = match flags & 0x0c { + 0x04 => 1, + 0x08 => 2, + 0 => 8, + _ => bail!("invalid LMp2 bitmap palette"), + }; + let palette_len = if bits < 8 { 1 << bits } else { 0 }; + let palette = reader.bytes(palette_len)?; + let data = reader.bytes(MIP_SIZE * MIP_SIZE * bits / 8)?; + if let Some(mask) = mask { + for z in 0..MIP_SIZE { + for x in 0..MIP_SIZE { + let bit = (z * MIP_SIZE + x) * bits; + let value = (usize::from(data[bit / 8]) >> (bit % 8)) & ((1 << bits) - 1); + let material = if palette.is_empty() { value as u8 } else { palette[value] }; + mask.fill( + [origin[0] + x * texel, origin[1] + z * texel], + texel, + material_is_road(is_road, material), + ); + } + } + } + Ok(()) +} + +struct Decal<'a> { + vertices: Vec<[f32; 2]>, + uvs: Vec<[f32; 2]>, + groups: Vec>, +} + +struct DecalFaces<'a> { + material: u8, + faces: &'a [u8], + texture_id: u16, + uv_faces: &'a [u8], +} + +fn read_points(reader: &mut Reader<'_>) -> Result> { + let count = usize::from(reader.u16()?); + (0..count) + .map(|_| { + let point = [reader.f32()?, reader.f32()?]; + ensure!(point.iter().all(|v| v.is_finite()), "non-finite LMp2 decal vertex"); + Ok(point) + }) + .collect() +} + +fn read_decals<'a>(reader: &mut Reader<'a>, version: u32) -> Result>> { + let count = reader.u16()?; + let mut decals = Vec::new(); + for _ in 0..count { + let vertices = read_points(reader)?; + let uvs = if version > 0 { read_points(reader)? } else { Vec::new() }; + let mut groups = Vec::new(); + loop { + let material = reader.u8()?; + let face_bytes = usize::from(reader.u16()?) * 6; + if face_bytes == 0 { + break; + } + let faces = reader.bytes(face_bytes)?; + let (texture_id, uv_faces) = if version > 0 { + (reader.u16()?, reader.bytes(face_bytes)?) + } else { + (u16::MAX, &[][..]) + }; + groups.push(DecalFaces { + material, + faces, + texture_id, + uv_faces, + }); + } + decals.push(Decal { vertices, uvs, groups }); + } + Ok(decals) +} + +fn indexed_points(indices: &[u8], points: &[[f32; 2]]) -> Result<[[f32; 2]; 3]> { + let mut reader = Reader::new(indices); + let mut triangle = [[0.0; 2]; 3]; + for point in &mut triangle { + *point = *points.get(usize::from(reader.u16()?)).context("LMp2 decal index outside its vertex list")?; + } + Ok(triangle) +} + +fn material_is_road(is_road: &[bool], material: u8) -> u8 { + u8::from(is_road.get(usize::from(material)).copied().unwrap_or(false)) +} + +fn edge(a: [f32; 2], b: [f32; 2], p: [f32; 2]) -> f32 { + (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]) +} + +fn mask_covers(texture: &[u8], uv: [[f32; 2]; 3], weights: [f32; 3]) -> bool { + let texel = |axis: usize| { + let value = uv[0][axis] * weights[0] + uv[1][axis] * weights[1] + uv[2][axis] * weights[2]; + ((value - value.floor()) * (MASK_TEXTURE_SIZE - 1) as f32) as usize + }; + let x = texel(0); + let z = texel(1); + texture[z * size_of::() + x / 8] & (1 << (x % 8)) != 0 +} diff --git a/tools/navgen/mission-bounds.mts b/tools/navgen/mission-bounds.mts index 4ea682a..3ebb15a 100644 --- a/tools/navgen/mission-bounds.mts +++ b/tools/navgen/mission-bounds.mts @@ -11,6 +11,8 @@ */ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { join, resolve } from 'node:path'; +import { TuningReader } from '../../apps/server/src/tuning/tuning-reader.ts'; +import { parseJsonc } from '../../packages/jsonc/src/index.ts'; import { readArchive, getFile, NAME_MAP_PATH } from '../../packages/vromfs/src/index.ts'; import { decodeBlk, parseSharedNameMap, findBlock, findParam, type BlkBlock, type SharedNameContext } from '../../packages/blk/src/index.ts'; @@ -32,6 +34,7 @@ interface LevelPois { readonly team1Spawns: readonly PoiPoint[]; readonly team2Spawns: readonly PoiPoint[]; readonly captureZones: readonly PoiPoint[]; + readonly coverBake: ReturnType; } function parseArgs(argv: string[]) { @@ -58,7 +61,7 @@ function openPack(packPath: string) { const dicts = [...arc.files.keys()].filter((k) => k.endsWith('.dict')); const dictionary = dicts.length ? arc.files.get(dicts[0]!) : undefined; const names = arc.files.has(NAME_MAP_PATH) ? parseSharedNameMap(getFile(arc, NAME_MAP_PATH), dictionary).names : []; - const shared: SharedNameContext = { names, dictionary }; + const shared: SharedNameContext = dictionary === undefined ? { names } : { names, dictionary }; const lowerMap = new Map(); for (const k of arc.files.keys()) lowerMap.set(k.toLowerCase(), k); return { @@ -145,8 +148,21 @@ function dedupePois(pts: PoiPoint[], minDistM: number): PoiPoint[] { return out; } +function readCoverBake() { + const path = join(import.meta.dirname, '../../apps/server/tuning/ground-ai.jsonc'); + const cover = new TuningReader(path, parseJsonc(readFileSync(path, 'utf8'))).object('coverMap'); + const peekMinM = cover.number('peekMinM', { min: 0.5 }); + return { + minCoverHeightM: cover.number('minCoverHeightM', { min: 0.5 }), + peekMinM, + peekMaxM: cover.number('peekMaxM', { min: peekMinM }), + retreatMinM: cover.number('retreatMinM', { min: 0.5 }), + }; +} + function main() { const { gameDir, outDir, levelsFilter } = parseArgs(process.argv.slice(2)); + const coverBake = readCoverBake(); mkdirSync(outDir, { recursive: true }); const charPack = openPack(join(gameDir, 'char.vromfs.bin')); @@ -193,7 +209,7 @@ function main() { if (!mPath) continue; const doc = misPack.readBlk(mPath); const ms = findBlock(doc, 'mission_settings'); - const mis = findBlock(ms, 'mission'); + const mis = ms ? findBlock(ms, 'mission') : undefined; if (val(mis, 'isTanksAllowed') === false) continue; const levelPath = String(val(mis, 'level') ?? ''); if (!levelPath) continue; @@ -268,6 +284,7 @@ function main() { team1Spawns: t1, team2Spawns: t2, captureZones: caps, + coverBake, }; const outPath = join(outDir, `${levelKey}.pois.json`); writeFileSync(outPath, `${JSON.stringify(out, null, 2)}\n`, 'utf8'); diff --git a/tools/navgen/render-preview.py b/tools/navgen/render-preview.py index d83112d..6b33d84 100644 --- a/tools/navgen/render-preview.py +++ b/tools/navgen/render-preview.py @@ -89,20 +89,23 @@ def main() -> None: with open(args.pois, "r", encoding="utf-8") as f: pois = json.load(f) - assert data[:8] == b"WTOPREV1", "bad preview magic" + magic = data[:8] + if magic not in (b"WTOPREV1", b"WTOPREV2"): + raise ValueError("bad preview magic") off = 8 pw, ph, min_x, min_z, max_x, max_z, water_y = struct.unpack_from(" None: # Bright green = T2 (wide heavy) + T1 + T0 walkable # Mid-green = T1 + T0 walkable (standard tank fits, wide heavy doesn't) # Yellow-green = T0 only (narrow tank alley) - # Orange = chokepoint, Purple-tint = crushable/forest, Teal = bridge + # Tan = road, Orange = chokepoint, Olive = crushable/forest, Teal = bridge r, g, b = base, base, base if fl & 16: # deep water r, g, b = 22, 58, 125 @@ -166,6 +169,8 @@ def main() -> None: r, g, b = 220, 145, 45 elif fl & 64: # crushable/forest r, g, b = int(base * 0.6 + 65), int(base * 0.8 + 85), int(base * 0.5 + 35) + elif fl & 256: # road + r, g, b = 174, 149, 108 elif fl & 4: # T2 wide walkable r, g, b = int(base * 0.5 + 48), int(base * 0.7 + 125), int(base * 0.5 + 52) elif fl & 2: # T1 standard walkable @@ -221,25 +226,25 @@ def main() -> None: draw_circle(rgb, pw, ph, x, y, 4, (255, 230, 40), fill=True) # Overlay covers on cover map: Blue=FULL, Green=HULLDOWN, Yellow=PEEK + peeks = [] for c in covers: px_w, py_w, pz_w = c[0], c[1], c[2] dx, dz = c[3], c[4] - peek_l = (c[7], c[9]) - peek_r = (c[10], c[12]) kind = c[16] - has_pl, has_pr = c[17], c[18] x, y = world_to_px(px_w, pz_w) col = (60, 165, 255) if kind == 1 else (55, 240, 100) draw_circle(cov_rgb, pw, ph, x, y, 2, col, fill=True) # Direction tick pointing toward blocked threat x2, y2 = world_to_px(px_w + dx * 8.0, pz_w + dz * 8.0) draw_line(cov_rgb, pw, ph, x, y, x2, y2, col, thick=1) - if has_pl: - lx, ly = world_to_px(*peek_l) - draw_circle(cov_rgb, pw, ph, lx, ly, 1, (255, 240, 60), fill=True) - if has_pr: - rx2, ry2 = world_to_px(*peek_r) - draw_circle(cov_rgb, pw, ph, rx2, ry2, 1, (255, 240, 60), fill=True) + if c[17]: + peeks.append(world_to_px(c[7], c[9])) + if c[18]: + peeks.append(world_to_px(c[10], c[12])) + + # Draw both corners last so neighboring covers cannot paint over their markers. + for x, y in peeks: + draw_circle(cov_rgb, pw, ph, x, y, 1, (255, 240, 60), fill=True) nav_out = os.path.join(args.out_dir, f"{args.name}_nav.png") cov_out = os.path.join(args.out_dir, f"{args.name}_cover.png") From 6f2d9f639b10a6652ba2a98aa1039d0329f1b953 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Fri, 4 Dec 2026 19:23:22 +0800 Subject: [PATCH 03/19] fix(navgen): qualify cover against source collision geometry Recheck continuous hull cover at the final parking height and validate both corner approaches on the navigation mesh. Preserve terrain and driving collision for low stone fences while excluding their geometry from cover traces. Add a preview raster size option. Verified with Rust and MSVC builds, TypeScript checks, and 300 dpi 8K bakes for Berlin, Poland, and Hurtgen. --- apps/server/tuning/ground-ai.jsonc | 4 +- native/wto-nav/wto_nav_format.h | 7 +- tools/navgen/bake/bake.cpp | 364 ++++++++++++++++++++--------- tools/navgen/extract/src/main.rs | 50 ++-- tools/navgen/mission-bounds.mts | 1 + 5 files changed, 288 insertions(+), 138 deletions(-) diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index 723df8f..b6353dd 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -99,7 +99,9 @@ "minCoverHeightM": 1.55, "peekMinM": 3.5, "peekMaxM": 6.0, - "retreatMinM": 8.0 + "retreatMinM": 8.0, + // Low dry-stone fence models observed to give unreliable shot protection. + "excludedCoverRendinst": ["stone_fence_a", "damaged_stone_fence_a", "damaged_stone_fence_b"] }, "navigation": { diff --git a/native/wto-nav/wto_nav_format.h b/native/wto-nav/wto_nav_format.h index 07aa7f5..ec18188 100644 --- a/native/wto-nav/wto_nav_format.h +++ b/native/wto-nav/wto_nav_format.h @@ -14,7 +14,7 @@ extern "C" { #endif #define WTO_GEO_MAGIC "WTOGEO\0\1" -#define WTO_GEO_VERSION 1u +#define WTO_GEO_VERSION 2u #define WTO_GEO_FLAG_ROAD_MASK 0x01u #define WTO_NAV_MAGIC "WTONAV\0\1" @@ -56,7 +56,8 @@ enum WtoObstacleClass { WTO_OBS_BRIDGE_DECK = 1, /* Walkable bridge decks and ramps */ WTO_OBS_CRUSHABLE = 2, /* Wooden fences, hedges, low-HP destructibles */ WTO_OBS_TREE_THICK = 3, /* Thick immovable tree trunks (r >= 0.25 m) */ - WTO_OBS_TREE_THIN = 4 /* Thin tree trunks / saplings (high-cost forest) */ + WTO_OBS_TREE_THIN = 4, /* Thin tree trunks / saplings (high-cost forest) */ + WTO_OBS_HARD_NO_COVER = 5 /* Vehicle collision with no eligible cover surface */ }; /* Baked tank cover classifications. */ @@ -99,7 +100,7 @@ typedef struct WtoCoverPoint { float peekLeft[3]; /* World XYZ left corner peek spot (valid if hasPeekLeft) */ float peekRight[3]; /* World XYZ right corner peek spot (valid if hasPeekRight) */ float halfAngleDeg; /* Effective covered half-angle around coverDir */ - float heightM; /* Measured hard-obstacle height above ground at cover */ + float heightM; /* Continuous cover height above the final parking point */ float widthM; /* Continuous hard-obstacle width */ uint8_t kind; /* WtoCoverKind */ uint8_t hasPeekLeft; /* 1 if peekLeft is valid and navigable */ diff --git a/tools/navgen/bake/bake.cpp b/tools/navgen/bake/bake.cpp index 2dcfb63..7a91552 100644 --- a/tools/navgen/bake/bake.cpp +++ b/tools/navgen/bake/bake.cpp @@ -17,6 +17,7 @@ #include "DetourCommon.h" #include +#include #include #include #include @@ -25,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -83,7 +85,14 @@ static constexpr float kTileWorldSize = kTileSize * kCellSize; static constexpr float kShallowWaterMaxM = 0.60f; static constexpr float kShallowWaterMinM = 0.05f; static constexpr float kRoughSlopeDeg = 18.0f; +static constexpr float kCoverProbeStartM = 0.6f; static constexpr float kCoverScanM = 5.2f; +static constexpr float kHullLowerM = 0.65f; +static constexpr float kHullUpperM = 1.80f; +static constexpr float kTurretLowerM = 2.05f; +static constexpr float kHullColumnSpacingM = 0.9f; +static constexpr float kExtraCoverColumnM = 2.6f; +static constexpr float kGeometryToleranceM = 0.001f; static constexpr float kPeekSightM = 14.0f; static constexpr float kHullDownSightM = 22.0f; static constexpr float kCoverHeightToleranceM = 1.2f; @@ -127,7 +136,7 @@ static bool loadGeo(const std::string &path, GeoData &out) { std::ifstream in(path, std::ios::binary); if (!in) return false; in.read(reinterpret_cast(&out.hdr), sizeof(WtoGeoHeader)); - if (!in || std::memcmp(out.hdr.magic, WTO_GEO_MAGIC, 8) != 0 || out.hdr.version != WTO_GEO_VERSION) { + if (!in || std::memcmp(out.hdr.magic, WTO_GEO_MAGIC, 8) != 0 || (out.hdr.version != 1u && out.hdr.version != WTO_GEO_VERSION)) { std::fprintf(stderr, "Invalid .wtogeo header: %s\n", path.c_str()); return false; } @@ -258,45 +267,26 @@ static inline float triNormalYRightHanded(const Vec3 &a, const Vec3 &b, const Ve return len > 1e-6f ? (ny / len) : 0.0f; } -/* Query whether a hard solid span exists in rcHeightfield at (wx, wz) intersecting [yLo, yHi]. */ -static bool hfHasSolidInBand(const rcHeightfield &hf, float wx, float wz, float yLo, float yHi, float *outTopY = nullptr) { - int gx = (int)std::floor((wx - hf.bmin[0]) / hf.cs); - int gz = (int)std::floor((wz - hf.bmin[2]) / hf.cs); - if (gx < 0 || gz < 0 || gx >= hf.width || gz >= hf.height) return false; - int sminBand = (int)std::floor((yLo - hf.bmin[1]) / hf.ch); - int smaxBand = (int)std::ceil((yHi - hf.bmin[1]) / hf.ch); - float maxTop = -1e9f; - bool hit = false; - for (const rcSpan *s = hf.spans[gx + gz * hf.width]; s; s = s->next) { - if ((int)s->smax >= sminBand && (int)s->smin <= smaxBand) { - hit = true; - float topY = hf.bmin[1] + s->smax * hf.ch; - if (topY > maxTop) maxTop = topY; - } +static bool hasCoverVoxel(const rcHeightfield &field, float x, float z, float low, float high) { + int gx = (int)std::floor((x - field.bmin[0]) / field.cs); + int gz = (int)std::floor((z - field.bmin[2]) / field.cs); + if (gx < 0 || gz < 0 || gx >= field.width || gz >= field.height) return false; + int first = (int)std::floor((low - field.bmin[1]) / field.ch); + int last = (int)std::ceil((high - field.bmin[1]) / field.ch); + for (const rcSpan *span = field.spans[gx + gz * field.width]; span; span = span->next) { + if ((int)span->smax >= first && (int)span->smin <= last) return true; } - if (hit && outTopY) *outTopY = maxTop; - return hit; + return false; } -/* Raycast along XZ inside tile's hard-obstacle heightfield to check occlusion in [yLo, yHi]. */ -static bool hfTraceBand(const rcHeightfield &hardHf, const GeoData &geo, - float ox, float oz, float dx, float dz, - float maxDist, float yLo, float yHi, float *outTopY = nullptr) { - float step = hardHf.cs * 0.85f; - for (float d = 0.6f; d <= maxDist; d += step) { - float px = ox + dx * d; - float pz = oz + dz * d; - float topY = -1e9f; - if (hfHasSolidInBand(hardHf, px, pz, yLo, yHi, &topY)) { - if (outTopY) *outTopY = topY; - return true; - } - /* Terrain ridge / cliff rise above yLo also acts as natural hard earth cover! */ - float gy = geo.sampleHeight(px, pz); - if (gy >= yLo + 0.35f) { - if (outTopY) *outTopY = gy; - return true; - } +// The voxel bands only nominate a pose. The final test is done on source geometry after snapping Y. +static bool hasCoverCandidate(const rcHeightfield &field, const GeoData &geo, + float x, float z, float dx, float dz, float baseY) { + float low = baseY + kHullLowerM; + float high = baseY + kHullUpperM; + for (float d = kCoverProbeStartM; d <= kCoverScanM; d += field.cs * 0.85f) { + float px = x + dx * d, pz = z + dz * d; + if (hasCoverVoxel(field, px, pz, low, high) || geo.sampleHeight(px, pz) >= low + 0.35f) return true; } return false; } @@ -321,36 +311,9 @@ static bool isCoverBoundary(const rcCompactHeightfield &field, int x, int z, con return false; } -static bool findCornerPeek( - const rcCompactHeightfield &field, const rcHeightfield &hard, const GeoData &geo, - const CoverBake &tuning, const WtoCoverPoint &cover, float side, float (&point)[3] -) { - const float dx = cover.coverDir[0], dz = cover.coverDir[1]; - for (float distance = tuning.peekMinM; distance <= tuning.peekMaxM; distance += field.cs) { - const float x = cover.pos[0] - dz * side * distance; - const float z = cover.pos[2] + dx * side * distance; - const int gx = (int)std::floor((x - field.bmin[0]) / field.cs); - const int gz = (int)std::floor((z - field.bmin[2]) / field.cs); - if (gx < 0 || gz < 0 || gx >= field.width || gz >= field.height) break; - - const rcCompactCell &cell = field.cells[gx + gz * field.width]; - for (unsigned int i = cell.index; i < cell.index + cell.count; ++i) { - if (!isCoverArea(field.areas[i])) continue; - float y = field.bmin[1] + field.spans[i].y * field.ch; - if (std::fabs(y - cover.pos[1]) > kCoverHeightToleranceM) continue; - if (hfTraceBand(hard, geo, x, z, dx, dz, kPeekSightM, y + 1.8f, y + 2.6f)) continue; - point[0] = x; - point[1] = y; - point[2] = z; - return true; - } - } - return false; -} - static void bakeTileCovers( const rcCompactHeightfield &field, const rcHeightfield &hard, const GeoData &geo, - const rcConfig &cfg, const CoverBake &tuning, std::vector &covers + const rcConfig &cfg, std::vector &covers ) { static const float directions[8][2] = { { 1.0f, 0.0f }, { 0.70710678f, 0.70710678f }, { 0.0f, 1.0f }, { -0.70710678f, 0.70710678f }, @@ -366,43 +329,19 @@ static void bakeTileCovers( Vec3 pos{ cfg.bmin[0] + (x + 0.5f) * cfg.cs, cfg.bmin[1] + span.y * cfg.ch, cfg.bmin[2] + (z + 0.5f) * cfg.cs }; - // Every usable bearing goes through the same checks, including opposite faces of one object. for (const auto &dir : directions) { float dx = dir[0], dz = dir[1]; - int hullHits = 0, turretHits = 0; - float totalHeight = 0.0f; + int hullHits = 0; for (int column = -2; column <= 2; ++column) { - float offset = column * 0.9f; // Five samples across a 3.6 m hull. - float sx = pos.x - dz * offset, sz = pos.z + dx * offset; - float top = pos.y; - if (!hfTraceBand(hard, geo, sx, sz, dx, dz, kCoverScanM, pos.y + 0.65f, pos.y + 1.80f, &top)) continue; - ++hullHits; - totalHeight += std::max(0.0f, top - pos.y); - turretHits += hfTraceBand(hard, geo, sx, sz, dx, dz, kCoverScanM, pos.y + 2.05f, pos.y + 2.85f); + float offset = column * kHullColumnSpacingM; + hullHits += hasCoverCandidate(hard, geo, pos.x - dz * offset, pos.z + dx * offset, dx, dz, pos.y); } - if (hullHits < 4 || totalHeight < tuning.minCoverHeightM * hullHits) continue; + if (hullHits < 4) continue; - float width = 3.6f; - for (float off : { -2.6f, 2.6f }) { - if (hfTraceBand(hard, geo, pos.x - dz * off, pos.z + dx * off, dx, dz, - kCoverScanM, pos.y + 0.65f, pos.y + 1.80f)) width += 1.0f; - } - WtoCoverPoint cover{}; - cover.pos[0] = pos.x; cover.pos[1] = pos.y; cover.pos[2] = pos.z; - cover.coverDir[0] = dx; cover.coverDir[1] = dz; - cover.halfAngleDeg = width >= 5.0f ? 42.0f : 32.0f; - cover.heightM = totalHeight / hullHits; - cover.widthM = width; - - if (turretHits >= 3) { - cover.kind = WTO_COVER_FULL; - cover.hasPeekLeft = findCornerPeek(field, hard, geo, tuning, cover, -1.0f, cover.peekLeft); - cover.hasPeekRight = findCornerPeek(field, hard, geo, tuning, cover, 1.0f, cover.peekRight); - } else { - if (hfTraceBand(hard, geo, pos.x, pos.z, dx, dz, kHullDownSightM, pos.y + 2.15f, pos.y + 2.75f)) continue; - cover.kind = WTO_COVER_HULLDOWN; - } - covers.push_back(cover); + WtoCoverPoint pose{}; + pose.pos[0] = pos.x; pose.pos[1] = pos.y; pose.pos[2] = pos.z; + pose.coverDir[0] = dx; pose.coverDir[1] = dz; + covers.push_back(pose); } } } @@ -546,7 +485,7 @@ static TileBakeResult buildSingleTile( const Vec3 &v0 = geo.obsVerts[t.i0]; const Vec3 &v1 = geo.obsVerts[t.i1]; const Vec3 &v2 = geo.obsVerts[t.i2]; - if (t.cls == WTO_OBS_HARD_SOLID || t.cls == WTO_OBS_TREE_THICK) { + if (t.cls == WTO_OBS_HARD_SOLID || t.cls == WTO_OBS_HARD_NO_COVER || t.cls == WTO_OBS_TREE_THICK) { rcRasterizeTriangle(&ctx, &v0.x, &v1.x, &v2.x, RC_NULL_AREA, *solid, cfg.walkableClimb); if (hardHf && t.cls == WTO_OBS_HARD_SOLID) { rcRasterizeTriangle(&ctx, &v0.x, &v1.x, &v2.x, 1, *hardHf, 1); @@ -614,7 +553,7 @@ static TileBakeResult buildSingleTile( } } - if (hardHf) bakeTileCovers(*chf, *hardHf, geo, cfg, coverTuning, res.covers); + if (hardHf) bakeTileCovers(*chf, *hardHf, geo, cfg, res.covers); rcFreeHeightField(hardHf); hardHf = nullptr; @@ -818,6 +757,173 @@ static void markChokepoints(dtNavMesh *mesh, dtNavMeshQuery *query, float chokeD } } +struct CoverRay { + float x, z, dx, dz, range; +}; + +struct CoverSpan { + float bottom, top; +}; + +// Cut each triangle by the vertical plane through the probe, then clip the cut +// segment to the horizontal ray length. Its Y interval is the silhouette seen +// from the parking point at this column. +static bool coverTriangleSpan(const CoverRay &ray, const Vec3 &a, const Vec3 &b, const Vec3 &c, + CoverSpan &out) { + const Vec3 points[3] = { a, b, c }; + float along[3], across[3]; + for (int i = 0; i < 3; ++i) { + float x = points[i].x - ray.x, z = points[i].z - ray.z; + along[i] = x * ray.dx + z * ray.dz; + across[i] = z * ray.dx - x * ray.dz; + } + + struct CutPoint { float distance, y; }; + CutPoint cut[3]; + int count = 0; + for (int i = 0; i < 3; ++i) { + const int j = (i + 1) % 3; + if (across[i] == 0.0f) { + cut[count++] = { along[i], points[i].y }; + } else if ((across[i] < 0.0f && across[j] > 0.0f) || (across[i] > 0.0f && across[j] < 0.0f)) { + float fraction = across[i] / (across[i] - across[j]); + cut[count++] = { + along[i] + (along[j] - along[i]) * fraction, + points[i].y + (points[j].y - points[i].y) * fraction + }; + } + } + if (count != 2) return false; + if (cut[0].distance > cut[1].distance) std::swap(cut[0], cut[1]); + if (cut[1].distance < kCoverProbeStartM || cut[0].distance > ray.range) return false; + + float length = cut[1].distance - cut[0].distance; + if (length > kGeometryToleranceM) { + float from = std::max(kCoverProbeStartM, cut[0].distance); + float to = std::min(ray.range, cut[1].distance); + float rise = cut[1].y - cut[0].y; + float y0 = cut[0].y + (from - cut[0].distance) / length * rise; + float y1 = cut[0].y + (to - cut[0].distance) / length * rise; + out = { std::min(y0, y1), std::max(y0, y1) }; + } else { + out = { std::min(cut[0].y, cut[1].y), std::max(cut[0].y, cut[1].y) }; + } + return true; +} + +class CoverGeometry { +public: + explicit CoverGeometry(const GeoData &geo) : geo(geo) { + cols = std::max(1, (int)std::ceil((geo.hdr.boundsMax[0] - geo.hdr.boundsMin[0]) / indexCellM)); + rows = std::max(1, (int)std::ceil((geo.hdr.boundsMax[1] - geo.hdr.boundsMin[1]) / indexCellM)); + cells.resize((size_t)cols * rows); + for (uint32_t i = 0; i < geo.obsTris.size(); ++i) { + const auto &tri = geo.obsTris[i]; + if (tri.cls != WTO_OBS_HARD_SOLID) continue; + + const auto &a = geo.obsVerts[tri.i0]; + const auto &b = geo.obsVerts[tri.i1]; + const auto &c = geo.obsVerts[tri.i2]; + int firstX = column(std::min({ a.x, b.x, c.x })); + int lastX = column(std::max({ a.x, b.x, c.x })); + int firstZ = row(std::min({ a.z, b.z, c.z })); + int lastZ = row(std::max({ a.z, b.z, c.z })); + for (int z = firstZ; z <= lastZ; ++z) { + for (int x = firstX; x <= lastX; ++x) cells[(size_t)z * cols + x].push_back(i); + } + } + } + + void collect(const CoverRay &ray, float lower, std::vector &spans) const { + spans.clear(); + + const float endX = ray.x + ray.dx * ray.range; + const float endZ = ray.z + ray.dz * ray.range; + float terrainTop = geo.sampleHeight(endX, endZ); + for (float d = kCoverProbeStartM; d < ray.range; d += kCellSize * 0.85f) { + terrainTop = std::max(terrainTop, geo.sampleHeight(ray.x + ray.dx * d, ray.z + ray.dz * d)); + } + if (terrainTop >= lower) spans.push_back({ lower, terrainTop }); + + const float startX = ray.x + ray.dx * kCoverProbeStartM; + const float startZ = ray.z + ray.dz * kCoverProbeStartM; + const float xmin = std::min(startX, endX), xmax = std::max(startX, endX); + const float zmin = std::min(startZ, endZ), zmax = std::max(startZ, endZ); + const int lastX = column(xmax), lastZ = row(zmax); + for (int z = row(zmin); z <= lastZ; ++z) { + for (int x = column(xmin); x <= lastX; ++x) { + for (uint32_t i : cells[(size_t)z * cols + x]) { + const auto &tri = geo.obsTris[i]; + const auto &a = geo.obsVerts[tri.i0]; + const auto &b = geo.obsVerts[tri.i1]; + const auto &c = geo.obsVerts[tri.i2]; + if (std::max({ a.y, b.y, c.y }) < lower || + std::max({ a.x, b.x, c.x }) < xmin || std::min({ a.x, b.x, c.x }) > xmax || + std::max({ a.z, b.z, c.z }) < zmin || std::min({ a.z, b.z, c.z }) > zmax) continue; + + CoverSpan span; + if (coverTriangleSpan(ray, a, b, c, span) && span.top >= lower) spans.push_back(span); + } + } + } + } + +private: + static constexpr float indexCellM = kTileWorldSize / 16.0f; + const GeoData &geo; + int cols = 0, rows = 0; + std::vector> cells; + + int column(float x) const { return std::clamp((int)std::floor((x - geo.hdr.boundsMin[0]) / indexCellM), 0, cols - 1); } + int row(float z) const { return std::clamp((int)std::floor((z - geo.hdr.boundsMin[1]) / indexCellM), 0, rows - 1); } +}; + +static float coverColumnHeight(const CoverGeometry &geometry, const WtoCoverPoint &cover, float offset, + std::vector &spans) { + float dx = cover.coverDir[0], dz = cover.coverDir[1]; + float lower = cover.pos[1] + kHullLowerM; + geometry.collect({ cover.pos[0] - dz * offset, cover.pos[2] + dx * offset, dx, dz, kCoverScanM }, lower, spans); + std::sort(spans.begin(), spans.end(), [](const CoverSpan &a, const CoverSpan &b) { return a.bottom < b.bottom; }); + + if (spans.empty() || spans.front().bottom > lower + kGeometryToleranceM) return -std::numeric_limits::infinity(); + float top = lower; + for (const auto &span : spans) { + if (span.bottom > top + kGeometryToleranceM) break; + top = std::max(top, span.top); + } + return top - cover.pos[1]; +} + +static bool coveredSightBand(const CoverGeometry &geometry, const float *pos, const float *direction, float range, + float low, float high, std::vector &spans) { + geometry.collect({ pos[0], pos[2], direction[0], direction[1], range }, pos[1] + low, spans); + return std::any_of(spans.begin(), spans.end(), [&](const CoverSpan &span) { return span.bottom <= pos[1] + high; }); +} + +static bool qualifyCover(WtoCoverPoint &cover, const CoverGeometry &geometry, + const CoverBake &tuning, std::vector &spans) { + std::array heights; + for (size_t i = 0; i < heights.size(); ++i) { + heights[i] = coverColumnHeight(geometry, cover, ((int)i - 2) * kHullColumnSpacingM, spans); + } + std::sort(heights.begin(), heights.end(), [](float a, float b) { return a > b; }); + + // Four columns must each hide the hull through the required height. + if (heights[3] < tuning.minCoverHeightM) return false; + cover.heightM = heights[3]; + + const bool full = heights[2] >= kTurretLowerM; + if (!full && coveredSightBand(geometry, cover.pos, cover.coverDir, kHullDownSightM, 2.15f, 2.75f, spans)) return false; + + cover.kind = full ? WTO_COVER_FULL : WTO_COVER_HULLDOWN; + cover.widthM = 4.0f * kHullColumnSpacingM; + for (float offset : { -kExtraCoverColumnM, kExtraCoverColumnM }) { + if (coverColumnHeight(geometry, cover, offset, spans) >= tuning.minCoverHeightM) cover.widthM += 1.0f; + } + cover.halfAngleDeg = cover.widthM >= 5.0f ? 42.0f : 32.0f; + return true; +} + static dtPolyRef verifyCoverPosition(dtNavMeshQuery &query, const dtQueryFilter &filter, float (&point)[3]) { const float extent[3] = { kCellSize, kCoverHeightToleranceM, kCellSize }; dtPolyRef ref = 0; @@ -839,16 +945,36 @@ static bool clearCoverCorridor(dtNavMeshQuery &query, const dtQueryFilter &filte fraction >= 1.0f && (!endRef || (count > 0 && trail[count - 1] == endRef)); } -static bool verifyCover(WtoCoverPoint &cover, dtNavMeshQuery &query, - const dtQueryFilter &filter, float retreatMinM) { +static bool findCornerPeek(WtoCoverPoint &cover, dtNavMeshQuery &query, const dtQueryFilter &filter, + dtPolyRef startRef, const CoverGeometry &geometry, const CoverBake &tuning, + float side, float (&point)[3], std::vector &spans) { + dtQueryFilter dry = filter; + dry.setExcludeFlags(filter.getExcludeFlags() | WTO_FLAG_SHALLOW_WATER); + for (float distance = tuning.peekMinM; distance <= tuning.peekMaxM; distance += kCellSize) { + float candidate[3] = { + cover.pos[0] - cover.coverDir[1] * side * distance, + cover.pos[1], + cover.pos[2] + cover.coverDir[0] * side * distance + }; + dtPolyRef endRef = verifyCoverPosition(query, dry, candidate); + if (!endRef || !clearCoverCorridor(query, filter, startRef, cover.pos, candidate, endRef)) continue; + if (coveredSightBand(geometry, candidate, cover.coverDir, kPeekSightM, 1.8f, 2.6f, spans)) continue; + std::copy(candidate, candidate + 3, point); + return true; + } + return false; +} + +static bool verifyCover(WtoCoverPoint &cover, dtNavMeshQuery &query, const dtQueryFilter &filter, + const CoverGeometry &geometry, const CoverBake &tuning, std::vector &spans) { dtPolyRef startRef = verifyCoverPosition(query, filter, cover.pos); - if (!startRef) return false; + if (!startRef || !qualifyCover(cover, geometry, tuning, spans)) return false; const float heading = std::atan2(-cover.coverDir[1], -cover.coverDir[0]); bool hasRetreat = false; for (float offset : { 0.0f, 0.45f, -0.45f }) { float rx = std::cos(heading + offset), rz = std::sin(heading + offset); - float end[3] = { cover.pos[0] + rx * retreatMinM, cover.pos[1], cover.pos[2] + rz * retreatMinM }; + float end[3] = { cover.pos[0] + rx * tuning.retreatMinM, cover.pos[1], cover.pos[2] + rz * tuning.retreatMinM }; if (!clearCoverCorridor(query, filter, startRef, cover.pos, end)) continue; cover.retreatDir[0] = rx; cover.retreatDir[1] = rz; @@ -857,12 +983,10 @@ static bool verifyCover(WtoCoverPoint &cover, dtNavMeshQuery &query, } if (!hasRetreat) return false; - auto validatePeek = [&](float (&point)[3]) { - dtPolyRef endRef = verifyCoverPosition(query, filter, point); - return endRef && clearCoverCorridor(query, filter, startRef, cover.pos, point, endRef); - }; - cover.hasPeekLeft = cover.hasPeekLeft && validatePeek(cover.peekLeft); - cover.hasPeekRight = cover.hasPeekRight && validatePeek(cover.peekRight); + if (cover.kind == WTO_COVER_FULL) { + cover.hasPeekLeft = findCornerPeek(cover, query, filter, startRef, geometry, tuning, -1.0f, cover.peekLeft, spans); + cover.hasPeekRight = findCornerPeek(cover, query, filter, startRef, geometry, tuning, 1.0f, cover.peekRight, spans); + } return true; } @@ -871,14 +995,16 @@ static unsigned int peekCount(const WtoCoverPoint &cover) { } static std::vector filterAndDedupeCovers( - const std::vector &raw, dtNavMeshQuery &query, const CoverBake &tuning + const std::vector &raw, dtNavMeshQuery &query, const CoverBake &tuning, const GeoData &geo ) { dtQueryFilter filter; filter.setIncludeFlags(WTO_FLAG_WALK); filter.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED); + const CoverGeometry geometry(geo); + std::vector spans; std::vector usable; for (WtoCoverPoint cover : raw) { - if (verifyCover(cover, query, filter, tuning.retreatMinM)) usable.push_back(cover); + if (verifyCover(cover, query, filter, geometry, tuning, spans)) usable.push_back(cover); } std::sort(usable.begin(), usable.end(), [](const WtoCoverPoint &a, const WtoCoverPoint &b) { @@ -925,15 +1051,25 @@ static void serializeTier(const dtNavMeshParams ¶ms, const std::vector 8192) { + std::fprintf(stderr, "Preview size must be between 1 and 8192 pixels.\n"); + return 2; + } + previewSize = (uint32_t)size; + } } if (geoPath.empty() || poisPath.empty() || outNavPath.empty()) { - std::fprintf(stderr, "Usage: wto_navgen_bake --geo --pois --out [--preview ]\n"); + std::fprintf(stderr, "Usage: wto_navgen_bake --geo --pois --out [--preview ] [--preview-size ]\n"); return 2; } @@ -1046,7 +1182,7 @@ int main(int argc, char **argv) { } /* Dedupe + retreat-verify tank covers on Tier 1 */ - std::vector covers = filterAndDedupeCovers(rawCovers, *queries[WTO_NAV_TIER_STANDARD], pois.cover); + std::vector covers = filterAndDedupeCovers(rawCovers, *queries[WTO_NAV_TIER_STANDARD], pois.cover, geo); int fullCnt = 0, hdCnt = 0, peekCnt = 0, bothPeeks = 0; for (const auto &c : covers) { if (c.kind == WTO_COVER_FULL) fullCnt++; else hdCnt++; @@ -1226,7 +1362,7 @@ int main(int argc, char **argv) { /* Write compact raster preview data for PNG visual inspection */ if (!outPreviewPath.empty()) { - const uint32_t pw = 1024, ph = 1024; + const uint32_t pw = previewSize, ph = previewSize; std::vector pHeight((size_t)pw * ph); std::vector pFlags((size_t)pw * ph, 0); /* Bit 0: T0 walkable, Bit 1: T1 walkable, Bit 2: T2 walkable, Bit 3: shallow water, diff --git a/tools/navgen/extract/src/main.rs b/tools/navgen/extract/src/main.rs index b10bf11..1016274 100644 --- a/tools/navgen/extract/src/main.rs +++ b/tools/navgen/extract/src/main.rs @@ -16,7 +16,7 @@ use wt_unpack::vromfs::Vromfs; mod phys_map; const WTO_GEO_MAGIC: &[u8; 8] = b"WTOGEO\0\x01"; -const WTO_GEO_VERSION: u32 = 1; +const WTO_GEO_VERSION: u32 = 2; const WTO_GEO_FLAG_ROAD_MASK: u32 = 1; const OBS_HARD_SOLID: u8 = 0; @@ -24,6 +24,7 @@ const OBS_BRIDGE_DECK: u8 = 1; const OBS_CRUSHABLE: u8 = 2; const OBS_TREE_THICK: u8 = 3; const OBS_TREE_THIN: u8 = 4; +const OBS_HARD_NO_COVER: u8 = 5; #[derive(Debug, Deserialize)] struct LevelPois { @@ -34,6 +35,14 @@ struct LevelPois { bounds_min: [f32; 2], #[serde(rename = "boundsMax")] bounds_max: [f32; 2], + #[serde(rename = "coverBake", default)] + cover: CoverBakeInput, +} + +#[derive(Debug, Default, Deserialize)] +struct CoverBakeInput { + #[serde(rename = "excludedCoverRendinst", default)] + excluded_rendinst: Vec, } #[derive(Debug, Clone)] @@ -264,7 +273,7 @@ fn tri_normal_y(a: [f32; 3], b: [f32; 3], c: [f32; 3]) -> f32 { if len > 1e-6 { (ny / len).abs() } else { 0.0 } } -fn build_cached_collision(c: &Collision, meta: &PoolMeta) -> Option { +fn build_cached_collision(c: &Collision, meta: &PoolMeta, cover_allowed: bool) -> Option { if meta.is_soft_foliage { return None; } @@ -283,6 +292,16 @@ fn build_cached_collision(c: &Collision, meta: &PoolMeta) -> Option= 0.72 { + OBS_BRIDGE_DECK + } else if meta.is_crushable { + OBS_CRUSHABLE + } else { + hard_class + } + }; match n.kind { NodeKind::Mesh | NodeKind::Convex => { if n.indices.len() < 3 { @@ -292,25 +311,13 @@ fn build_cached_collision(c: &Collision, meta: &PoolMeta) -> Option= 0.72 { - OBS_BRIDGE_DECK - } else if meta.is_crushable { - OBS_CRUSHABLE - } else { - OBS_HARD_SOLID - }; + let cls = obstacle_class(p0, p1, p2); tris.push((p0, p1, p2, cls)); } } NodeKind::Box => { for (p0, p1, p2) in box_tris(n) { - let cls = if meta.is_bridge && tri_normal_y(p0, p1, p2) >= 0.72 { - OBS_BRIDGE_DECK - } else if meta.is_crushable { - OBS_CRUSHABLE - } else { - OBS_HARD_SOLID - }; + let cls = obstacle_class(p0, p1, p2); tris.push((p0, p1, p2, cls)); } } @@ -427,6 +434,7 @@ fn main() -> Result<()> { } } + let excluded_cover: HashSet<_> = pois.cover.excluded_rendinst.iter().map(|name| name.to_ascii_lowercase()).collect(); let mut cached_cols: HashMap = HashMap::new(); for (pack_path, items) in &by_pack { let Ok(bytes) = fs::read(pack_path) else { continue }; @@ -434,9 +442,10 @@ fn main() -> Result<()> { for (pool_name, res_name) in items { let Some(res) = pack.find(res_name, COLLISION) else { continue }; let Ok(col) = Collision::parse(res_name, pack.data(res)) else { continue }; - let imp = aces_meta.destr_impulse.get(&pool_name.to_lowercase()).copied(); + let key = pool_name.to_ascii_lowercase(); + let imp = aces_meta.destr_impulse.get(&key).copied(); let meta = classify_pool(pool_name, imp); - if let Some(cc) = build_cached_collision(&col, &meta) { + if let Some(cc) = build_cached_collision(&col, &meta, !excluded_cover.contains(&key)) { cached_cols.insert(pool_name.clone(), cc); } } @@ -447,7 +456,7 @@ fn main() -> Result<()> { let mut verts: Vec<[f32; 3]> = Vec::with_capacity(200_000); let mut tris: Vec<([u32; 3], u8)> = Vec::with_capacity(100_000); let mut inst_used = 0usize; - let mut cls_counts = [0usize; 5]; + let mut cls_counts = [0usize; 6]; for layer in &layers { let instances = layer.instances()?; @@ -484,7 +493,7 @@ fn main() -> Result<()> { } println!( - " RIGz: pools={} cols={} noCol={} instancesInBounds={} obsTris={} [hard={} bridge={} crush={} treeThick={} treeThin={}] ({:.2}s)", + " RIGz: pools={} cols={} noCol={} instancesInBounds={} obsTris={} [hard={} bridge={} crush={} treeThick={} treeThin={} collisionOnly={}] ({:.2}s)", pool_names.len(), cached_cols.len(), no_collision, @@ -495,6 +504,7 @@ fn main() -> Result<()> { cls_counts[2], cls_counts[3], cls_counts[4], + cls_counts[5], t0.elapsed().as_secs_f32() ); diff --git a/tools/navgen/mission-bounds.mts b/tools/navgen/mission-bounds.mts index 3ebb15a..707e76f 100644 --- a/tools/navgen/mission-bounds.mts +++ b/tools/navgen/mission-bounds.mts @@ -157,6 +157,7 @@ function readCoverBake() { peekMinM, peekMaxM: cover.number('peekMaxM', { min: peekMinM }), retreatMinM: cover.number('retreatMinM', { min: 0.5 }), + excludedCoverRendinst: cover.stringList('excludedCoverRendinst'), }; } From ed5296e0b847316c383a37071e5c6c65fa52ab3b Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Fri, 4 Dec 2026 22:56:21 +0800 Subject: [PATCH 04/19] fix(navgen): restore Berlin roads and terrain access Retain road identity on narrow polygons, bake upward support faces on the verified fountain model, and attach directional Detour links for two dry canal-bank descents. Keep map-specific inputs in the Berlin tuning file and show both surfaces and links in the preview. Verified three-tier bakes, platform approaches, and downhill and reverse route queries on 2.61.0.58. --- apps/server/tuning/maps/avg_berlin.jsonc | 24 ++++ native/wto-nav/wto_nav_format.h | 19 +++- tools/navgen/bake/bake.cpp | 139 +++++++++++++++++++++-- tools/navgen/extract/src/main.rs | 78 +++++++++++-- tools/navgen/extract/src/phys_map.rs | 4 +- tools/navgen/mission-bounds.mts | 30 ++++- tools/navgen/render-preview.py | 31 ++++- 7 files changed, 298 insertions(+), 27 deletions(-) create mode 100644 apps/server/tuning/maps/avg_berlin.jsonc diff --git a/apps/server/tuning/maps/avg_berlin.jsonc b/apps/server/tuning/maps/avg_berlin.jsonc new file mode 100644 index 0000000..8c6ce5b --- /dev/null +++ b/apps/server/tuning/maps/avg_berlin.jsonc @@ -0,0 +1,24 @@ +{ + "level": "avg_berlin", + "version": 1, + "bake": { + // The original arterial and ring roads use this LMp2 material. + "roadMaterials": ["concrete"], + "walkableRendinst": ["fountain_base_b_body"], + "downhillLinks": [ + // Dry endpoints verified on the two meshes at the eastern canal bank. + { + "from": { "x": 2476.0, "y": 43.34, "z": 1124.0 }, + "to": { "x": 2460.0, "y": 36.61, "z": 1124.0 }, + "radiusM": 0.75, + "widthTiers": [0] + }, + { + "from": { "x": 2476.0, "y": 43.12, "z": 1135.5 }, + "to": { "x": 2458.0, "y": 36.59, "z": 1135.5 }, + "radiusM": 0.75, + "widthTiers": [1] + } + ] + } +} diff --git a/native/wto-nav/wto_nav_format.h b/native/wto-nav/wto_nav_format.h index ec18188..efdc3d8 100644 --- a/native/wto-nav/wto_nav_format.h +++ b/native/wto-nav/wto_nav_format.h @@ -14,8 +14,9 @@ extern "C" { #endif #define WTO_GEO_MAGIC "WTOGEO\0\1" -#define WTO_GEO_VERSION 2u +#define WTO_GEO_VERSION 3u #define WTO_GEO_FLAG_ROAD_MASK 0x01u +#define WTO_GEO_FLAG_DOWNHILL_LINKS 0x02u #define WTO_NAV_MAGIC "WTONAV\0\1" #define WTO_NAV_VERSION 1u @@ -47,7 +48,10 @@ enum WtoPolyFlag { WTO_FLAG_SHALLOW_WATER = 0x02, WTO_FLAG_DEEP_WATER = 0x04, WTO_FLAG_CHOKEPOINT = 0x08, - WTO_FLAG_BLOCKED = 0x10 + WTO_FLAG_BLOCKED = 0x10, + WTO_FLAG_ROAD = 0x20, /* Surface identity, retained on chokepoint polygons */ + WTO_FLAG_DOWNHILL = 0x40, /* One-way Detour connection */ + WTO_FLAG_PLATFORM = 0x80 /* Walkable top of a validated placed object */ }; /* Obstacle classification written into `.wtogeo` by the extractor. */ @@ -57,7 +61,9 @@ enum WtoObstacleClass { WTO_OBS_CRUSHABLE = 2, /* Wooden fences, hedges, low-HP destructibles */ WTO_OBS_TREE_THICK = 3, /* Thick immovable tree trunks (r >= 0.25 m) */ WTO_OBS_TREE_THIN = 4, /* Thin tree trunks / saplings (high-cost forest) */ - WTO_OBS_HARD_NO_COVER = 5 /* Vehicle collision with no eligible cover surface */ + WTO_OBS_HARD_NO_COVER = 5, /* Vehicle collision with no eligible cover surface */ + WTO_OBS_PLATFORM = 6, /* Placed geometry with eligible upward-facing support surfaces */ + WTO_OBS_PLATFORM_NO_COVER = 7 /* Support surfaces from vehicle-only collision */ }; /* Baked tank cover classifications. */ @@ -92,6 +98,13 @@ typedef struct WtoGeoRoadMask { float cellSize; } WtoGeoRoadMask; +/* Optional downhill links trailer: uint32_t count followed by records. */ +typedef struct WtoGeoDownhillLink { + float endpoints[6]; /* From XYZ (high) followed by to XYZ (low) */ + float radiusM; /* Detour endpoint attachment radius */ + uint32_t tierMask; +} WtoGeoDownhillLink; + /* Baked tank cover point (68 bytes). */ typedef struct WtoCoverPoint { float pos[3]; /* World XYZ parking position behind cover */ diff --git a/tools/navgen/bake/bake.cpp b/tools/navgen/bake/bake.cpp index 7a91552..86c89fc 100644 --- a/tools/navgen/bake/bake.cpp +++ b/tools/navgen/bake/bake.cpp @@ -93,6 +93,12 @@ static constexpr float kTurretLowerM = 2.05f; static constexpr float kHullColumnSpacingM = 0.9f; static constexpr float kExtraCoverColumnM = 2.6f; static constexpr float kGeometryToleranceM = 0.001f; +// Intermediate Recast area. Its serialized area is ground. +static constexpr unsigned char kPlatformArea = RC_WALKABLE_AREA - 1; + +static bool hasCoverGeometry(uint8_t cls) { + return cls == WTO_OBS_HARD_SOLID || cls == WTO_OBS_PLATFORM; +} static constexpr float kPeekSightM = 14.0f; static constexpr float kHullDownSightM = 22.0f; static constexpr float kCoverHeightToleranceM = 1.2f; @@ -102,6 +108,7 @@ struct GeoData { std::vector heights; WtoGeoRoadMask roads{}; std::vector roadCells; + std::vector downhillLinks; std::vector obsVerts; std::vector obsTris; float minY = 1e9f; @@ -136,7 +143,7 @@ static bool loadGeo(const std::string &path, GeoData &out) { std::ifstream in(path, std::ios::binary); if (!in) return false; in.read(reinterpret_cast(&out.hdr), sizeof(WtoGeoHeader)); - if (!in || std::memcmp(out.hdr.magic, WTO_GEO_MAGIC, 8) != 0 || (out.hdr.version != 1u && out.hdr.version != WTO_GEO_VERSION)) { + if (!in || std::memcmp(out.hdr.magic, WTO_GEO_MAGIC, 8) != 0 || (out.hdr.version < 1u || out.hdr.version > WTO_GEO_VERSION)) { std::fprintf(stderr, "Invalid .wtogeo header: %s\n", path.c_str()); return false; } @@ -162,6 +169,18 @@ static bool loadGeo(const std::string &path, GeoData &out) { out.roadCells.resize((size_t)out.roads.size * out.roads.size); in.read(reinterpret_cast(out.roadCells.data()), out.roadCells.size()); } + if (out.hdr.flags & WTO_GEO_FLAG_DOWNHILL_LINKS) { + uint32_t count = 0; + in.read(reinterpret_cast(&count), sizeof(count)); + if (!in || count > UINT16_MAX) return false; + out.downhillLinks.resize(count); + in.read(reinterpret_cast(out.downhillLinks.data()), count * sizeof(WtoGeoDownhillLink)); + for (const auto &link : out.downhillLinks) { + if (!std::all_of(std::begin(link.endpoints), std::end(link.endpoints), [](float v) { return std::isfinite(v); }) || + !(link.radiusM > 0.0f) || !std::isfinite(link.radiusM) || link.endpoints[1] <= link.endpoints[4] || + !link.tierMask || link.tierMask >= (1u << WTO_NAV_TIER_COUNT)) return false; + } + } if (!in) return false; for (float h : out.heights) { @@ -378,7 +397,7 @@ struct TileBakeResult { static TileBakeResult buildSingleTile( const GeoData &geo, const std::vector &triBucket, - const TierSpec &tier, + uint32_t tierIndex, int tx, int tz, float mapMinX, float mapMinZ, const CoverBake &coverTuning, bool bakeCovers @@ -387,6 +406,7 @@ static TileBakeResult buildSingleTile( res.tile.tx = tx; res.tile.tz = tz; + const TierSpec &tier = kTiers[tierIndex]; rcContext ctx(false); rcConfig cfg{}; cfg.cs = kCellSize; @@ -490,6 +510,11 @@ static TileBakeResult buildSingleTile( if (hardHf && t.cls == WTO_OBS_HARD_SOLID) { rcRasterizeTriangle(&ctx, &v0.x, &v1.x, &v2.x, 1, *hardHf, 1); } + } else if (t.cls == WTO_OBS_PLATFORM || t.cls == WTO_OBS_PLATFORM_NO_COVER) { + float ny = triNormalYRightHanded(v0, v1, v2); + unsigned char area = ny >= cosMaxSlope ? kPlatformArea : RC_NULL_AREA; + rcRasterizeTriangle(&ctx, &v0.x, &v1.x, &v2.x, area, *solid, cfg.walkableClimb); + if (hardHf && hasCoverGeometry(t.cls)) rcRasterizeTriangle(&ctx, &v0.x, &v1.x, &v2.x, 1, *hardHf, 1); } else if (t.cls == WTO_OBS_BRIDGE_DECK) { float ny = triNormalYRightHanded(v0, v1, v2); if (std::fabs(ny) >= cosMaxSlope) { @@ -607,7 +632,11 @@ static TileBakeResult buildSingleTile( if (a == WTO_AREA_DEEP_WATER) pmesh->flags[i] = WTO_FLAG_DEEP_WATER; else if (a == WTO_AREA_SHALLOW_WATER) pmesh->flags[i] = WTO_FLAG_WALK | WTO_FLAG_SHALLOW_WATER; else if (a == WTO_AREA_NO_GO) pmesh->flags[i] = WTO_FLAG_BLOCKED; - else if (a != RC_NULL_AREA) pmesh->flags[i] = WTO_FLAG_WALK; + else if (a == WTO_AREA_ROAD) pmesh->flags[i] = WTO_FLAG_WALK | WTO_FLAG_ROAD; + else if (a == kPlatformArea) { + pmesh->areas[i] = WTO_AREA_GROUND; + pmesh->flags[i] = WTO_FLAG_WALK | WTO_FLAG_PLATFORM; + } else if (a != RC_NULL_AREA) pmesh->flags[i] = WTO_FLAG_WALK; else pmesh->flags[i] = 0; } @@ -636,6 +665,30 @@ static TileBakeResult buildSingleTile( params.ch = cfg.ch; params.buildBvTree = true; + std::vector endpoints, radii; + std::vector linkFlags; + std::vector linkAreas, linkDirections; + std::vector linkIds; + for (size_t i = 0; i < geo.downhillLinks.size(); ++i) { + const auto &link = geo.downhillLinks[i]; + if (!(link.tierMask & (1u << tierIndex))) continue; + float x = link.endpoints[0], z = link.endpoints[2]; + if (x < params.bmin[0] || x >= params.bmax[0] || z < params.bmin[2] || z >= params.bmax[2]) continue; + endpoints.insert(endpoints.end(), std::begin(link.endpoints), std::end(link.endpoints)); + radii.push_back(link.radiusM); + linkFlags.push_back(WTO_FLAG_WALK | WTO_FLAG_DOWNHILL); + linkAreas.push_back(WTO_AREA_ROUGH); + linkDirections.push_back(0); + linkIds.push_back((unsigned int)i + 1); + } + params.offMeshConCount = (int)linkIds.size(); + params.offMeshConVerts = endpoints.data(); + params.offMeshConRad = radii.data(); + params.offMeshConFlags = linkFlags.data(); + params.offMeshConAreas = linkAreas.data(); + params.offMeshConDir = linkDirections.data(); + params.offMeshConUserID = linkIds.data(); + unsigned char *navData = nullptr; int navDataSize = 0; if (dtCreateNavMeshData(¶ms, &navData, &navDataSize)) { @@ -723,6 +776,63 @@ static int pruneUnreachableIslands(dtNavMesh *mesh, dtNavMeshQuery *query, const return pruned; } +static bool hasPolygonLink(const dtNavMesh &mesh, dtPolyRef from, dtPolyRef to) { + const dtMeshTile *tile = nullptr; + const dtPoly *poly = nullptr; + if (dtStatusFailed(mesh.getTileAndPolyByRef(from, &tile, &poly))) return false; + for (unsigned int i = poly->firstLink; i != DT_NULL_LINK; i = tile->links[i].next) { + if (tile->links[i].ref == to) return true; + } + return false; +} + +static bool verifyDownhillLinks(const dtNavMesh &mesh, const GeoData &geo, uint32_t tierIndex) { + if (geo.downhillLinks.empty()) return true; + std::vector attached(geo.downhillLinks.size()); + for (int i = 0; i < mesh.getMaxTiles(); ++i) { + const dtMeshTile *tile = mesh.getTile(i); + if (!tile || !tile->header) continue; + for (int n = 0; n < tile->header->offMeshConCount; ++n) { + const dtOffMeshConnection &con = tile->offMeshCons[n]; + if (con.userId == 0 || con.userId > attached.size() || attached[con.userId - 1] || + (con.flags & DT_OFFMESH_CON_BIDIR)) return false; + + const dtPoly &poly = tile->polys[con.poly]; + if ((poly.flags & WTO_FLAG_DOWNHILL) == 0) return false; + dtPolyRef ref = mesh.getPolyRefBase(tile) | con.poly; + dtPolyRef endpoints[2] = {}; + for (unsigned int j = poly.firstLink; j != DT_NULL_LINK; j = tile->links[j].next) { + const dtLink &link = tile->links[j]; + if (link.edge < 2) endpoints[link.edge] = link.ref; + } + unsigned short startFlags = 0, endFlags = 0; + if (!endpoints[0] || !endpoints[1] || endpoints[0] == endpoints[1] || + dtStatusFailed(mesh.getPolyFlags(endpoints[0], &startFlags)) || + dtStatusFailed(mesh.getPolyFlags(endpoints[1], &endFlags)) || + !(startFlags & WTO_FLAG_WALK) || !(endFlags & WTO_FLAG_WALK) || + !hasPolygonLink(mesh, endpoints[0], ref) || hasPolygonLink(mesh, endpoints[1], ref)) { + std::fprintf(stderr, "Downhill link %u (%.2f, %.2f -> %.2f, %.2f) unattached on %s.\n", con.userId, + con.pos[0], con.pos[2], con.pos[3], con.pos[5], kTiers[tierIndex].name); + return false; + } + const float *from = &tile->verts[poly.verts[0] * 3]; + const float *to = &tile->verts[poly.verts[1] * 3]; + if (from[1] <= to[1]) return false; + attached[con.userId - 1] = true; + std::printf(" Downhill link %u on %s: (%.2f, %.2f, %.2f) -> (%.2f, %.2f, %.2f)\n", + con.userId, kTiers[tierIndex].name, from[0], from[1], from[2], to[0], to[1], to[2]); + } + } + for (size_t i = 0; i < geo.downhillLinks.size(); ++i) { + bool expected = (geo.downhillLinks[i].tierMask & (1u << tierIndex)) != 0; + if (expected != (bool)attached[i]) { + std::fprintf(stderr, "Missing downhill link %zu on %s\n", i + 1, kTiers[tierIndex].name); + return false; + } + } + return true; +} + static void markChokepoints(dtNavMesh *mesh, dtNavMeshQuery *query, float chokeDistM) { dtQueryFilter filter; filter.setIncludeFlags(WTO_FLAG_WALK); @@ -819,7 +929,7 @@ public: cells.resize((size_t)cols * rows); for (uint32_t i = 0; i < geo.obsTris.size(); ++i) { const auto &tri = geo.obsTris[i]; - if (tri.cls != WTO_OBS_HARD_SOLID) continue; + if (!hasCoverGeometry(tri.cls)) continue; const auto &a = geo.obsVerts[tri.i0]; const auto &b = geo.obsVerts[tri.i1]; @@ -1148,7 +1258,7 @@ int main(int argc, char **argv) { if (idx >= totalTiles) break; int tx = idx % tilesX; int tz = idx / tilesX; - auto br = buildSingleTile(geo, buckets[(size_t)idx], kTiers[tierIdx], tx, tz, mapMinX, mapMinZ, pois.cover, doCovers); + auto br = buildSingleTile(geo, buckets[(size_t)idx], tierIdx, tx, tz, mapMinX, mapMinZ, pois.cover, doCovers); tierTiles[tierIdx][(size_t)idx] = br.tile; if (doCovers && !br.covers.empty()) { localCov.insert(localCov.end(), br.covers.begin(), br.covers.end()); @@ -1174,6 +1284,7 @@ int main(int argc, char **argv) { if (tl && tl->header) polyCnt += tl->header->polyCount; } int pruned = pruneUnreachableIslands(meshes[tierIdx], queries[tierIdx], geo, pois); + if (!verifyDownhillLinks(*meshes[tierIdx], geo, tierIdx)) return 1; if (tierIdx == WTO_NAV_TIER_STANDARD) { markChokepoints(meshes[tierIdx], queries[tierIdx], 3.8f); } @@ -1366,7 +1477,7 @@ int main(int argc, char **argv) { std::vector pHeight((size_t)pw * ph); std::vector pFlags((size_t)pw * ph, 0); /* Bit 0: T0 walkable, Bit 1: T1 walkable, Bit 2: T2 walkable, Bit 3: shallow water, - * Bit 4: deep water, Bit 5: chokepoint, Bit 6: crushable/forest, Bit 7: bridge, Bit 8: road */ + * Bit 4: deep water, Bit 5: chokepoint, Bit 6: crushable/forest, Bit 7: bridge, Bit 8: road, Bit 9: platform */ dtQueryFilter anyF; anyF.setIncludeFlags(0xFFFF); anyF.setExcludeFlags(WTO_FLAG_BLOCKED); @@ -1403,11 +1514,14 @@ int main(int argc, char **argv) { else { fl |= (1u << ti); if (ti == WTO_NAV_TIER_STANDARD) { + unsigned short flags = 0; + meshes[ti]->getPolyFlags(ref, &flags); if (area == WTO_AREA_SHALLOW_WATER) fl |= 8; - else if (area == WTO_AREA_CHOKEPOINT) fl |= 32; - else if (area == WTO_AREA_CRUSHABLE || area == WTO_AREA_FOREST) fl |= 64; - else if (area == WTO_AREA_BRIDGE) fl |= 128; - else if (area == WTO_AREA_ROAD) fl |= 256; + if (flags & WTO_FLAG_CHOKEPOINT) fl |= 32; + if (area == WTO_AREA_CRUSHABLE || area == WTO_AREA_FOREST) fl |= 64; + if (area == WTO_AREA_BRIDGE) fl |= 128; + if ((flags & WTO_FLAG_ROAD) || area == WTO_AREA_ROAD) fl |= 256; + if (flags & WTO_FLAG_PLATFORM) fl |= 512; } } } @@ -1445,6 +1559,11 @@ int main(int argc, char **argv) { pout.write(reinterpret_cast(&npts), 4); pout.write(reinterpret_cast(sp.pts.data()), sp.pts.size() * sizeof(float)); } + if (!geo.downhillLinks.empty()) { + uint32_t count = (uint32_t)geo.downhillLinks.size(); + pout.write(reinterpret_cast(&count), sizeof(count)); + pout.write(reinterpret_cast(geo.downhillLinks.data()), count * sizeof(WtoGeoDownhillLink)); + } } for (uint32_t ti = 0; ti < WTO_NAV_TIER_COUNT; ++ti) { diff --git a/tools/navgen/extract/src/main.rs b/tools/navgen/extract/src/main.rs index 1016274..bf75484 100644 --- a/tools/navgen/extract/src/main.rs +++ b/tools/navgen/extract/src/main.rs @@ -16,8 +16,9 @@ use wt_unpack::vromfs::Vromfs; mod phys_map; const WTO_GEO_MAGIC: &[u8; 8] = b"WTOGEO\0\x01"; -const WTO_GEO_VERSION: u32 = 2; +const WTO_GEO_VERSION: u32 = 3; const WTO_GEO_FLAG_ROAD_MASK: u32 = 1; +const WTO_GEO_FLAG_DOWNHILL_LINKS: u32 = 2; const OBS_HARD_SOLID: u8 = 0; const OBS_BRIDGE_DECK: u8 = 1; @@ -25,6 +26,8 @@ const OBS_CRUSHABLE: u8 = 2; const OBS_TREE_THICK: u8 = 3; const OBS_TREE_THIN: u8 = 4; const OBS_HARD_NO_COVER: u8 = 5; +const OBS_PLATFORM: u8 = 6; +const OBS_PLATFORM_NO_COVER: u8 = 7; #[derive(Debug, Deserialize)] struct LevelPois { @@ -37,6 +40,8 @@ struct LevelPois { bounds_max: [f32; 2], #[serde(rename = "coverBake", default)] cover: CoverBakeInput, + #[serde(rename = "mapBake", default)] + map: MapBakeInput, } #[derive(Debug, Default, Deserialize)] @@ -45,6 +50,46 @@ struct CoverBakeInput { excluded_rendinst: Vec, } +#[derive(Debug, Default, Deserialize)] +#[serde(default, rename_all = "camelCase")] +struct MapBakeInput { + road_materials: Vec, + walkable_rendinst: Vec, + downhill_links: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct DownhillLink { + from: [f32; 3], + to: [f32; 3], + radius_m: f32, + width_tiers: Vec, +} + +impl DownhillLink { + fn write(&self, out: &mut impl Write) -> Result<()> { + let mut mask = 0u32; + for &tier in &self.width_tiers { + if tier >= 3 { + bail!("invalid downhill width tier {tier}"); + } + mask |= 1 << tier; + } + if mask == 0 || self.from[1] <= self.to[1] || self.radius_m <= 0.0 || + !self.radius_m.is_finite() || !self.from.iter().chain(&self.to).all(|v| v.is_finite()) + { + bail!("invalid downhill link {:?} -> {:?}", self.from, self.to); + } + for &value in self.from.iter().chain(&self.to) { + out.write_all(&value.to_le_bytes())?; + } + out.write_all(&self.radius_m.to_le_bytes())?; + out.write_all(&mask.to_le_bytes())?; + Ok(()) + } +} + #[derive(Debug, Clone)] struct PoolMeta { is_bridge: bool, @@ -273,7 +318,7 @@ fn tri_normal_y(a: [f32; 3], b: [f32; 3], c: [f32; 3]) -> f32 { if len > 1e-6 { (ny / len).abs() } else { 0.0 } } -fn build_cached_collision(c: &Collision, meta: &PoolMeta, cover_allowed: bool) -> Option { +fn build_cached_collision(c: &Collision, meta: &PoolMeta, cover_allowed: bool, platform: bool) -> Option { if meta.is_soft_foliage { return None; } @@ -294,7 +339,9 @@ fn build_cached_collision(c: &Collision, meta: &PoolMeta, cover_allowed: bool) - let scale = det3(&n.tm).abs().cbrt(); let hard_class = if cover_allowed && n.traceable() { OBS_HARD_SOLID } else { OBS_HARD_NO_COVER }; let obstacle_class = |a, b, c| { - if meta.is_bridge && tri_normal_y(a, b, c) >= 0.72 { + if platform { + if hard_class == OBS_HARD_SOLID { OBS_PLATFORM } else { OBS_PLATFORM_NO_COVER } + } else if meta.is_bridge && tri_normal_y(a, b, c) >= 0.72 { OBS_BRIDGE_DECK } else if meta.is_crushable { OBS_CRUSHABLE @@ -382,7 +429,7 @@ fn main() -> Result<()> { let aces_meta = read_aces_meta(&game_dir, &pois.level); let water_level = aces_meta.water_level; - let roads = phys_map::RoadMask::read(&level).with_context(|| format!("extracting {} roads", pois.level))?; + let roads = phys_map::RoadMask::read(&level, &pois.map.road_materials).with_context(|| format!("extracting {} roads", pois.level))?; let hm = level.heightmap()?.with_context(|| format!("{} has no HM2 heightmap", pois.level))?; let (cw, ch, crop_origin, heights) = crop_heightmap( @@ -435,6 +482,7 @@ fn main() -> Result<()> { } let excluded_cover: HashSet<_> = pois.cover.excluded_rendinst.iter().map(|name| name.to_ascii_lowercase()).collect(); + let platforms: HashSet<_> = pois.map.walkable_rendinst.iter().map(|name| name.to_ascii_lowercase()).collect(); let mut cached_cols: HashMap = HashMap::new(); for (pack_path, items) in &by_pack { let Ok(bytes) = fs::read(pack_path) else { continue }; @@ -445,7 +493,7 @@ fn main() -> Result<()> { let key = pool_name.to_ascii_lowercase(); let imp = aces_meta.destr_impulse.get(&key).copied(); let meta = classify_pool(pool_name, imp); - if let Some(cc) = build_cached_collision(&col, &meta, !excluded_cover.contains(&key)) { + if let Some(cc) = build_cached_collision(&col, &meta, !excluded_cover.contains(&key), platforms.contains(&key)) { cached_cols.insert(pool_name.clone(), cc); } } @@ -456,7 +504,7 @@ fn main() -> Result<()> { let mut verts: Vec<[f32; 3]> = Vec::with_capacity(200_000); let mut tris: Vec<([u32; 3], u8)> = Vec::with_capacity(100_000); let mut inst_used = 0usize; - let mut cls_counts = [0usize; 6]; + let mut cls_counts = [0usize; 8]; for layer in &layers { let instances = layer.instances()?; @@ -493,7 +541,7 @@ fn main() -> Result<()> { } println!( - " RIGz: pools={} cols={} noCol={} instancesInBounds={} obsTris={} [hard={} bridge={} crush={} treeThick={} treeThin={} collisionOnly={}] ({:.2}s)", + " RIGz: pools={} cols={} noCol={} instancesInBounds={} obsTris={} [hard={} bridge={} crush={} treeThick={} treeThin={} collisionOnly={} platform={} platformCollisionOnly={}] ({:.2}s)", pool_names.len(), cached_cols.len(), no_collision, @@ -505,6 +553,8 @@ fn main() -> Result<()> { cls_counts[3], cls_counts[4], cls_counts[5], + cls_counts[6], + cls_counts[7], t0.elapsed().as_secs_f32() ); @@ -515,7 +565,13 @@ fn main() -> Result<()> { // WtoGeoHeader (must match native/wto-nav/wto_nav_format.h byte-for-byte) w.write_all(WTO_GEO_MAGIC)?; w.write_all(&WTO_GEO_VERSION.to_le_bytes())?; - let flags = if roads.is_some() { WTO_GEO_FLAG_ROAD_MASK } else { 0 }; + let mut flags = 0; + if roads.is_some() { + flags |= WTO_GEO_FLAG_ROAD_MASK; + } + if !pois.map.downhill_links.is_empty() { + flags |= WTO_GEO_FLAG_DOWNHILL_LINKS; + } w.write_all(&flags.to_le_bytes())?; w.write_all(&ever_sha1)?; w.write_all(&water_level.to_le_bytes())?; @@ -551,6 +607,12 @@ fn main() -> Result<()> { if let Some(roads) = roads { roads.write(&mut w)?; } + if !pois.map.downhill_links.is_empty() { + w.write_all(&(pois.map.downhill_links.len() as u32).to_le_bytes())?; + for link in &pois.map.downhill_links { + link.write(&mut w)?; + } + } w.flush()?; println!(" wrote {} ({:.1} MB)", out_path.display(), fs::metadata(&out_path)?.len() as f64 / (1024.0 * 1024.0)); Ok(()) diff --git a/tools/navgen/extract/src/phys_map.rs b/tools/navgen/extract/src/phys_map.rs index 2e127e0..bc414cc 100644 --- a/tools/navgen/extract/src/phys_map.rs +++ b/tools/navgen/extract/src/phys_map.rs @@ -18,7 +18,7 @@ pub struct RoadMask { } impl RoadMask { - pub fn read(level: &Level<'_>) -> Result> { + pub fn read(level: &Level<'_>, road_materials: &[String]) -> Result> { let Some(info) = level.phys_map_info()? else { return Ok(None); }; @@ -44,7 +44,7 @@ impl RoadMask { matches!( name.to_ascii_lowercase().as_str(), "road" | "roadsoil" | "roadsand" | "roadsnow" | "roadmud" - ) + ) || road_materials.iter().any(|material| name.eq_ignore_ascii_case(material)) }) .collect(); if !is_road.contains(&true) { diff --git a/tools/navgen/mission-bounds.mts b/tools/navgen/mission-bounds.mts index 707e76f..d17f57d 100644 --- a/tools/navgen/mission-bounds.mts +++ b/tools/navgen/mission-bounds.mts @@ -9,7 +9,7 @@ * --out "build\nav-work" \ * --levels avg_berlin,avg_poland,avg_hurtgen */ -import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { join, resolve } from 'node:path'; import { TuningReader } from '../../apps/server/src/tuning/tuning-reader.ts'; import { parseJsonc } from '../../packages/jsonc/src/index.ts'; @@ -35,6 +35,7 @@ interface LevelPois { readonly team2Spawns: readonly PoiPoint[]; readonly captureZones: readonly PoiPoint[]; readonly coverBake: ReturnType; + readonly mapBake?: NonNullable>; } function parseArgs(argv: string[]) { @@ -161,6 +162,31 @@ function readCoverBake() { }; } +function readMapBake(level: string) { + const path = join(import.meta.dirname, '..', '..', 'apps', 'server', 'tuning', 'maps', level + '.jsonc'); + if (!existsSync(path)) return undefined; + const map = new TuningReader(path, parseJsonc(readFileSync(path, 'utf8'))); + if (map.string('level') !== level) throw new Error('Mismatched level in ' + path); + map.int('version', { min: 1, max: 1 }); + if (!map.has('bake')) return undefined; + const bake = map.object('bake'); + const point = (r: TuningReader) => [r.number('x'), r.number('y'), r.number('z')] as const; + const downhillLinks = bake.has('downhillLinks') ? bake.list('downhillLinks', (link) => { + const from = point(link.object('from')); + const to = point(link.object('to')); + const widthTiers = link.intList('widthTiers', { min: 0, max: 2 }); + if (!widthTiers.length || from[1] <= to[1] || (from[0] === to[0] && from[2] === to[2])) { + throw new Error('Invalid downhill link in ' + path); + } + return { from, to, radiusM: link.number('radiusM', { min: 0.01 }), widthTiers }; + }) : []; + return { + roadMaterials: bake.has('roadMaterials') ? bake.stringList('roadMaterials') : [], + walkableRendinst: bake.has('walkableRendinst') ? bake.stringList('walkableRendinst') : [], + downhillLinks, + }; +} + function main() { const { gameDir, outDir, levelsFilter } = parseArgs(process.argv.slice(2)); const coverBake = readCoverBake(); @@ -276,6 +302,7 @@ function main() { } // Expand battle-area union by 120m safety padding const margin = 120; + const mapBake = readMapBake(levelKey); const out: LevelPois = { level: levelKey, levelPath: acc.levelPath, @@ -286,6 +313,7 @@ function main() { team2Spawns: t2, captureZones: caps, coverBake, + ...(mapBake && { mapBake }), }; const outPath = join(outDir, `${levelKey}.pois.json`); writeFileSync(outPath, `${JSON.stringify(out, null, 2)}\n`, 'utf8'); diff --git a/tools/navgen/render-preview.py b/tools/navgen/render-preview.py index 6b33d84..819b5b6 100644 --- a/tools/navgen/render-preview.py +++ b/tools/navgen/render-preview.py @@ -127,6 +127,13 @@ def main() -> None: off += npts * 12 paths.append([(pts[i * 3], pts[i * 3 + 2]) for i in range(npts)]) + downhill = [] + if off < len(data): + count, = struct.unpack_from(" None: # Bright green = T2 (wide heavy) + T1 + T0 walkable # Mid-green = T1 + T0 walkable (standard tank fits, wide heavy doesn't) # Yellow-green = T0 only (narrow tank alley) - # Tan = road, Orange = chokepoint, Olive = crushable/forest, Teal = bridge + # Tan = road, Ochre = narrow road, Orange = chokepoint, + # Olive = crushable/forest, Teal = bridge, Pale green = platform r, g, b = base, base, base if fl & 16: # deep water r, g, b = 22, 58, 125 @@ -165,12 +173,14 @@ def main() -> None: r, g, b = 55, 130, 185 elif fl & 128: # bridge r, g, b = 70, 210, 210 + elif fl & 512: # platform + r, g, b = 102, 185, 152 + elif fl & 256: # road, including road polygons flagged as narrow + r, g, b = (197, 154, 97) if fl & 32 else (174, 149, 108) elif fl & 32: # chokepoint r, g, b = 220, 145, 45 elif fl & 64: # crushable/forest r, g, b = int(base * 0.6 + 65), int(base * 0.8 + 85), int(base * 0.5 + 35) - elif fl & 256: # road - r, g, b = 174, 149, 108 elif fl & 4: # T2 wide walkable r, g, b = int(base * 0.5 + 48), int(base * 0.7 + 125), int(base * 0.5 + 52) elif fl & 2: # T1 standard walkable @@ -209,6 +219,21 @@ def main() -> None: x1, y1 = world_to_px(*path[i + 1]) draw_line(nav_rgb, pw, ph, x0, y0, x1, y1, (0, 245, 255), thick=2) + for link in downhill: + x0, y0 = world_to_px(link[0], link[2]) + x1, y1 = world_to_px(link[3], link[5]) + length = math.hypot(x1 - x0, y1 - y0) + if length == 0: + continue + color = (244, 108, 210) + ux, uy = (x1 - x0) / length, (y1 - y0) / length + head = min(6.0, length / 2) + draw_line(nav_rgb, pw, ph, x0, y0, x1, y1, color, thick=2) + for side in (-1, 1): + bx = round(x1 - head * ux - side * head * uy * 0.5) + by = round(y1 - head * uy + side * head * ux * 0.5) + draw_line(nav_rgb, pw, ph, x1, y1, bx, by, color, thick=2) + # Overlay spawns & capture zones on BOTH maps for rgb in (nav_rgb, cov_rgb): for sp in pois.get("team1Spawns", []): From 21ab1084a66fd594fc9190fad107d2dfa6a46c9e Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sat, 5 Dec 2026 12:42:40 +0800 Subject: [PATCH 05/19] fix(navgen): bake crushable riExtra objects and true chokepoints Read both damage tables in config/rendinst_dmg.blk. riExtra blocks are named after each destructible object and often carry hp without a destructionImpulse, so dry-stone and wooden fences, metal railings, sandbags and car wrecks were baked as solid walls. Stock damage data now decides before model-name guesses, with the impulse and hp limits in the navBake tuning section. Flag chokepoints on the eroded voxel field instead of per polygon. A span is a chokepoint only when no passable span within reach has room for a passage chokepointMaxWidthVehicles wide, so long polygons touching a wall no longer mark open yards. Chokepoints become WTO_FLAG_CHOKEPOINT on all three tiers and keep their surface area. Let roads cover rough slopes, map Poland's concrete streets as road, and add an extractor --report with ground material shares and per-object classification. Previews draw short cover ticks and record 300 DPI. Verified with Rust release and MSVC builds without warnings, TypeScript checks, and rebakes of Berlin, Poland and Hurtgen on 2.61.0.58 with 15/15, 416/416 and 840/840 spawn-to-capture connectivity on every tier. --- apps/server/tuning/ground-ai.jsonc | 12 ++ apps/server/tuning/maps/avg_poland.jsonc | 8 + native/wto-nav/wto_nav_format.h | 6 +- tools/navgen/bake/bake.cpp | 152 +++++++++++---- tools/navgen/extract/src/main.rs | 238 +++++++++++++++++++---- tools/navgen/extract/src/phys_map.rs | 89 ++++++--- tools/navgen/mission-bounds.mts | 21 +- tools/navgen/render-preview.py | 16 +- 8 files changed, 430 insertions(+), 112 deletions(-) create mode 100644 apps/server/tuning/maps/avg_poland.jsonc diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index b6353dd..4a719c8 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -104,6 +104,18 @@ "excludedCoverRendinst": ["stone_fence_a", "damaged_stone_fence_a", "damaged_stone_fence_b"] }, + // Offline navigation mesh baking parameters, copied into the generator's per-level POI input. + "navBake": { + // Placed objects whose stock destructionImpulse (config/rendinst_dmg.blk) is at most this + // value are knocked down by tanks and baked as crushable rather than solid (N*s). + "crushableMaxImpulse": 45000, + // riExtra objects with no destructionImpulse are crushable when their stock hp is at most + // this value (wooden fences 2, dry-stone fences 12, car wrecks 20; buses 40). + "crushableMaxRiExtraHp": 20, + // Passages narrower than this many standard-tier vehicle widths are flagged as chokepoints. + "chokepointMaxWidthVehicles": 2.0 + }, + "navigation": { // "vehicle_phys" uses custom inputs with native ownership. "movesys" keeps stock movement. "driveMode": "vehicle_phys", diff --git a/apps/server/tuning/maps/avg_poland.jsonc b/apps/server/tuning/maps/avg_poland.jsonc new file mode 100644 index 0000000..d2eb2af --- /dev/null +++ b/apps/server/tuning/maps/avg_poland.jsonc @@ -0,0 +1,8 @@ +{ + "level": "avg_poland", + "version": 1, + "bake": { + // The town streets and squares use this LMp2 material. + "roadMaterials": ["concrete"] + } +} diff --git a/native/wto-nav/wto_nav_format.h b/native/wto-nav/wto_nav_format.h index efdc3d8..119bebc 100644 --- a/native/wto-nav/wto_nav_format.h +++ b/native/wto-nav/wto_nav_format.h @@ -36,7 +36,7 @@ enum WtoPolyArea { WTO_AREA_FOREST = 5, WTO_AREA_CRUSHABLE = 6, WTO_AREA_SHALLOW_WATER = 7, - WTO_AREA_CHOKEPOINT = 8, + WTO_AREA_CHOKEPOINT = 8, /* Not baked: chokepoints keep their surface area, see WTO_FLAG_CHOKEPOINT */ WTO_AREA_EXPOSED = 9, WTO_AREA_DEEP_WATER = 10, WTO_AREA_NO_GO = 11 @@ -47,9 +47,9 @@ enum WtoPolyFlag { WTO_FLAG_WALK = 0x01, WTO_FLAG_SHALLOW_WATER = 0x02, WTO_FLAG_DEEP_WATER = 0x04, - WTO_FLAG_CHOKEPOINT = 0x08, + WTO_FLAG_CHOKEPOINT = 0x08, /* Narrower than navBake.chokepointMaxWidthVehicles for this mesh's tier */ WTO_FLAG_BLOCKED = 0x10, - WTO_FLAG_ROAD = 0x20, /* Surface identity, retained on chokepoint polygons */ + WTO_FLAG_ROAD = 0x20, /* Surface identity, set on road polygons */ WTO_FLAG_DOWNHILL = 0x40, /* One-way Detour connection */ WTO_FLAG_PLATFORM = 0x80 /* Walkable top of a validated placed object */ }; diff --git a/tools/navgen/bake/bake.cpp b/tools/navgen/bake/bake.cpp index 86c89fc..c72fdc0 100644 --- a/tools/navgen/bake/bake.cpp +++ b/tools/navgen/bake/bake.cpp @@ -59,6 +59,7 @@ struct CoverBake { struct PoisData { CoverBake cover{}; + float chokepointMaxWidthVehicles = 0.0f; std::vector t1Spawns; std::vector t2Spawns; std::vector caps; @@ -95,6 +96,9 @@ static constexpr float kExtraCoverColumnM = 2.6f; static constexpr float kGeometryToleranceM = 0.001f; // Intermediate Recast area. Its serialized area is ground. static constexpr unsigned char kPlatformArea = RC_WALKABLE_AREA - 1; +// Intermediate Recast area bit that splits chokepoint polygons from their surroundings. It is +// stripped from the serialized area and becomes WTO_FLAG_CHOKEPOINT. +static constexpr unsigned char kChokeAreaBit = 0x20; static bool hasCoverGeometry(uint8_t cls) { return cls == WTO_OBS_HARD_SOLID || cls == WTO_OBS_PLATFORM; @@ -270,6 +274,11 @@ static bool loadPois(const std::string &path, PoisData &out) { std::fprintf(stderr, "Invalid cover baking settings in %s. Regenerate it with mission-bounds.mts.\n", path.c_str()); return false; } + out.chokepointMaxWidthVehicles = readJsonNumber(content, "chokepointMaxWidthVehicles", -1.0f); + if (!(out.chokepointMaxWidthVehicles >= 1.0f && out.chokepointMaxWidthVehicles <= 4.0f)) { + std::fprintf(stderr, "Invalid navigation baking settings in %s. Regenerate it with mission-bounds.mts.\n", path.c_str()); + return false; + } parsePoiArray(content, "team1Spawns", out.t1Spawns); parsePoiArray(content, "team2Spawns", out.t2Spawns); parsePoiArray(content, "captureZones", out.caps); @@ -376,12 +385,95 @@ static void markRoadAreas(rcCompactHeightfield &field, const GeoData &geo) { if (!geo.isRoad(wx, wz)) continue; const rcCompactCell &cell = field.cells[x + z * field.width]; for (unsigned int i = cell.index; i < cell.index + cell.count; ++i) { - if (field.areas[i] == WTO_AREA_GROUND) field.areas[i] = WTO_AREA_ROAD; + if (field.areas[i] == WTO_AREA_GROUND || field.areas[i] == WTO_AREA_ROUGH) field.areas[i] = WTO_AREA_ROAD; } } } } +/* Visits the up to eight spans around span `i` at cell (x, z) that it connects to. */ +template +static void forEachNeighborSpan(const rcCompactHeightfield &field, int x, int z, int i, Fn &&fn) { + const rcCompactSpan &span = field.spans[i]; + for (int dir = 0; dir < 4; ++dir) { + int con = rcGetCon(span, dir); + if (con == RC_NOT_CONNECTED) continue; + int ax = x + rcGetDirOffsetX(dir); + int az = z + rcGetDirOffsetY(dir); + int ai = (int)field.cells[ax + az * field.width].index + con; + fn(ai, false); + int dir2 = (dir + 1) & 3; + int con2 = rcGetCon(field.spans[ai], dir2); + if (con2 == RC_NOT_CONNECTED) continue; + int bx = ax + rcGetDirOffsetX(dir2); + int bz = az + rcGetDirOffsetY(dir2); + fn((int)field.cells[bx + bz * field.width].index + con2, true); + } +} + +/* + * Flags narrow passages on the eroded compact heightfield. Erosion already removed the vehicle's + * own half width, so a span's chamfer distance to the nearest impassable span is the room left + * beside the vehicle. A span lies in a chokepoint when no passable span within reach has at least + * `clearanceM` of room; spans that touch a wall beside open ground keep their plain surface. + */ +static int markChokepointSpans(rcCompactHeightfield &field, float clearanceM) { + auto passable = [](unsigned char area) { + return area != RC_NULL_AREA && area != WTO_AREA_DEEP_WATER && area != WTO_AREA_NO_GO; + }; + const int threshold = (int)std::lround(2.0f * clearanceM / field.cs); /* 2 = one cell */ + const int reachCells = (int)std::ceil(clearanceM / field.cs) + 1; + const int n = field.spanCount; + std::vector dist((size_t)n, 0); + for (int i = 0; i < n; ++i) dist[(size_t)i] = passable(field.areas[i]) ? 0xffff : 0; + + /* Distances beyond the threshold need not be exact, so relax only as far as it reaches. */ + for (int pass = 0; pass <= threshold / 2 + 1; ++pass) { + for (int z = 0; z < field.height; ++z) { + for (int x = 0; x < field.width; ++x) { + const rcCompactCell &cell = field.cells[x + z * field.width]; + for (int i = (int)cell.index, end = (int)(cell.index + cell.count); i < end; ++i) { + if (!dist[(size_t)i]) continue; + uint16_t best = dist[(size_t)i]; + forEachNeighborSpan(field, x, z, i, [&](int ni, bool diagonal) { + int d = (int)dist[(size_t)ni] + (diagonal ? 3 : 2); + if (d < best) best = (uint16_t)d; + }); + dist[(size_t)i] = best; + } + } + } + } + + std::vector room = dist, next((size_t)n); + for (int step = 0; step < reachCells; ++step) { + for (int z = 0; z < field.height; ++z) { + for (int x = 0; x < field.width; ++x) { + const rcCompactCell &cell = field.cells[x + z * field.width]; + for (int i = (int)cell.index, end = (int)(cell.index + cell.count); i < end; ++i) { + uint16_t best = room[(size_t)i]; + if (dist[(size_t)i]) { + forEachNeighborSpan(field, x, z, i, [&](int ni, bool) { + if (dist[(size_t)ni] && room[(size_t)ni] > best) best = room[(size_t)ni]; + }); + } + next[(size_t)i] = best; + } + } + } + room.swap(next); + } + + int marked = 0; + for (int i = 0; i < n; ++i) { + unsigned char area = field.areas[i]; + if (!dist[(size_t)i] || room[(size_t)i] >= threshold || area >= kChokeAreaBit) continue; + field.areas[i] = (unsigned char)(area | kChokeAreaBit); + marked++; + } + return marked; +} + struct BuiltTile { int tx = 0; int tz = 0; @@ -400,7 +492,8 @@ static TileBakeResult buildSingleTile( uint32_t tierIndex, int tx, int tz, float mapMinX, float mapMinZ, - const CoverBake &coverTuning, bool bakeCovers + const CoverBake &coverTuning, bool bakeCovers, + float chokeClearanceM ) { TileBakeResult res; res.tile.tx = tx; @@ -424,6 +517,10 @@ static TileBakeResult buildSingleTile( cfg.borderSize = cfg.walkableRadius + 3; // Cover and corner rays must see hard collision on the other side of tile boundaries. if (bakeCovers) cfg.borderSize = std::max(cfg.borderSize, coverBorderCells(coverTuning)); + // Erosion walls off the heightfield edge; chokepoint reach must stay clear of that band. + if (chokeClearanceM > 0.0f) { + cfg.borderSize = std::max(cfg.borderSize, cfg.walkableRadius + 2 * (int)std::ceil(chokeClearanceM / cfg.cs) + 4); + } cfg.width = cfg.tileSize + cfg.borderSize * 2; cfg.height = cfg.tileSize + cfg.borderSize * 2; cfg.detailSampleDist = 12.0f * cfg.cs; @@ -586,6 +683,7 @@ static TileBakeResult buildSingleTile( rcMedianFilterWalkableArea(&ctx, *chf); rcMedianFilterWalkableArea(&ctx, *chf); markRoadAreas(*chf, geo); + if (chokeClearanceM > 0.0f) markChokepointSpans(*chf, chokeClearanceM); if (!rcBuildDistanceField(&ctx, *chf) || !rcBuildRegions(&ctx, *chf, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea)) { @@ -629,6 +727,8 @@ static TileBakeResult buildSingleTile( /* Assign initial polygon flags from Area ID */ for (int i = 0; i < pmesh->npolys; ++i) { unsigned char a = pmesh->areas[i]; + const bool choke = a != RC_NULL_AREA && a < kPlatformArea && (a & kChokeAreaBit); + if (choke) a = pmesh->areas[i] = (unsigned char)(a & ~kChokeAreaBit); if (a == WTO_AREA_DEEP_WATER) pmesh->flags[i] = WTO_FLAG_DEEP_WATER; else if (a == WTO_AREA_SHALLOW_WATER) pmesh->flags[i] = WTO_FLAG_WALK | WTO_FLAG_SHALLOW_WATER; else if (a == WTO_AREA_NO_GO) pmesh->flags[i] = WTO_FLAG_BLOCKED; @@ -638,6 +738,7 @@ static TileBakeResult buildSingleTile( pmesh->flags[i] = WTO_FLAG_WALK | WTO_FLAG_PLATFORM; } else if (a != RC_NULL_AREA) pmesh->flags[i] = WTO_FLAG_WALK; else pmesh->flags[i] = 0; + if (choke && (pmesh->flags[i] & WTO_FLAG_WALK)) pmesh->flags[i] |= WTO_FLAG_CHOKEPOINT; } dtNavMeshCreateParams params{}; @@ -833,38 +934,16 @@ static bool verifyDownhillLinks(const dtNavMesh &mesh, const GeoData &geo, uint3 return true; } -static void markChokepoints(dtNavMesh *mesh, dtNavMeshQuery *query, float chokeDistM) { - dtQueryFilter filter; - filter.setIncludeFlags(WTO_FLAG_WALK); - filter.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED); - const dtNavMesh *cmesh = mesh; - for (int i = 0; i < cmesh->getMaxTiles(); ++i) { - const dtMeshTile *tile = cmesh->getTile(i); +static int countChokepointPolys(const dtNavMesh &mesh) { + int count = 0; + for (int i = 0; i < mesh.getMaxTiles(); ++i) { + const dtMeshTile *tile = mesh.getTile(i); if (!tile || !tile->header) continue; - dtPolyRef base = cmesh->getPolyRefBase(tile); for (int p = 0; p < tile->header->polyCount; ++p) { - const dtPoly &poly = tile->polys[p]; - if (poly.getType() == DT_POLYTYPE_OFFMESH_CONNECTION) continue; - uint8_t area = poly.getArea(); - if (area == WTO_AREA_DEEP_WATER || area == WTO_AREA_SHALLOW_WATER) continue; - float cx = 0, cy = 0, cz = 0; - for (int v = 0; v < poly.vertCount; ++v) { - const float *vp = &tile->verts[poly.verts[v] * 3]; - cx += vp[0]; cy += vp[1]; cz += vp[2]; - } - float inv = 1.0f / (float)poly.vertCount; - float pos[3] = { cx * inv, cy * inv, cz * inv }; - dtPolyRef ref = base | (dtPolyRef)p; - float hitDist = 999.0f; - float hitPos[3], hitNorm[3]; - if (dtStatusSucceed(query->findDistanceToWall(ref, pos, chokeDistM + 1.0f, &filter, &hitDist, hitPos, hitNorm))) { - if (hitDist < chokeDistM) { - mesh->setPolyArea(ref, WTO_AREA_CHOKEPOINT); - mesh->setPolyFlags(ref, poly.flags | WTO_FLAG_CHOKEPOINT); - } - } + if (tile->polys[p].flags & WTO_FLAG_CHOKEPOINT) count++; } } + return count; } struct CoverRay { @@ -1245,6 +1324,8 @@ int main(int argc, char **argv) { for (uint32_t tierIdx = 0; tierIdx < WTO_NAV_TIER_COUNT; ++tierIdx) { const bool doCovers = (tierIdx == WTO_NAV_TIER_STANDARD); + /* Room beside the vehicle left in a passage exactly chokepointMaxWidthVehicles wide. */ + const float chokeClearanceM = (pois.chokepointMaxWidthVehicles - 1.0f) * kTiers[tierIdx].agentRadius; tierTiles[tierIdx].resize((size_t)totalTiles); std::atomic nextTile{ 0 }; std::mutex covMtx; @@ -1258,7 +1339,7 @@ int main(int argc, char **argv) { if (idx >= totalTiles) break; int tx = idx % tilesX; int tz = idx / tilesX; - auto br = buildSingleTile(geo, buckets[(size_t)idx], tierIdx, tx, tz, mapMinX, mapMinZ, pois.cover, doCovers); + auto br = buildSingleTile(geo, buckets[(size_t)idx], tierIdx, tx, tz, mapMinX, mapMinZ, pois.cover, doCovers, chokeClearanceM); tierTiles[tierIdx][(size_t)idx] = br.tile; if (doCovers && !br.covers.empty()) { localCov.insert(localCov.end(), br.covers.begin(), br.covers.end()); @@ -1285,11 +1366,9 @@ int main(int argc, char **argv) { } int pruned = pruneUnreachableIslands(meshes[tierIdx], queries[tierIdx], geo, pois); if (!verifyDownhillLinks(*meshes[tierIdx], geo, tierIdx)) return 1; - if (tierIdx == WTO_NAV_TIER_STANDARD) { - markChokepoints(meshes[tierIdx], queries[tierIdx], 3.8f); - } - std::printf(" %s (r=%.2fm): tiles=%d/%d polys=%d prunedIslands=%d\n", - kTiers[tierIdx].name, kTiers[tierIdx].agentRadius, builtCnt, totalTiles, polyCnt, pruned); + std::printf(" %s (r=%.2fm): tiles=%d/%d polys=%d chokepointPolys=%d prunedIslands=%d\n", + kTiers[tierIdx].name, kTiers[tierIdx].agentRadius, builtCnt, totalTiles, polyCnt, + countChokepointPolys(*meshes[tierIdx]), pruned); } /* Dedupe + retreat-verify tank covers on Tier 1 */ @@ -1362,7 +1441,6 @@ int main(int argc, char **argv) { pf.setAreaCost(WTO_AREA_FOREST, 2.10f); pf.setAreaCost(WTO_AREA_CRUSHABLE, 2.40f); pf.setAreaCost(WTO_AREA_SHALLOW_WATER, 2.60f); - pf.setAreaCost(WTO_AREA_CHOKEPOINT, 1.80f); const float snapExt[3] = { 12.0f, 12.0f, 12.0f }; std::vector allSpawns = pois.t1Spawns; diff --git a/tools/navgen/extract/src/main.rs b/tools/navgen/extract/src/main.rs index bf75484..5ab795b 100644 --- a/tools/navgen/extract/src/main.rs +++ b/tools/navgen/extract/src/main.rs @@ -5,7 +5,7 @@ use std::path::{Path, PathBuf}; use std::time::Instant; use anyhow::{bail, Context, Result}; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use wt_formats::grp::GrpPack; use wt_unpack::blk::{self, Value}; use wt_unpack::collision::{Collision, CollisionNode, NodeKind, COLLISION}; @@ -40,10 +40,19 @@ struct LevelPois { bounds_max: [f32; 2], #[serde(rename = "coverBake", default)] cover: CoverBakeInput, + #[serde(rename = "navBake")] + nav: NavBakeInput, #[serde(rename = "mapBake", default)] map: MapBakeInput, } +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct NavBakeInput { + crushable_max_impulse: f32, + crushable_max_ri_extra_hp: f32, +} + #[derive(Debug, Default, Deserialize)] struct CoverBakeInput { #[serde(rename = "excludedCoverRendinst", default)] @@ -103,34 +112,105 @@ struct CachedCollision { tris: Vec<([f32; 3], [f32; 3], [f32; 3], u8)>, } -fn parse_args() -> Result<(PathBuf, PathBuf, PathBuf)> { +struct Args { + game: PathBuf, + pois: PathBuf, + out: PathBuf, + report: Option, +} + +fn parse_args() -> Result { let mut game: Option = None; let mut pois: Option = None; let mut out: Option = None; + let mut report: Option = None; let mut args = std::env::args().skip(1); while let Some(a) = args.next() { match a.as_str() { "--game" => game = args.next().map(PathBuf::from), "--pois" => pois = args.next().map(PathBuf::from), "--out" => out = args.next().map(PathBuf::from), + "--report" => report = args.next().map(PathBuf::from), other => bail!("unknown argument: {other}"), } } - Ok(( - game.context("missing --game ")?, - pois.context("missing --pois ")?, - out.context("missing --out ")?, - )) + Ok(Args { + game: game.context("missing --game ")?, + pois: pois.context("missing --pois ")?, + out: out.context("missing --out ")?, + report, + }) +} + +/// Development report: what the extractor found and how it classified it. +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct ExtractReport { + level: String, + ground_materials: Vec, + pools: Vec, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct MaterialReport { + name: String, + road: bool, + share: f64, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct PoolReport { + name: String, + instances: usize, + class: &'static str, + #[serde(skip_serializing_if = "Option::is_none")] + destruction_impulse: Option, + #[serde(skip_serializing_if = "Option::is_none")] + ri_extra_hp: Option, + #[serde(skip_serializing_if = "Option::is_none")] + collision_size: Option<[f32; 3]>, +} + +/// Stock damage data for one placed object from `config/rendinst_dmg.blk`. Plain rendinst are +/// listed in `dmg` blocks by `name`; riExtra objects are blocks named after the object under `riExtra`. +#[derive(Debug, Default, Clone)] +struct DamageInfo { + destruction_impulse: Option, + immortal: bool, + ri_extra_hp: Option, +} + +impl DamageInfo { + /// Whether a moving tank knocks the object down, or `None` when the stock data does not say. + fn crushable(&self, nav: &NavBakeInput) -> Option { + if let Some(impulse) = self.destruction_impulse.filter(|v| *v > 0.0) { + return Some(impulse <= nav.crushable_max_impulse); + } + if self.immortal { + return Some(false); + } + self.ri_extra_hp.filter(|v| *v > 0.0).map(|hp| hp <= nav.crushable_max_ri_extra_hp) + } } struct AcesMeta { water_level: f32, - /// Authoritative tank-crushable impulse threshold from `config/rendinst_dmg.blk` (lowercase name -> destructionImpulse). - destr_impulse: HashMap, + /// Lowercase object name -> stock damage data. + damage: HashMap, +} + +fn blk_number(value: &Value) -> Option { + match value { + Value::Real(x) => Some(*x), + Value::Int(x) => Some(*x as f32), + _ => None, + } } fn read_aces_meta(game: &Path, level_name: &str) -> AcesMeta { - let mut meta = AcesMeta { water_level: -1.0e6, destr_impulse: HashMap::new() }; + let mut meta = AcesMeta { water_level: -1.0e6, damage: HashMap::new() }; let aces_path = game.join("aces.vromfs.bin"); let Ok(raw) = fs::read(&aces_path) else { return meta; }; let Ok(arc) = Vromfs::parse(&raw) else { return meta; }; @@ -164,21 +244,35 @@ fn read_aces_meta(game: &Path, level_name: &str) -> AcesMeta { if let Some(dmg_entry) = arc.files.iter().find(|f| f.name.eq_ignore_ascii_case("config/rendinst_dmg.blk")) { if let Ok(doc) = blk::parse(&dmg_entry.data, shared.as_ref()) { for b in &doc.blocks { + if b.name.eq_ignore_ascii_case("riExtra") { + for entry in &b.blocks { + let info = meta.damage.entry(entry.name.to_lowercase()).or_default(); + for (k, v) in &entry.params { + if k.eq_ignore_ascii_case("destructionImpulse") { + info.destruction_impulse = blk_number(v).or(info.destruction_impulse); + } else if k.eq_ignore_ascii_case("hp") { + info.ri_extra_hp = blk_number(v); + } + } + } + continue; + } let mut rname: Option<&str> = None; let mut impulse: Option = None; + let mut immortal = false; for (k, v) in &b.params { if k.eq_ignore_ascii_case("name") { if let Value::Str(s) = v { rname = Some(s.as_str()); } } else if k.eq_ignore_ascii_case("destructionImpulse") { - match v { - Value::Real(x) => impulse = Some(*x), - Value::Int(x) => impulse = Some(*x as f32), - _ => {} - } + impulse = blk_number(v); + } else if k.eq_ignore_ascii_case("immortal") { + immortal = matches!(v, Value::Bool(true)); } } - if let (Some(n), Some(imp)) = (rname, impulse) { - meta.destr_impulse.insert(n.to_lowercase(), imp); + if let Some(n) = rname { + let info = meta.damage.entry(n.to_lowercase()).or_default(); + info.destruction_impulse = impulse.or(info.destruction_impulse); + info.immortal |= immortal; } } } @@ -186,7 +280,7 @@ fn read_aces_meta(game: &Path, level_name: &str) -> AcesMeta { meta } -fn classify_pool(name: &str, destr_impulse: Option) -> PoolMeta { +fn classify_pool(name: &str, damage: Option<&DamageInfo>, nav: &NavBakeInput) -> PoolMeta { let lower = name.to_lowercase(); let is_bridge = lower.contains("bridge") || lower.contains("viaduct") @@ -212,6 +306,9 @@ fn classify_pool(name: &str, destr_impulse: Option) -> PoolMeta { || lower.contains("tank_wreck") || is_bridge; + // Stock damage data decides when it exists; model names are only a fallback. + let stock_crushable = if is_bridge { None } else { damage.and_then(|d| d.crushable(nav)) }; + let is_soft_foliage = !always_hard && (lower.starts_with("bush_") || lower.contains("_bush_") @@ -222,19 +319,20 @@ fn classify_pool(name: &str, destr_impulse: Option) -> PoolMeta { || lower.contains("flower") || lower.contains("fern")); - // Authoritative War Thunder physics: objects in `config/rendinst_dmg.blk` with low - // `destructionImpulse` (<= 45,000 N*s) are crushed on contact by moving tanks (wooden fences, - // lamp posts, hedges, benches, sheds, destructible thin walls, small trees). - let is_crushable = !always_hard - && match destr_impulse { - Some(imp) if imp > 0.0 && imp <= 45_000.0 => true, - _ => lower.contains("fence_wood") - || lower.contains("wooden_fence") - || lower.contains("hedge") - || lower.contains("sign_") - || lower.contains("bench") - || lower.contains("hay"), - }; + // Stock War Thunder physics: low destructionImpulse or low riExtra hp means a moving tank + // knocks the object down (wooden and dry-stone fences, lamp posts, sheds, small trees). + let is_crushable = match stock_crushable { + Some(crushable) => crushable, + None => { + !always_hard + && (lower.contains("fence_wood") + || lower.contains("wooden_fence") + || lower.contains("hedge") + || lower.contains("sign_") + || lower.contains("bench") + || lower.contains("hay")) + } + }; PoolMeta { is_bridge, is_crushable, is_soft_foliage } } @@ -416,7 +514,7 @@ fn crop_heightmap(hm: &Heightmap, min_x: f32, min_z: f32, max_x: f32, max_z: f32 fn main() -> Result<()> { let t0 = Instant::now(); - let (game_dir, pois_path, out_path) = parse_args()?; + let Args { game: game_dir, pois: pois_path, out: out_path, report: report_path } = parse_args()?; let pois: LevelPois = serde_json::from_str( &fs::read_to_string(&pois_path).with_context(|| format!("reading {}", pois_path.display()))?, )?; @@ -429,7 +527,9 @@ fn main() -> Result<()> { let aces_meta = read_aces_meta(&game_dir, &pois.level); let water_level = aces_meta.water_level; - let roads = phys_map::RoadMask::read(&level, &pois.map.road_materials).with_context(|| format!("extracting {} roads", pois.level))?; + let phys_map = phys_map::PhysMap::read(&level, &pois.map.road_materials) + .with_context(|| format!("extracting {} ground materials", pois.level))?; + let roads = phys_map.as_ref().filter(|map| map.has_road()); let hm = level.heightmap()?.with_context(|| format!("{} has no HM2 heightmap", pois.level))?; let (cw, ch, crop_origin, heights) = crop_heightmap( @@ -484,6 +584,7 @@ fn main() -> Result<()> { let excluded_cover: HashSet<_> = pois.cover.excluded_rendinst.iter().map(|name| name.to_ascii_lowercase()).collect(); let platforms: HashSet<_> = pois.map.walkable_rendinst.iter().map(|name| name.to_ascii_lowercase()).collect(); let mut cached_cols: HashMap = HashMap::new(); + let mut pool_reports: HashMap = HashMap::new(); for (pack_path, items) in &by_pack { let Ok(bytes) = fs::read(pack_path) else { continue }; let Ok(pack) = GrpPack::parse(&bytes) else { continue }; @@ -491,9 +592,33 @@ fn main() -> Result<()> { let Some(res) = pack.find(res_name, COLLISION) else { continue }; let Ok(col) = Collision::parse(res_name, pack.data(res)) else { continue }; let key = pool_name.to_ascii_lowercase(); - let imp = aces_meta.destr_impulse.get(&key).copied(); - let meta = classify_pool(pool_name, imp); - if let Some(cc) = build_cached_collision(&col, &meta, !excluded_cover.contains(&key), platforms.contains(&key)) { + let damage = aces_meta.damage.get(&key); + let meta = classify_pool(pool_name, damage, &pois.nav); + let cover_allowed = !excluded_cover.contains(&key); + let platform = platforms.contains(&key); + let class = if meta.is_soft_foliage { + "foliage" + } else if platform { + "platform" + } else if meta.is_bridge { + "bridge" + } else if meta.is_crushable { + "crushable" + } else if cover_allowed { + "hard" + } else { + "hardNoCover" + }; + let [lo, hi] = col.bbox; + pool_reports.insert(pool_name.clone(), PoolReport { + name: pool_name.clone(), + instances: 0, + class, + destruction_impulse: damage.and_then(|d| d.destruction_impulse), + ri_extra_hp: damage.and_then(|d| d.ri_extra_hp), + collision_size: Some([hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]]), + }); + if let Some(cc) = build_cached_collision(&col, &meta, cover_allowed, platform) { cached_cols.insert(pool_name.clone(), cc); } } @@ -510,8 +635,27 @@ fn main() -> Result<()> { let instances = layer.instances()?; for inst in instances { let Some(pool) = layer.pools.get(inst.pool) else { continue }; - let Some(cc) = cached_cols.get(&pool.name) else { continue }; let pos = inst.tm[3]; + if report_path.is_some() + && pos[0] >= crop_origin[0] && pos[0] <= crop_max_x + && pos[2] >= crop_origin[1] && pos[2] <= crop_max_z + { + pool_reports + .entry(pool.name.clone()) + .or_insert_with(|| { + let damage = aces_meta.damage.get(&pool.name.to_ascii_lowercase()); + PoolReport { + name: pool.name.clone(), + instances: 0, + class: "noCollision", + destruction_impulse: damage.and_then(|d| d.destruction_impulse), + ri_extra_hp: damage.and_then(|d| d.ri_extra_hp), + collision_size: None, + } + }) + .instances += 1; + } + let Some(cc) = cached_cols.get(&pool.name) else { continue }; // Quick XZ culling using instance scale + object bounding radius let sx = (inst.tm[0][0].powi(2) + inst.tm[0][1].powi(2) + inst.tm[0][2].powi(2)).sqrt(); let sz = (inst.tm[2][0].powi(2) + inst.tm[2][1].powi(2) + inst.tm[2][2].powi(2)).sqrt(); @@ -605,7 +749,7 @@ fn main() -> Result<()> { w.write_all(&[*cls])?; } if let Some(roads) = roads { - roads.write(&mut w)?; + roads.write_road_mask(&mut w)?; } if !pois.map.downhill_links.is_empty() { w.write_all(&(pois.map.downhill_links.len() as u32).to_le_bytes())?; @@ -615,5 +759,23 @@ fn main() -> Result<()> { } w.flush()?; println!(" wrote {} ({:.1} MB)", out_path.display(), fs::metadata(&out_path)?.len() as f64 / (1024.0 * 1024.0)); + + if let Some(report_path) = report_path { + let stats = phys_map + .as_ref() + .map(|map| map.material_stats(crop_origin, [crop_max_x, crop_max_z])) + .unwrap_or_default(); + let total = stats.iter().map(|s| s.texels).sum::().max(1) as f64; + let mut ground_materials: Vec<_> = stats + .into_iter() + .map(|s| MaterialReport { name: s.name, road: s.road, share: s.texels as f64 / total }) + .collect(); + ground_materials.sort_by(|a, b| b.share.total_cmp(&a.share)); + let mut pools: Vec<_> = pool_reports.into_values().filter(|p| p.instances > 0).collect(); + pools.sort_by(|a, b| b.instances.cmp(&a.instances).then_with(|| a.name.cmp(&b.name))); + let report = ExtractReport { level: pois.level.clone(), ground_materials, pools }; + fs::write(&report_path, serde_json::to_string_pretty(&report)?)?; + println!(" wrote report {}", report_path.display()); + } Ok(()) } diff --git a/tools/navgen/extract/src/phys_map.rs b/tools/navgen/extract/src/phys_map.rs index bc414cc..282f2aa 100644 --- a/tools/navgen/extract/src/phys_map.rs +++ b/tools/navgen/extract/src/phys_map.rs @@ -10,14 +10,23 @@ const MASK_TEXTURE_SIZE: usize = 32; const MAX_PAYLOAD: usize = 256 * 1024 * 1024; const MAX_GRID_CELLS: usize = 64 * 1024 * 1024; -pub struct RoadMask { +/// The decoded ground material map: one LMp2 material index per texel, with decals painted on top. +pub struct PhysMap { size: usize, origin: [f32; 2], cell_size: f32, cells: Vec, + materials: Vec, + is_road: Vec, } -impl RoadMask { +pub struct MaterialStat { + pub name: String, + pub road: bool, + pub texels: u64, +} + +impl PhysMap { pub fn read(level: &Level<'_>, road_materials: &[String]) -> Result> { let Some(info) = level.phys_map_info()? else { return Ok(None); @@ -47,9 +56,6 @@ impl RoadMask { ) || road_materials.iter().any(|material| name.eq_ignore_ascii_case(material)) }) .collect(); - if !is_road.contains(&true) { - return Ok(None); - } let block = level.find("LMp2").context("missing LMp2 block")?; let mut reader = Reader::at(block.data, 8)?; @@ -72,7 +78,7 @@ impl RoadMask { let payload = unpack(block_header >> 30, packed)?; let mut reader = Reader::new(&payload); if let Some(size) = legacy_size { - read_tree(&mut reader, None, &is_road, [0, 0], size)?; + read_tree(&mut reader, None, [0, 0], size)?; } let mut mask = Self { @@ -80,8 +86,10 @@ impl RoadMask { origin: info.world_origin, cell_size: info.metres_per_texel, cells: vec![0; size * size], + materials: info.materials.clone(), + is_road, }; - read_tree(&mut reader, Some(&mut mask), &is_road, [0, 0], size)?; + read_tree(&mut reader, Some(&mut mask), [0, 0], size)?; let decals = read_decals(&mut reader, info.version)?; let textures = if info.version == 0 { &[][..] @@ -94,40 +102,72 @@ impl RoadMask { let texture_bytes = MASK_TEXTURE_SIZE * size_of::(); let start = usize::from(group.texture_id) * texture_bytes; let texture = textures.get(start..start + texture_bytes); - let road = material_is_road(&is_road, group.material); for (index, face) in group.faces.chunks_exact(6).enumerate() { let vertices = indexed_points(face, &decal.vertices)?; let uvs = texture .map(|_| indexed_points(&group.uv_faces[index * 6..index * 6 + 6], &decal.uvs)) .transpose()?; - mask.paint_triangle(vertices, road, texture.zip(uvs)); + mask.paint_triangle(vertices, group.material, texture.zip(uvs)); } } } - let roads = mask.cells.iter().filter(|&&cell| cell != 0).count(); + let roads = mask.cells.iter().filter(|&&cell| mask.cell_is_road(cell)).count(); println!(" LMp2: {size}x{size} at {:.2} m, {roads} road texels", mask.cell_size); Ok(Some(mask)) } - pub fn write(&self, out: &mut impl Write) -> std::io::Result<()> { + pub fn has_road(&self) -> bool { + self.cells.iter().any(|&cell| self.cell_is_road(cell)) + } + + /// Texel counts per material inside the given world XZ rectangle. + pub fn material_stats(&self, min: [f32; 2], max: [f32; 2]) -> Vec { + let to_cell = |v: f32, axis: usize| { + (((v - self.origin[axis]) / self.cell_size).floor().max(0.0) as usize).min(self.size) + }; + let mut counts = vec![0u64; 256]; + for z in to_cell(min[1], 1)..to_cell(max[1], 1) { + for x in to_cell(min[0], 0)..to_cell(max[0], 0) { + counts[usize::from(self.cells[z * self.size + x])] += 1; + } + } + counts + .iter() + .enumerate() + .filter(|&(_, &texels)| texels > 0) + .map(|(index, &texels)| MaterialStat { + name: self.materials.get(index).cloned().unwrap_or_else(|| format!("#{index}")), + road: self.cell_is_road(index as u8), + texels, + }) + .collect() + } + + /// Writes the `.wtogeo` road mask section: one byte per texel, 1 = road. + pub fn write_road_mask(&self, out: &mut impl Write) -> std::io::Result<()> { out.write_all(&(self.size as u32).to_le_bytes())?; out.write_all(&self.origin[0].to_le_bytes())?; out.write_all(&self.origin[1].to_le_bytes())?; out.write_all(&self.cell_size.to_le_bytes())?; - out.write_all(&self.cells) + let road: Vec = self.cells.iter().map(|&cell| u8::from(self.cell_is_road(cell))).collect(); + out.write_all(&road) } - fn fill(&mut self, [x, z]: [usize; 2], size: usize, road: u8) { + fn cell_is_road(&self, material: u8) -> bool { + self.is_road.get(usize::from(material)).copied().unwrap_or(false) + } + + fn fill(&mut self, [x, z]: [usize; 2], size: usize, material: u8) { for row in z..z + size { let start = row * self.size + x; - self.cells[start..start + size].fill(road); + self.cells[start..start + size].fill(material); } } fn paint_triangle( &mut self, vertices: [[f32; 2]; 3], - road: u8, + material: u8, mask: Option<(&[u8], [[f32; 2]; 3])>, ) { let [a, b, c] = vertices.map(|[x, z]| { @@ -148,7 +188,7 @@ impl RoadMask { if weights.iter().all(|weight| *weight >= 0.0) && mask.is_none_or(|(tex, uv)| mask_covers(tex, uv, weights)) { - self.cells[z * self.size + x] = road; + self.cells[z * self.size + x] = material; } } } @@ -179,15 +219,14 @@ fn unpack(codec: u32, packed: &[u8]) -> Result> { fn read_tree( reader: &mut Reader<'_>, - mut mask: Option<&mut RoadMask>, - is_road: &[bool], + mut mask: Option<&mut PhysMap>, origin: [usize; 2], size: usize, ) -> Result<()> { let flags = reader.u8()?; if reader.u8()? == 0 { if let Some(mask) = mask { - mask.fill(origin, size, material_is_road(is_road, flags)); + mask.fill(origin, size, flags); } return Ok(()); } @@ -199,7 +238,7 @@ fn read_tree( for z in 0..stride { for x in 0..stride { let child = [origin[0] + x * child_size, origin[1] + z * child_size]; - read_tree(reader, mask.as_deref_mut(), is_road, child, child_size)?; + read_tree(reader, mask.as_deref_mut(), child, child_size)?; } } return Ok(()); @@ -224,11 +263,7 @@ fn read_tree( let bit = (z * MIP_SIZE + x) * bits; let value = (usize::from(data[bit / 8]) >> (bit % 8)) & ((1 << bits) - 1); let material = if palette.is_empty() { value as u8 } else { palette[value] }; - mask.fill( - [origin[0] + x * texel, origin[1] + z * texel], - texel, - material_is_road(is_road, material), - ); + mask.fill([origin[0] + x * texel, origin[1] + z * texel], texel, material); } } } @@ -299,10 +334,6 @@ fn indexed_points(indices: &[u8], points: &[[f32; 2]]) -> Result<[[f32; 2]; 3]> Ok(triangle) } -fn material_is_road(is_road: &[bool], material: u8) -> u8 { - u8::from(is_road.get(usize::from(material)).copied().unwrap_or(false)) -} - fn edge(a: [f32; 2], b: [f32; 2], p: [f32; 2]) -> f32 { (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]) } diff --git a/tools/navgen/mission-bounds.mts b/tools/navgen/mission-bounds.mts index d17f57d..a3b6e91 100644 --- a/tools/navgen/mission-bounds.mts +++ b/tools/navgen/mission-bounds.mts @@ -35,6 +35,7 @@ interface LevelPois { readonly team2Spawns: readonly PoiPoint[]; readonly captureZones: readonly PoiPoint[]; readonly coverBake: ReturnType; + readonly navBake: ReturnType; readonly mapBake?: NonNullable>; } @@ -149,9 +150,23 @@ function dedupePois(pts: PoiPoint[], minDistM: number): PoiPoint[] { return out; } +const groundAiTuningPath = join(import.meta.dirname, '../../apps/server/tuning/ground-ai.jsonc'); + +function readGroundAiTuning() { + return new TuningReader(groundAiTuningPath, parseJsonc(readFileSync(groundAiTuningPath, 'utf8'))); +} + +function readNavBake() { + const nav = readGroundAiTuning().object('navBake'); + return { + crushableMaxImpulse: nav.number('crushableMaxImpulse', { min: 0 }), + crushableMaxRiExtraHp: nav.number('crushableMaxRiExtraHp', { min: 0 }), + chokepointMaxWidthVehicles: nav.number('chokepointMaxWidthVehicles', { min: 1, max: 4 }), + }; +} + function readCoverBake() { - const path = join(import.meta.dirname, '../../apps/server/tuning/ground-ai.jsonc'); - const cover = new TuningReader(path, parseJsonc(readFileSync(path, 'utf8'))).object('coverMap'); + const cover = readGroundAiTuning().object('coverMap'); const peekMinM = cover.number('peekMinM', { min: 0.5 }); return { minCoverHeightM: cover.number('minCoverHeightM', { min: 0.5 }), @@ -190,6 +205,7 @@ function readMapBake(level: string) { function main() { const { gameDir, outDir, levelsFilter } = parseArgs(process.argv.slice(2)); const coverBake = readCoverBake(); + const navBake = readNavBake(); mkdirSync(outDir, { recursive: true }); const charPack = openPack(join(gameDir, 'char.vromfs.bin')); @@ -313,6 +329,7 @@ function main() { team2Spawns: t2, captureZones: caps, coverBake, + navBake, ...(mapBake && { mapBake }), }; const outPath = join(outDir, `${levelKey}.pois.json`); diff --git a/tools/navgen/render-preview.py b/tools/navgen/render-preview.py index 819b5b6..2d36450 100644 --- a/tools/navgen/render-preview.py +++ b/tools/navgen/render-preview.py @@ -8,6 +8,8 @@ import os import struct import zlib +PRINT_DPI = 300 + def write_png(path: str, width: int, height: int, rgb: bytearray) -> None: def chunk(tag: bytes, data: bytes) -> bytes: @@ -21,7 +23,15 @@ def write_png(path: str, width: int, height: int, rgb: bytearray) -> None: row = y * stride raw.extend(rgb[row : row + stride]) ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0) - png = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(bytes(raw), 6)) + chunk(b"IEND", b"") + dots_per_metre = round(PRINT_DPI / 0.0254) + phys = struct.pack(">IIB", dots_per_metre, dots_per_metre, 1) + png = ( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", ihdr) + + chunk(b"pHYs", phys) + + chunk(b"IDAT", zlib.compress(bytes(raw), 6)) + + chunk(b"IEND", b"") + ) os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) with open(path, "wb") as f: f.write(png) @@ -259,8 +269,8 @@ def main() -> None: x, y = world_to_px(px_w, pz_w) col = (60, 165, 255) if kind == 1 else (55, 240, 100) draw_circle(cov_rgb, pw, ph, x, y, 2, col, fill=True) - # Direction tick pointing toward blocked threat - x2, y2 = world_to_px(px_w + dx * 8.0, pz_w + dz * 8.0) + # Short direction tick pointing toward the blocked threat, kept short so dense cover rows stay legible + x2, y2 = world_to_px(px_w + dx * 2.0, pz_w + dz * 2.0) draw_line(cov_rgb, pw, ph, x, y, x2, y2, col, thick=1) if c[17]: peeks.append(world_to_px(c[7], c[9])) From e0a344708da2b13964a8d4c90fbce9afd747452e Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sat, 5 Dec 2026 16:39:26 +0800 Subject: [PATCH 06/19] feat(ground-ai): load baked navigation packs in battle Statically link upstream Detour into wto_ws.dll with a navigation engine (native/wto-nav) that loads one .wtonav pack per battle, reads the level file's eVER fingerprint and answers path queries through a cost filter that multiplies chokepoint polygons. Start and goal points that do not sit on the ground are retried over the mesh's height range. The ground AI script talks to it through call_mission_action("wtoNav") with load_map, unload_map, find_path and get_stats. Requests are string parameters; replies use the DataBlock setters local_mp_awards already resolves, with coordinates as centimetre ints, so no new native site is needed. The local server writes the battle level into customBots wtoLevel, and the build writes the pack folder as nav.dir in wto_ws.cfg (build-game-copy.ts --map-nav). The first load_map of a battle decides it once: loaded, fallback to the script's own navigation, or refused when navEngine.allowFallback is off, in which case bots do not plan or drive. A fingerprint mismatch is logged and the pack is still used. The script proves the round trip with one path per team at battle start and logs query statistics. Add the navEngine, navCostsTracked and navCostsWheeled tuning sections through the server reader, generated daScript constants and the launcher's bot tuning page in both languages. Verified with root and launcher type checks, MSVC builds without warnings in project code, check-patches 14/14 on 2.61.0.58 and 2.61.0.60, native module resolution 14/14 on 2.61.0.37, .58, .60 and .64, a scratch game copy build packing 29 ground AI modules, and an offline run of the engine: all three maps load with matching fingerprints and every spawn-to-capture path on every tier succeeds. --- .../src/renderer/src/i18n/locales/en.json | 27 ++ .../src/renderer/src/i18n/locales/zh-CN.json | 27 ++ .../src/pages/tuning/bot-tuning-fields.ts | 15 + apps/launcher/src/shared/schemas/tuning.ts | 24 ++ .../src/battle/battle-mission-settings.ts | 2 + apps/server/src/tuning/ground-ai-tuning.ts | 26 ++ apps/server/tuning/ground-ai.jsonc | 36 ++ game-ai/ground/wto_ai_navmesh_common.das | 157 +++++++ game-ai/ground/wto_ai_runtime.das | 13 +- native/wto-nav/wto_nav_runtime.cpp | 399 ++++++++++++++++++ native/wto-nav/wto_nav_runtime.h | 86 ++++ native/wto-net/build.ps1 | 27 +- native/wto-net/src/hook_config.c | 17 +- native/wto-net/src/hook_config.h | 2 + native/wto-net/src/local_mp_ground_ai.c | 8 + native/wto-net/src/local_mp_internal.h | 4 + native/wto-net/src/local_mp_nav.c | 352 +++++++++++++++ packages/patcher/src/build-game-copy.ts | 3 + .../patcher/src/ground-ai/ground-ai-config.ts | 36 ++ packages/patcher/src/index.ts | 2 + packages/patcher/src/network/network-hook.ts | 11 +- patches/native/local_mp_ground_ai.jsonc | 4 +- scripts/build-game-copy.ts | 16 +- 23 files changed, 1280 insertions(+), 14 deletions(-) create mode 100644 game-ai/ground/wto_ai_navmesh_common.das create mode 100644 native/wto-nav/wto_nav_runtime.cpp create mode 100644 native/wto-nav/wto_nav_runtime.h create mode 100644 native/wto-net/src/local_mp_nav.c diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 13e0c5e..559c22e 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -515,6 +515,7 @@ "estimation": "Lead estimation & aim bias", "fireControl": "Fire control & fire gate", "navigation": "Driving & navigation", + "navEngine": "Map navigation mesh & path costs", "crowd": "Spacing & crowd dispersal", "terrain": "Terrain & ridge limits", "runtime": "Tick cadence & diagnostics" @@ -531,6 +532,7 @@ "estimation": "Sample-based velocity lead, exit watch and natural shot spread", "fireControl": "Range bands, speed gates, barrel settle and ballistic safety", "navigation": "Drive backend, corner braking, pivot turns and unstick reverse", + "navEngine": "Baked map navigation packs, their fallback, and path costs per surface for tracked and wheeled vehicles", "crowd": "Personal space and ally cluster dispersal", "terrain": "Climb/drop slope limits, water depth and ridge peek caps", "runtime": "Script update intervals and telemetry logging" @@ -677,6 +679,31 @@ "tacticalReverseDistM": "Tactical reverse max distance", "tacticalReverseMaxSec": "Tactical reverse max duration" }, + "navEngine": { + "enabled": "Use map navigation packs", + "allowFallback": "Fall back to the old pathing for the battle when a pack is missing or broken", + "snapRadiusM": "Max distance from a path's start or goal to the mesh" + }, + "navCostsTracked": { + "road": "Tracked · road cost", + "bridge": "Tracked · bridge cost", + "ground": "Tracked · open ground cost", + "rough": "Tracked · steep or rocky ground cost", + "forest": "Tracked · forest cost", + "crushable": "Tracked · crushable obstacle cost", + "shallowWater": "Tracked · shallow water cost", + "chokepoint": "Tracked · chokepoint multiplier" + }, + "navCostsWheeled": { + "road": "Wheeled · road cost", + "bridge": "Wheeled · bridge cost", + "ground": "Wheeled · open ground cost", + "rough": "Wheeled · steep or rocky ground cost", + "forest": "Wheeled · forest cost", + "crushable": "Wheeled · crushable obstacle cost", + "shallowWater": "Wheeled · shallow water cost", + "chokepoint": "Wheeled · chokepoint multiplier" + }, "crowd": { "personalSpaceM": "Personal spacing distance", "clusterRadiusM": "Ally cluster detection radius", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index 8f515b8..12b25c4 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -515,6 +515,7 @@ "estimation": "目击测速与瞄准偏差", "fireControl": "火控与开火许可", "navigation": "机动与寻路控制", + "navEngine": "地图导航网格与通行代价", "crowd": "编队间距与避让", "terrain": "地形与棱线约束", "runtime": "运行频率与诊断" @@ -531,6 +532,7 @@ "estimation": "本车目击测速、守出口时长与自然散布", "fireControl": "距离分档、车速门槛、稳定等待与弹道防误伤", "navigation": "底层驱动方式、转向刹车与脱困倒车", + "navEngine": "离线地图导航包的启用与降级,以及履带 / 轮式车在各类地表上的寻路代价", "crowd": "友军安全间距与扎堆疏散", "terrain": "爬坡 / 下坡角度、涉水深度与探头限制", "runtime": "脚本刷新间隔与调试遥测日志" @@ -677,6 +679,31 @@ "tacticalReverseDistM": "战术倒车最大距离", "tacticalReverseMaxSec": "战术倒车最长时长" }, + "navEngine": { + "enabled": "启用地图导航包", + "allowFallback": "缺少或损坏时整局退回旧寻路", + "snapRadiusM": "起终点吸附到导航网格的最大距离" + }, + "navCostsTracked": { + "road": "履带车 · 道路代价", + "bridge": "履带车 · 桥面代价", + "ground": "履带车 · 普通地面代价", + "rough": "履带车 · 陡坡碎石代价", + "forest": "履带车 · 树林代价", + "crushable": "履带车 · 可碾压障碍代价", + "shallowWater": "履带车 · 浅滩涉水代价", + "chokepoint": "履带车 · 窄口代价倍率" + }, + "navCostsWheeled": { + "road": "轮式车 · 道路代价", + "bridge": "轮式车 · 桥面代价", + "ground": "轮式车 · 普通地面代价", + "rough": "轮式车 · 陡坡碎石代价", + "forest": "轮式车 · 树林代价", + "crushable": "轮式车 · 可碾压障碍代价", + "shallowWater": "轮式车 · 浅滩涉水代价", + "chokepoint": "轮式车 · 窄口代价倍率" + }, "crowd": { "personalSpaceM": "单车安全个人空间", "clusterRadiusM": "扎堆检测半径", diff --git a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts index d818982..c9238ad 100644 --- a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts +++ b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts @@ -68,6 +68,9 @@ function int( }; } +/** Surfaces of the baked navigation mesh, in the order of tuning/ground-ai.jsonc navCosts*. */ +const NAV_COST_FIELDS = ['road', 'bridge', 'ground', 'rough', 'forest', 'crushable', 'shallowWater', 'chokepoint'] as const; + export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ { id: 'general', @@ -269,6 +272,18 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ num('navigation', 'tacticalReverseMaxSec', 2, 25, 's'), ], }, + { + id: 'navEngine', + defaultOpen: false, + customOnly: true, + fields: [ + { id: 'groundAi.navEngine.enabled', section: 'navEngine', field: 'enabled', kind: 'bool' }, + { id: 'groundAi.navEngine.allowFallback', section: 'navEngine', field: 'allowFallback', kind: 'bool' }, + num('navEngine', 'snapRadiusM', 2, 40, 'm'), + ...NAV_COST_FIELDS.map((field) => num('navCostsTracked', field, 0.1, 20)), + ...NAV_COST_FIELDS.map((field) => num('navCostsWheeled', field, 0.1, 20)), + ], + }, { id: 'crowd', defaultOpen: false, diff --git a/apps/launcher/src/shared/schemas/tuning.ts b/apps/launcher/src/shared/schemas/tuning.ts index 4ae2c15..e953f6d 100644 --- a/apps/launcher/src/shared/schemas/tuning.ts +++ b/apps/launcher/src/shared/schemas/tuning.ts @@ -100,6 +100,24 @@ const GroundAiNavigationSchema = z.object({ tacticalReverseMaxSec: z.number().min(2).max(25), }); +const GroundAiNavEngineSchema = z.object({ + enabled: z.boolean(), + allowFallback: z.boolean(), + snapRadiusM: z.number().min(2).max(40), +}); + +const navCost = z.number().min(0.1).max(20); +const GroundAiNavCostsSchema = z.object({ + road: navCost, + bridge: navCost, + ground: navCost, + rough: navCost, + forest: navCost, + crushable: navCost, + shallowWater: navCost, + chokepoint: navCost, +}); + const GroundAiPerceptionSchema = z.object({ foliageTransparency: z.number().min(0.001).max(1), nearSpotRangeM: z.number().min(20).max(250), @@ -194,6 +212,9 @@ export const GroundAiTuningSchema = z.object({ crowd: GroundAiCrowdSchema, terrain: GroundAiTerrainSchema, navigation: GroundAiNavigationSchema, + navEngine: GroundAiNavEngineSchema, + navCostsTracked: GroundAiNavCostsSchema, + navCostsWheeled: GroundAiNavCostsSchema, perception: GroundAiPerceptionSchema, stateMachine: GroundAiStateMachineSchema, tactics: GroundAiTacticsSchema, @@ -212,6 +233,9 @@ export const GroundAiTuningPatchSchema = z.object({ crowd: GroundAiCrowdSchema.partial().optional(), terrain: GroundAiTerrainSchema.partial().optional(), navigation: GroundAiNavigationSchema.partial().optional(), + navEngine: GroundAiNavEngineSchema.partial().optional(), + navCostsTracked: GroundAiNavCostsSchema.partial().optional(), + navCostsWheeled: GroundAiNavCostsSchema.partial().optional(), perception: GroundAiPerceptionSchema.partial().optional(), stateMachine: GroundAiStateMachineSchema.partial().optional(), tactics: GroundAiTacticsSchema.partial().optional(), diff --git a/apps/server/src/battle/battle-mission-settings.ts b/apps/server/src/battle/battle-mission-settings.ts index a62b74a..7813a51 100644 --- a/apps/server/src/battle/battle-mission-settings.ts +++ b/apps/server/src/battle/battle-mission-settings.ts @@ -131,6 +131,8 @@ function customBotsBlock(plan: BattleLaunchPlan): BlkBlock { setParam(bots, 'wtoTeamACountries', text(plan.countriesAllies.join(';'))); setParam(bots, 'wtoTeamBCountries', text(plan.countriesAxis.join(';'))); if (plan.mission.groundMode !== undefined) setParam(bots, 'wtoGroundMode', text(plan.mission.groundMode)); + // The battle's level file: the ground AI loads its navigation pack by this name (native local_mp_nav.c). + if (plan.level !== undefined) setParam(bots, 'wtoLevel', text(plan.level)); if (plan.maxRespawns === UNLIMITED_RESPAWNS) setParam(bots, 'wtoUnlimitedRespawns', text('1')); setParam(bots, 'numBotRespawnsInMultiSlot', integer(plan.airBotRespawns)); setParam(bots, 'numTankBotRespawnsInMultiSlot', integer(plan.tankBotRespawns)); diff --git a/apps/server/src/tuning/ground-ai-tuning.ts b/apps/server/src/tuning/ground-ai-tuning.ts index 1bb7e90..5302a95 100644 --- a/apps/server/src/tuning/ground-ai-tuning.ts +++ b/apps/server/src/tuning/ground-ai-tuning.ts @@ -8,6 +8,7 @@ import { type GroundAiConfig, type GroundAiDriveMode, type GroundAiMode, + type GroundAiNavCosts, } from '@wto/patcher'; import type { TankLineupWeights } from '../battle/battle-ranks.ts'; import { tuningFiles } from './tuning-loader.ts'; @@ -44,6 +45,9 @@ export function readGroundAiTuning(reader: TuningReader): GroundAiTuning { crowd: readCrowdSection(reader.object('crowd')), terrain: readTerrainSection(reader.object('terrain')), navigation: readNavigationSection(reader.object('navigation')), + navEngine: readNavEngineSection(reader.object('navEngine')), + navCostsTracked: readNavCosts(reader.object('navCostsTracked')), + navCostsWheeled: readNavCosts(reader.object('navCostsWheeled')), perception: readPerceptionSection(reader.object('perception')), stateMachine: readStateMachineSection(reader.object('stateMachine')), tactics: readTacticsSection(reader.object('tactics')), @@ -173,6 +177,28 @@ function readTerrainSection(terrain: TuningReader): GroundAiTuning['terrain'] { }; } +function readNavEngineSection(engine: TuningReader): GroundAiTuning['navEngine'] { + return { + enabled: engine.bool('enabled'), + allowFallback: engine.bool('allowFallback'), + snapRadiusM: engine.number('snapRadiusM', { min: 2, max: 40 }), + }; +} + +function readNavCosts(costs: TuningReader): GroundAiNavCosts { + const read = (key: keyof GroundAiNavCosts) => costs.number(key, { min: 0.1, max: 20 }); + return { + road: read('road'), + bridge: read('bridge'), + ground: read('ground'), + rough: read('rough'), + forest: read('forest'), + crushable: read('crushable'), + shallowWater: read('shallowWater'), + chokepoint: read('chokepoint'), + }; +} + function readNavigationSection(nav: TuningReader): GroundAiTuning['navigation'] { const driveModeRaw = nav.string('driveMode'); const driveMode = GROUND_AI_DRIVE_MODES.find((candidate): candidate is GroundAiDriveMode => candidate === driveModeRaw); diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index 4a719c8..c3ad4ac 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -134,6 +134,42 @@ "tacticalReverseMaxSec": 9.5 }, + // Baked navigation packs (tools/navgen), loaded once per battle by the native engine. + "navEngine": { + "enabled": true, + // When the battle's pack is missing or broken: true keeps the script's own navigation for the + // whole battle, false leaves the bots standing so the problem shows (testing). Decided once at + // battle start, never in the middle of a battle. + "allowFallback": true, + // Farthest a path's start or goal may lie from the mesh. + "snapRadiusM": 12.0 + }, + + // Path cost multipliers per surface for tracked vehicles; chokepoint multiplies the surface cost + // of passages narrower than navBake.chokepointMaxWidthVehicles. + "navCostsTracked": { + "road": 0.75, + "bridge": 0.9, + "ground": 1.0, + "rough": 1.65, + "forest": 2.1, + "crushable": 2.4, + "shallowWater": 2.6, + "chokepoint": 1.8 + }, + + // The same for wheeled vehicles. + "navCostsWheeled": { + "road": 0.55, + "bridge": 0.75, + "ground": 1.15, + "rough": 3.2, + "forest": 2.8, + "crushable": 3.5, + "shallowWater": 4.0, + "chokepoint": 2.2 + }, + // Exposure-based visual perception (offline values; foliageTransparency matches stock infantry AI). "perception": { "foliageTransparency": 0.01, diff --git a/game-ai/ground/wto_ai_navmesh_common.das b/game-ai/ground/wto_ai_navmesh_common.das new file mode 100644 index 0000000..670b10f --- /dev/null +++ b/game-ai/ground/wto_ai_navmesh_common.das @@ -0,0 +1,157 @@ +// Baked navigation pack of the battle (native/wto-nav through the "wtoNav" mission action). +// The native side answers synchronously into the request DataBlock; see local_mp_nav.c. +// The pack is loaded once at battle start; whether the battle uses it, keeps the script's own +// navigation or refuses to drive is decided by that load and never changes mid-battle. +options indenting = 2 +options no_global_heap = true +module wto_ai_navmesh_common shared + +require ecs +require math +require DagorDataBlock +require DagorSystem +require Mission +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_types_common + +let public WTO_NAVMESH_UNDECIDED = 0 +let public WTO_NAVMESH_LOADED = 1 +let public WTO_NAVMESH_FALLBACK = 2 +let public WTO_NAVMESH_FAILED = 3 +let public WTO_NAVMESH_OFF = 4 + +let public WTO_NAVMESH_TIER_STANDARD = 1 +let public WTO_NAVMESH_FILTER_TRACKED = 0 +let public WTO_NAVMESH_MAX_POINTS = 96 + +let public WTO_NAVMESH_PATH_FULL = 0 +let public WTO_NAVMESH_PATH_PARTIAL = 1 +let public WTO_NAVMESH_PATH_FAILED = 2 + +[never_inline] +def private wto_navmesh_add_costs(var blk : DataBlock&) + add(blk, "t_road", "{WTO_AI_NAVMESH_T_ROAD}") + add(blk, "t_bridge", "{WTO_AI_NAVMESH_T_BRIDGE}") + add(blk, "t_ground", "{WTO_AI_NAVMESH_T_GROUND}") + add(blk, "t_rough", "{WTO_AI_NAVMESH_T_ROUGH}") + add(blk, "t_forest", "{WTO_AI_NAVMESH_T_FOREST}") + add(blk, "t_crushable", "{WTO_AI_NAVMESH_T_CRUSHABLE}") + add(blk, "t_shallowWater", "{WTO_AI_NAVMESH_T_SHALLOW_WATER}") + add(blk, "t_chokepoint", "{WTO_AI_NAVMESH_T_CHOKEPOINT}") + add(blk, "w_road", "{WTO_AI_NAVMESH_W_ROAD}") + add(blk, "w_bridge", "{WTO_AI_NAVMESH_W_BRIDGE}") + add(blk, "w_ground", "{WTO_AI_NAVMESH_W_GROUND}") + add(blk, "w_rough", "{WTO_AI_NAVMESH_W_ROUGH}") + add(blk, "w_forest", "{WTO_AI_NAVMESH_W_FOREST}") + add(blk, "w_crushable", "{WTO_AI_NAVMESH_W_CRUSHABLE}") + add(blk, "w_shallowWater", "{WTO_AI_NAVMESH_W_SHALLOW_WATER}") + add(blk, "w_chokepoint", "{WTO_AI_NAVMESH_W_CHOKEPOINT}") + +// Asks the native engine for this battle's pack once; returns a WTO_NAVMESH_* state. +[never_inline] +def public wto_navmesh_load() : int + if !WTO_AI_NAVMESH_ENABLED + print("WTO_AI|NAVMESH|state=off\n") + return WTO_NAVMESH_OFF + var state = WTO_AI_NAVMESH_ALLOW_FALLBACK ? WTO_NAVMESH_FALLBACK : WTO_NAVMESH_FAILED + using() <| $(var blk : DataBlock) + add(blk, "op", "load_map") + add(blk, "allowFallback", WTO_AI_NAVMESH_ALLOW_FALLBACK ? "1" : "0") + wto_navmesh_add_costs(blk) + call_mission_action("wtoNav", blk) + let answer = datablock_getStr(blk, "state", "") + if answer == "loaded" + state = WTO_NAVMESH_LOADED + elif answer == "fallback" + state = WTO_NAVMESH_FALLBACK + elif answer == "failed" + state = WTO_NAVMESH_FAILED + let reason = answer == "" ? "native navigation unavailable" : datablock_getStr(blk, "reason", "") + let level = datablock_getStr(blk, "level", "") + let fp = datablock_getStr(blk, "fingerprint", "") + let tiers = datablock_getInt(blk, "tiers", 0) + let covers = datablock_getInt(blk, "covers", 0) + print("WTO_AI|NAVMESH|state={state}|answer={answer}|level={level}|fp={fp}|tiers={tiers}|covers={covers}|reason={reason}\n") + return state + +[never_inline] +def public wto_navmesh_unload() + using() <| $(var blk : DataBlock) + add(blk, "op", "unload_map") + call_mission_action("wtoNav", blk) + +// Corners of a path on the mesh of `tier`; returns WTO_NAVMESH_PATH_* and fills count/lenM. +[never_inline] +def public wto_navmesh_find_path(tier, costFilter : int; start, goal : float3; + var pts : float3[96]&; var count : int&; var lenM : float&) : int + var status = WTO_NAVMESH_PATH_FAILED + count = 0 + lenM = 0.0 + using() <| $(var blk : DataBlock) + add(blk, "op", "find_path") + add(blk, "tier", "{tier}") + add(blk, "filter", "{costFilter}") + add(blk, "max", "{WTO_NAVMESH_MAX_POINTS}") + add(blk, "snap", "{WTO_AI_NAVMESH_SNAP_M}") + add(blk, "sx", "{start.x}") + add(blk, "sy", "{start.y}") + add(blk, "sz", "{start.z}") + add(blk, "gx", "{goal.x}") + add(blk, "gy", "{goal.y}") + add(blk, "gz", "{goal.z}") + call_mission_action("wtoNav", blk) + let answer = datablock_getStr(blk, "status", "") + status = answer == "full" ? WTO_NAVMESH_PATH_FULL : answer == "partial" ? WTO_NAVMESH_PATH_PARTIAL : WTO_NAVMESH_PATH_FAILED + if status == WTO_NAVMESH_PATH_FAILED + return + count = clamp(datablock_getInt(blk, "count", 0), 0, WTO_NAVMESH_MAX_POINTS) + lenM = float(datablock_getInt(blk, "lenCm", 0)) * 0.01 + for i in range(count) + let px = datablock_getInt(blk, "p{i}x", 0) + let py = datablock_getInt(blk, "p{i}y", 0) + let pz = datablock_getInt(blk, "p{i}z", 0) + pts[i] = float3(float(px) * 0.01, float(py) * 0.01, float(pz) * 0.01) + return status + +// Logs one path per team from its spawn to the first capture zone; proves the round trip. +[never_inline] +def public wto_navmesh_self_test(world : WtoWorldSnap const&) : bool + if world.capCount <= 0 || !world.teamSpawnValid[1] || !world.teamSpawnValid[2] + return false + var pts : float3[96] + for army in range(1, 3) + var count = 0 + var lenM = 0.0 + let status = wto_navmesh_find_path(WTO_NAVMESH_TIER_STANDARD, WTO_NAVMESH_FILTER_TRACKED, + world.teamSpawnCenter[army], world.caps[0].center, pts, count, lenM) + let last = count > 0 ? pts[count - 1] : float3(0.0, 0.0, 0.0) + print("WTO_AI|NAVMESH_SELFTEST|army={army}|status={status}|corners={count}|lenM={lenM}|from={world.teamSpawnCenter[army]}|to={world.caps[0].center}|end={last}\n") + return true + +// Per world tick: decide the battle's navigation once, then prove a path per team once. +[never_inline] +def public wto_navmesh_battle_tick(world : WtoWorldSnap const&; var state : int&; var selfTested : bool&) + if state == WTO_NAVMESH_UNDECIDED + state = wto_navmesh_load() + if state == WTO_NAVMESH_LOADED && !selfTested + selfTested = wto_navmesh_self_test(world) + +// Battle end: release the pack and forget the decision. +[never_inline] +def public wto_navmesh_battle_reset(var state : int&; var selfTested : bool&) + if state != WTO_NAVMESH_UNDECIDED && state != WTO_NAVMESH_OFF + wto_navmesh_unload() + state = WTO_NAVMESH_UNDECIDED + selfTested = false + +[never_inline] +def public wto_navmesh_log_stats() + using() <| $(var blk : DataBlock) + add(blk, "op", "get_stats") + call_mission_action("wtoNav", blk) + let loaded = datablock_getInt(blk, "loaded", 0) + let queries = datablock_getInt(blk, "queries", 0) + let failures = datablock_getInt(blk, "failures", 0) + let avgUs = datablock_getInt(blk, "avgUs", 0) + let maxUs = datablock_getInt(blk, "maxUs", 0) + print("WTO_AI|NAVMESH_STATS|loaded={loaded}|queries={queries}|failures={failures}|avgUs={avgUs}|maxUs={maxUs}\n") diff --git a/game-ai/ground/wto_ai_runtime.das b/game-ai/ground/wto_ai_runtime.das index 775e92b..22f0cc4 100644 --- a/game-ai/ground/wto_ai_runtime.das +++ b/game-ai/ground/wto_ai_runtime.das @@ -32,6 +32,7 @@ require %appGame.wtoai.wto_ai_commander_common require %appGame.wtoai.wto_ai_perceive_common require %appGame.wtoai.wto_ai_tactics_common require %appGame.wtoai.wto_ai_nav_common +require %appGame.wtoai.wto_ai_navmesh_common require %appGame.wtoai.wto_ai_drive_common require %appGame.wtoai.wto_ai_fire_common require %appGame.wtoai.wto_ai_diag_common @@ -47,6 +48,8 @@ var private g_cmd_dirty : bool = true var private g_last_zone_ver : int = -1 var private g_fire_budget : int = 0 var private g_next_diag_at : float = 0.0 +var private g_navmesh_state : int = 0 +var private g_navmesh_tested : bool = false def private wto_any_layer_active() : bool return WTO_AI_ENABLED && (WTO_AI_LAYER_MACRO || WTO_AI_LAYER_TACTICS || WTO_AI_LAYER_NAVIGATION || WTO_AI_LAYER_FIRE_CONTROL) @@ -66,6 +69,7 @@ def private wto_reset_runtime() g_cmd_dirty = true g_last_zone_ver = -1 g_next_diag_at = 0.0 + wto_navmesh_battle_reset(g_navmesh_state, g_navmesh_tested) for i in range(WTO_MAX_BOTS) if g_bots[i].drive.routeBOwned wto_drive_request_control(g_bots[i].eid, 0) @@ -207,6 +211,8 @@ def wto_ai_world_tick_es(act : UpdateStageInfoAct) wto_drive_announce_script_ready() print("WTO_AI|RUNTIME_READY\n") wto_world_refresh(now, g_world) + if WTO_AI_LAYER_NAVIGATION + wto_navmesh_battle_tick(g_world, g_navmesh_state, g_navmesh_tested) wto_crowd_update_all(g_world, g_bots, g_crowd) let zoneChanged = g_world.zoneVersion != g_last_zone_ver if zoneChanged @@ -237,6 +243,8 @@ def wto_ai_world_tick_es(act : UpdateStageInfoAct) if WTO_AI_DIAG_TELEMETRY && now >= g_next_diag_at g_next_diag_at = now + WTO_AI_DIAG_INTERVAL_SEC wto_diag_log_telemetry(g_world, now, g_bots, g_crowd) + if g_navmesh_state == WTO_NAVMESH_LOADED + wto_navmesh_log_stats() [es(tag=server, no_order)] def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&; @@ -264,7 +272,8 @@ def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : if WTO_AI_LAYER_TACTICS || WTO_AI_LAYER_FIRE_CONTROL wto_perceive_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], slot) wto_tactics_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], unit.isBurn, repair_system_remaining_repair_time, slot, g_crowd) - if now >= slot.nextNavAt + // A failed pack with navEngine.allowFallback off leaves every bot standing for the battle. + if now >= slot.nextNavAt && g_navmesh_state != WTO_NAVMESH_FAILED slot.nextNavAt = now + WTO_AI_NAV_TICK_SEC wto_nav_update(g_world, now, unit.pos, unit.unitTm[0], slot) wto_fire_update(g_world, unit, now, act.dt, slot, g_fire_budget) @@ -272,7 +281,7 @@ def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : [es(tag=server, after=wto_ai_pipeline_es)] def wto_ai_phys_tick_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&; unit__missionName : string; var vehicle_net_phys : VehiclePhysActor&) - if !wto_any_layer_active() || !WTO_AI_LAYER_NAVIGATION || WTO_AI_NAV_DRIVE_MODE != "vehicle_phys" + if !wto_any_layer_active() || !WTO_AI_LAYER_NAVIGATION || WTO_AI_NAV_DRIVE_MODE != "vehicle_phys" || g_navmesh_state == WTO_NAVMESH_FAILED return var unit = unit__ref.unit if unit == null || !unit.isAlive || unit.isDelayed || unit.isHumanPlayer || vehicle_net_phys.physEdit == null diff --git a/native/wto-nav/wto_nav_runtime.cpp b/native/wto-nav/wto_nav_runtime.cpp new file mode 100644 index 0000000..43b5871 --- /dev/null +++ b/native/wto-nav/wto_nav_runtime.cpp @@ -0,0 +1,399 @@ +/* + * In-game navigation engine (wto_nav_runtime.h): loads one `.wtonav` pack written by + * tools/navgen/bake into upstream Detour meshes and answers path queries for the ground AI. + */ +#include "wto_nav_runtime.h" +#include "wto_nav_format.h" + +#include "DetourAlloc.h" +#include "DetourCommon.h" +#include "DetourNavMesh.h" +#include "DetourNavMeshQuery.h" + +#include + +#include +#include +#include + +#ifndef DT_VIRTUAL_QUERYFILTER +#error "Detour must be built with DT_VIRTUAL_QUERYFILTER for the chokepoint cost filter" +#endif + +namespace { + +constexpr int kMaxSearchNodes = 32768; +constexpr int kMaxPathPolys = 4096; +constexpr size_t kMaxPackBytes = 512u * 1024u * 1024u; +constexpr size_t kMaxEverBytes = 64u * 1024u; +constexpr int kMaxLevelBlocks = 4096; + +/* Area costs per WtoPolyArea, times a multiplier on chokepoint polygons. */ +class WtoQueryFilter : public dtQueryFilter { +public: + float chokepointMul = 1.0f; + + float getCost(const float *pa, const float *pb, + const dtPolyRef, const dtMeshTile *, const dtPoly *, + const dtPolyRef, const dtMeshTile *, const dtPoly *curPoly, + const dtPolyRef, const dtMeshTile *, const dtPoly *) const override + { + float cost = dtVdist(pa, pb) * getAreaCost(curPoly->getArea()); + if (curPoly->flags & WTO_FLAG_CHOKEPOINT) + cost *= chokepointMul; + return cost; + } +}; + +struct Pack { + float heightSpan = 0.0f; /* Vertical extent of the mesh bounds */ + dtNavMesh *meshes[WTO_NAV_TIER_COUNT] = {}; + dtNavMeshQuery *queries[WTO_NAV_TIER_COUNT] = {}; + std::vector covers; + std::vector tactical; +}; + +SRWLOCK g_lock = SRWLOCK_INIT; +Pack *g_pack; +WtoQueryFilter g_filters[WTO_NAV_RT_FILTER_COUNT]; +bool g_filters_ready; +WtoNavStats g_stats; + +void init_filters_locked() +{ + if (g_filters_ready) + return; + for (WtoQueryFilter &filter : g_filters) { + filter.setIncludeFlags(WTO_FLAG_WALK); + filter.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED); + } + g_filters_ready = true; +} + +void free_pack(Pack *pack) +{ + if (pack == nullptr) + return; + for (uint32_t t = 0; t < WTO_NAV_TIER_COUNT; t++) { + dtFreeNavMeshQuery(pack->queries[t]); + dtFreeNavMesh(pack->meshes[t]); + } + delete pack; +} + +bool read_file(const wchar_t *path, std::vector &out, WtoNavLoadInfo *info) +{ + FILE *file = nullptr; + if (_wfopen_s(&file, path, L"rb") != 0 || file == nullptr) { + info->result = GetFileAttributesW(path) == INVALID_FILE_ATTRIBUTES ? WTO_NAV_LOAD_MISSING : WTO_NAV_LOAD_UNREADABLE; + snprintf(info->detail, sizeof(info->detail), "%s", info->result == WTO_NAV_LOAD_MISSING ? "no pack file" : "cannot open pack"); + return false; + } + bool ok = _fseeki64(file, 0, SEEK_END) == 0; + long long size = ok ? _ftelli64(file) : -1; + ok = ok && size > 0 && (unsigned long long)size <= kMaxPackBytes && _fseeki64(file, 0, SEEK_SET) == 0; + if (ok) { + out.resize((size_t)size); + ok = fread(out.data(), 1, out.size(), file) == out.size(); + } + fclose(file); + if (!ok) { + info->result = WTO_NAV_LOAD_UNREADABLE; + snprintf(info->detail, sizeof(info->detail), "cannot read pack (%lld bytes)", size); + } + return ok; +} + +bool fits(const std::vector &data, uint64_t offset, uint64_t size) +{ + return offset <= data.size() && size <= data.size() - offset; +} + +bool load_tier(const std::vector &data, const WtoNavHeader &hdr, uint32_t tier, Pack *pack, uint32_t *polys, char *detail, size_t detail_size) +{ + uint64_t at = hdr.tierOffsets[tier]; + const uint64_t end = at + hdr.tierSizes[tier]; + dtNavMeshParams params; + uint32_t tile_count = 0; + + if (!fits(data, at, hdr.tierSizes[tier]) || hdr.tierSizes[tier] < sizeof(params) + sizeof(tile_count)) { + snprintf(detail, detail_size, "tier %u outside the file", tier); + return false; + } + memcpy(¶ms, data.data() + at, sizeof(params)); + at += sizeof(params); + memcpy(&tile_count, data.data() + at, sizeof(tile_count)); + at += sizeof(tile_count); + + pack->meshes[tier] = dtAllocNavMesh(); + if (pack->meshes[tier] == nullptr || dtStatusFailed(pack->meshes[tier]->init(¶ms))) { + snprintf(detail, detail_size, "tier %u mesh parameters rejected", tier); + return false; + } + for (uint32_t i = 0; i < tile_count; i++) { + uint32_t size = 0; + if (at + sizeof(size) > end) { + snprintf(detail, detail_size, "tier %u tile %u header truncated", tier, i); + return false; + } + memcpy(&size, data.data() + at, sizeof(size)); + at += sizeof(size); + if (size == 0 || at + size > end) { + snprintf(detail, detail_size, "tier %u tile %u truncated", tier, i); + return false; + } + unsigned char *tile = (unsigned char *)dtAlloc(size, DT_ALLOC_PERM); + if (tile == nullptr) { + snprintf(detail, detail_size, "out of memory for tier %u", tier); + return false; + } + memcpy(tile, data.data() + at, size); + at += size; + if (dtStatusFailed(pack->meshes[tier]->addTile(tile, (int)size, DT_TILE_FREE_DATA, 0, nullptr))) { + dtFree(tile); + snprintf(detail, detail_size, "tier %u tile %u rejected by Detour", tier, i); + return false; + } + *polys += (uint32_t)((const dtMeshHeader *)tile)->polyCount; + } + pack->queries[tier] = dtAllocNavMeshQuery(); + if (pack->queries[tier] == nullptr || dtStatusFailed(pack->queries[tier]->init(pack->meshes[tier], kMaxSearchNodes))) { + snprintf(detail, detail_size, "tier %u query init failed", tier); + return false; + } + return true; +} + +Pack *parse_pack(const std::vector &data, WtoNavLoadInfo *info) +{ + WtoNavHeader hdr; + if (data.size() < sizeof(hdr)) { + snprintf(info->detail, sizeof(info->detail), "file shorter than the header"); + return nullptr; + } + memcpy(&hdr, data.data(), sizeof(hdr)); + if (memcmp(hdr.magic, WTO_NAV_MAGIC, sizeof(hdr.magic)) != 0 || hdr.version != WTO_NAV_VERSION || + hdr.tierCount != WTO_NAV_TIER_COUNT) { + snprintf(info->detail, sizeof(info->detail), "not a version %u pack", WTO_NAV_VERSION); + return nullptr; + } + const uint64_t cover_bytes = (uint64_t)hdr.coverCount * sizeof(WtoCoverPoint); + const uint64_t tac_bytes = (uint64_t)hdr.tacCols * hdr.tacRows * sizeof(WtoTacticalCell); + if (!fits(data, hdr.coverOffset, cover_bytes) || !fits(data, hdr.tacOffset, tac_bytes)) { + snprintf(info->detail, sizeof(info->detail), "cover or tactical grid outside the file"); + return nullptr; + } + memcpy(info->packSha1, hdr.everSha1, sizeof(info->packSha1)); + + Pack *pack = new Pack(); + pack->heightSpan = hdr.bmax[1] - hdr.bmin[1]; + for (uint32_t t = 0; t < WTO_NAV_TIER_COUNT; t++) { + if (!load_tier(data, hdr, t, pack, &info->polys[t], info->detail, sizeof(info->detail))) { + free_pack(pack); + return nullptr; + } + } + pack->covers.resize(hdr.coverCount); + if (cover_bytes != 0) + memcpy(pack->covers.data(), data.data() + hdr.coverOffset, (size_t)cover_bytes); + pack->tactical.resize((size_t)hdr.tacCols * hdr.tacRows); + if (tac_bytes != 0) + memcpy(pack->tactical.data(), data.data() + hdr.tacOffset, (size_t)tac_bytes); + info->tiers = WTO_NAV_TIER_COUNT; + info->covers = hdr.coverCount; + return pack; +} + +/* + * Nearest polygon within `snap` metres; mission points (spawn and capture zone centres) carry + * heights that are not on the ground, so a miss is retried over the mesh's whole height range, + * still within `snap` horizontally. + */ +bool snap_to_mesh(const dtNavMeshQuery *query, const dtQueryFilter &filter, float snap, float height_span, + const float point[3], dtPolyRef *ref, float nearest[3]) +{ + const float near_extents[3] = { snap, snap, snap }; + if (dtStatusSucceed(query->findNearestPoly(point, near_extents, &filter, ref, nearest)) && *ref != 0) + return true; + const float column_extents[3] = { snap, height_span > snap ? height_span : snap, snap }; + return dtStatusSucceed(query->findNearestPoly(point, column_extents, &filter, ref, nearest)) && *ref != 0; +} + +double now_micros() +{ + static LARGE_INTEGER frequency; + LARGE_INTEGER counter; + if (frequency.QuadPart == 0) + QueryPerformanceFrequency(&frequency); + QueryPerformanceCounter(&counter); + return (double)counter.QuadPart * 1e6 / (double)frequency.QuadPart; +} + +WtoNavPathStatus find_path_locked(uint32_t tier, uint32_t filter_index, float snap_radius_m, + const float start[3], const float goal[3], + float *points, int max_points, int *count, float *length_m) +{ + if (g_pack == nullptr || tier >= WTO_NAV_TIER_COUNT || filter_index >= WTO_NAV_RT_FILTER_COUNT || + points == nullptr || max_points < 2 || !(snap_radius_m > 0.0f)) + return WTO_NAV_PATH_FAILED; + dtNavMeshQuery *query = g_pack->queries[tier]; + const WtoQueryFilter &filter = g_filters[filter_index]; + dtPolyRef start_ref = 0, goal_ref = 0; + float start_pt[3], goal_pt[3]; + + if (!snap_to_mesh(query, filter, snap_radius_m, g_pack->heightSpan, start, &start_ref, start_pt)) + return WTO_NAV_PATH_NO_START; + if (!snap_to_mesh(query, filter, snap_radius_m, g_pack->heightSpan, goal, &goal_ref, goal_pt)) + return WTO_NAV_PATH_NO_GOAL; + + static dtPolyRef path[kMaxPathPolys]; + int path_count = 0; + dtStatus status = query->findPath(start_ref, goal_ref, start_pt, goal_pt, &filter, path, &path_count, kMaxPathPolys); + if (dtStatusFailed(status) || path_count == 0) + return WTO_NAV_PATH_FAILED; + bool partial = dtStatusDetail(status, DT_PARTIAL_RESULT) || path[path_count - 1] != goal_ref; + if (partial && dtStatusFailed(query->closestPointOnPoly(path[path_count - 1], goal, goal_pt, nullptr))) + return WTO_NAV_PATH_FAILED; + + int corners = 0; + status = query->findStraightPath(start_pt, goal_pt, path, path_count, points, nullptr, nullptr, &corners, max_points, 0); + if (dtStatusFailed(status) || corners == 0) + return WTO_NAV_PATH_FAILED; + float length = 0.0f; + for (int i = 1; i < corners; i++) + length += dtVdist(points + (i - 1) * 3, points + i * 3); + *count = corners; + *length_m = length; + return partial ? WTO_NAV_PATH_PARTIAL : WTO_NAV_PATH_FULL; +} + +} // namespace + +extern "C" int wto_nav_read_level_fingerprint(const wchar_t *level_path, uint8_t sha1[20]) +{ + FILE *file = nullptr; + uint8_t header[12]; + int found = 0; + + if (level_path == nullptr || _wfopen_s(&file, level_path, L"rb") != 0 || file == nullptr) + return 0; + if (fread(header, 1, sizeof(header), file) != sizeof(header) || memcmp(header, "DBLD3x64", 8) != 0) { + fclose(file); + return 0; + } + /* Tagged top-level blocks: u32 length (low 30 bits, tag included), 4-byte NUL-padded tag. */ + for (int block = 0; block < kMaxLevelBlocks && !found; block++) { + uint32_t len_flags = 0; + char tag[4]; + if (fread(&len_flags, 1, 4, file) != 4 || fread(tag, 1, 4, file) != 4) + break; + const uint32_t len = len_flags & 0x3FFFFFFFu; + if (len < 4) + break; + if (memcmp(tag, "\0END", 4) == 0) + break; + if (memcmp(tag, "eVER", 4) != 0) { + if (_fseeki64(file, (long long)len - 4, SEEK_CUR) != 0) + break; + continue; + } + /* Exporter version string (u32 length, bytes padded to 4), section count, level SHA-1. */ + std::vector body(len - 4 <= kMaxEverBytes ? len - 4 : 0); + if (body.empty() || fread(body.data(), 1, body.size(), file) != body.size()) + break; + uint32_t text_len = 0; + memcpy(&text_len, body.data(), body.size() >= 4 ? 4 : 0); + const size_t at = 4 + (((size_t)text_len + 3u) & ~(size_t)3u); + if (body.size() >= 4 && at + 4 + 20 <= body.size()) { + memcpy(sha1, body.data() + at + 4, 20); + found = 1; + } + break; + } + fclose(file); + return found; +} + +extern "C" void wto_nav_load(const wchar_t *pack_path, const uint8_t *level_sha1, WtoNavLoadInfo *info) +{ + std::vector data; + Pack *pack = nullptr; + + memset(info, 0, sizeof(*info)); + if (level_sha1 != nullptr) { + info->fingerprintKnown = 1; + memcpy(info->levelSha1, level_sha1, sizeof(info->levelSha1)); + } + if (read_file(pack_path, data, info)) { + pack = parse_pack(data, info); + info->result = pack != nullptr ? WTO_NAV_LOAD_OK : WTO_NAV_LOAD_CORRUPT; + } + if (pack != nullptr && level_sha1 != nullptr) + info->fingerprintMatch = memcmp(info->packSha1, level_sha1, sizeof(info->packSha1)) == 0; + + AcquireSRWLockExclusive(&g_lock); + init_filters_locked(); + free_pack(g_pack); + g_pack = pack; + memset(&g_stats, 0, sizeof(g_stats)); + g_stats.loaded = pack != nullptr; + ReleaseSRWLockExclusive(&g_lock); +} + +extern "C" void wto_nav_unload(void) +{ + AcquireSRWLockExclusive(&g_lock); + free_pack(g_pack); + g_pack = nullptr; + g_stats.loaded = 0; + ReleaseSRWLockExclusive(&g_lock); +} + +extern "C" int wto_nav_is_loaded(void) +{ + AcquireSRWLockShared(&g_lock); + const int loaded = g_pack != nullptr; + ReleaseSRWLockShared(&g_lock); + return loaded; +} + +extern "C" void wto_nav_set_costs(uint32_t filter, const WtoNavCosts *costs) +{ + if (filter >= WTO_NAV_RT_FILTER_COUNT || costs == nullptr) + return; + AcquireSRWLockExclusive(&g_lock); + init_filters_locked(); + for (int area = 0; area < WTO_NAV_RT_AREA_COUNT; area++) + g_filters[filter].setAreaCost(area, costs->area[area]); + g_filters[filter].chokepointMul = costs->chokepointMul; + ReleaseSRWLockExclusive(&g_lock); +} + +extern "C" WtoNavPathStatus wto_nav_find_path(uint32_t tier, uint32_t filter, float snap_radius_m, + const float start[3], const float goal[3], + float *points, int max_points, int *count, float *length_m) +{ + *count = 0; + *length_m = 0.0f; + AcquireSRWLockExclusive(&g_lock); + const double began = now_micros(); + const WtoNavPathStatus status = find_path_locked(tier, filter, snap_radius_m, start, goal, points, max_points, count, length_m); + const double spent = now_micros() - began; + if (g_pack != nullptr) { + g_stats.queries++; + g_stats.totalMicros += spent; + if (spent > g_stats.maxMicros) + g_stats.maxMicros = spent; + if (status != WTO_NAV_PATH_FULL) + g_stats.failures++; + } + ReleaseSRWLockExclusive(&g_lock); + return status; +} + +extern "C" void wto_nav_get_stats(WtoNavStats *stats) +{ + AcquireSRWLockShared(&g_lock); + *stats = g_stats; + ReleaseSRWLockShared(&g_lock); +} diff --git a/native/wto-nav/wto_nav_runtime.h b/native/wto-nav/wto_nav_runtime.h new file mode 100644 index 0000000..a278edc --- /dev/null +++ b/native/wto-nav/wto_nav_runtime.h @@ -0,0 +1,86 @@ +/* + * In-game navigation engine: one baked `.wtonav` pack (tools/navgen) held for the battle in + * progress, queried through upstream Detour. The C side (wto-net local_mp_nav.c) owns the + * daScript request protocol; this interface only knows packs, levels and paths. + * + * Every function is safe to call from any thread; queries are serialized internally. + */ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define WTO_NAV_RT_AREA_COUNT 12 /* WtoPolyArea values 0..11 */ +#define WTO_NAV_RT_FILTER_COUNT 2 /* 0 tracked, 1 wheeled */ + +/* Detour traversal costs for one vehicle class, indexed by WtoPolyArea. */ +typedef struct WtoNavCosts { + float area[WTO_NAV_RT_AREA_COUNT]; + float chokepointMul; /* Multiplies the area cost on WTO_FLAG_CHOKEPOINT polygons */ +} WtoNavCosts; + +typedef enum WtoNavLoadResult { + WTO_NAV_LOAD_OK = 0, + WTO_NAV_LOAD_MISSING, /* No pack file for the level */ + WTO_NAV_LOAD_UNREADABLE, /* The file exists but cannot be read */ + WTO_NAV_LOAD_CORRUPT, /* Bad header, offsets or Detour tile data */ +} WtoNavLoadResult; + +typedef struct WtoNavLoadInfo { + WtoNavLoadResult result; + int fingerprintKnown; /* 1 when the level file's eVER SHA-1 was read */ + int fingerprintMatch; /* 1 when it equals the pack's; meaningful only when known */ + uint8_t packSha1[20]; + uint8_t levelSha1[20]; + uint32_t tiers; + uint32_t covers; + uint32_t polys[3]; + char detail[96]; /* Why loading failed, for the log */ +} WtoNavLoadInfo; + +typedef enum WtoNavPathStatus { + WTO_NAV_PATH_FULL = 0, + WTO_NAV_PATH_PARTIAL, /* Ends at the reachable polygon closest to the goal */ + WTO_NAV_PATH_NO_START, /* Start not within the snap radius of the mesh */ + WTO_NAV_PATH_NO_GOAL, + WTO_NAV_PATH_FAILED, /* No pack loaded, bad tier or Detour failure */ +} WtoNavPathStatus; + +typedef struct WtoNavStats { + int loaded; + uint32_t queries; + uint32_t failures; + double totalMicros; + double maxMicros; +} WtoNavStats; + +/* Reads the eVER SHA-1 of a Dagor level file (levels/.bin) without loading the level. */ +int wto_nav_read_level_fingerprint(const wchar_t *level_path, uint8_t sha1[20]); + +/* + * Loads `pack_path`, replacing any loaded pack. `level_sha1` is the fingerprint of the level the + * game runs (NULL when unknown); a mismatch is reported but never refuses the pack. + */ +void wto_nav_load(const wchar_t *pack_path, const uint8_t *level_sha1, WtoNavLoadInfo *info); +void wto_nav_unload(void); +int wto_nav_is_loaded(void); + +/* Replaces the traversal costs of one filter (0 tracked, 1 wheeled). */ +void wto_nav_set_costs(uint32_t filter, const WtoNavCosts *costs); + +/* + * Straight-line corners from `start` to `goal` on the mesh of `tier` (0 narrow, 1 standard, + * 2 wide). `points` receives up to `max_points` xyz triples; the first is the snapped start. + */ +WtoNavPathStatus wto_nav_find_path(uint32_t tier, uint32_t filter, float snap_radius_m, + const float start[3], const float goal[3], + float *points, int max_points, int *count, float *length_m); + +void wto_nav_get_stats(WtoNavStats *stats); + +#ifdef __cplusplus +} +#endif diff --git a/native/wto-net/build.ps1 b/native/wto-net/build.ps1 index 4e45c3a..c786288 100644 --- a/native/wto-net/build.ps1 +++ b/native/wto-net/build.ps1 @@ -5,6 +5,8 @@ Output: \wto_ws.dll (default build\native). Static C runtime (/MT), so the DLL needs nothing but the system's ws2_32.dll. MinHook comes from native\third_party\minhook (BSD-2). + The ground AI navigation engine (native\wto-nav) links upstream Detour from + native\third_party\recastnavigation (zlib), compiled separately at its own warning level. #> param([string]$Out = (Join-Path $PSScriptRoot '..\..\build\native')) $ErrorActionPreference = 'Stop' @@ -16,19 +18,34 @@ $vcvars = Join-Path $vs 'VC\Auxiliary\Build\vcvars64.bat' $src = Join-Path $PSScriptRoot 'src' $mh = Join-Path $PSScriptRoot '..\third_party\minhook' +$nav = Join-Path $PSScriptRoot '..\wto-nav' +$dt = Join-Path $PSScriptRoot '..\third_party\recastnavigation\Detour' New-Item -ItemType Directory -Force $Out | Out-Null $obj = Join-Path $Out 'obj' New-Item -ItemType Directory -Force $obj | Out-Null +$dtObj = Join-Path $obj 'detour' +New-Item -ItemType Directory -Force $dtObj | Out-Null -$sources = @( +function Quote($paths) { $paths | ForEach-Object { '"' + (Resolve-Path $_) + '"' } } + +$sources = Quote @( "$src\dll_main.c", "$src\hook_config.c", "$src\redirect_rules.c", "$src\resolver_hooks.c", "$src\connection_hooks.c", "$src\local_mp_core.c", "$src\local_mp_values.c", "$src\local_mp_players.c", "$src\local_mp_loadout.c", "$src\local_mp_actions.c", "$src\local_mp_awards.c", "$src\local_mp_kills.c", "$src\local_mp_events.c", "$src\local_mp_scores.c", "$src\local_mp_nuke.c", "$src\local_mp_support.c", - "$src\local_mp_damage_notifications.c", "$src\local_mp_air_events.c", "$src\local_mp_ground_ai.c", "$src\local_mp_zones.c", + "$src\local_mp_damage_notifications.c", "$src\local_mp_air_events.c", "$src\local_mp_ground_ai.c", "$src\local_mp_nav.c", "$src\local_mp_zones.c", + "$nav\wto_nav_runtime.cpp", "$mh\src\hook.c", "$mh\src\buffer.c", "$mh\src\trampoline.c", "$mh\src\hde\hde64.c" -) | ForEach-Object { '"' + (Resolve-Path $_) + '"' } +) +$detourSources = Quote (Get-ChildItem "$dt\Source\*.cpp").FullName +$detourObjects = (Get-ChildItem "$dt\Source\*.cpp") | ForEach-Object { '"' + (Join-Path $dtObj ($_.BaseName + '.obj')) + '"' } +# Every translation unit that sees dtQueryFilter must agree on its layout (wto_nav_runtime.cpp). +$detourFlags = "/DDT_VIRTUAL_QUERYFILTER /I`"$dt\Include`"" -$command = "`"$vcvars`" >nul && cl /nologo /LD /O2 /MT /W4 /wd4100 /D_CRT_SECURE_NO_WARNINGS /DWIN32_LEAN_AND_MEAN " + - "/I`"$mh\include`" /Fo`"$obj\\`" $($sources -join ' ') /Fe`"$Out\wto_ws.dll`" " + +$detour = "`"$vcvars`" >nul && cl /nologo /c /O2 /MT /EHsc /W3 $detourFlags /Fo`"$dtObj\\`" $($detourSources -join ' ')" +cmd /c $detour +if ($LASTEXITCODE -ne 0) { throw "cl (Detour) failed with $LASTEXITCODE" } + +$command = "`"$vcvars`" >nul && cl /nologo /LD /O2 /MT /EHsc /W4 /wd4100 /D_CRT_SECURE_NO_WARNINGS /DWIN32_LEAN_AND_MEAN $detourFlags " + + "/I`"$mh\include`" /I`"$nav`" /Fo`"$obj\\`" $($sources -join ' ') $($detourObjects -join ' ') /Fe`"$Out\wto_ws.dll`" " + "/link /DEF:`"$src\wto_ws.def`" ws2_32.lib" cmd /c $command if ($LASTEXITCODE -ne 0) { throw "cl failed with $LASTEXITCODE" } diff --git a/native/wto-net/src/hook_config.c b/native/wto-net/src/hook_config.c index a049a16..df86dd0 100644 --- a/native/wto-net/src/hook_config.c +++ b/native/wto-net/src/hook_config.c @@ -9,6 +9,7 @@ * exe.size_of_image=0x... * native.= what the LocalMP modules need from the executable: RVAs of * functions and globals, structure offsets (local_mp_values.c) + * nav.dir= optional, UTF-8: where the ground AI finds .wtonav packs * * wto_ws.log: which host names were answered locally and which connections were redirected or * refused, so a run shows every address the game tried (the audit handover 6.2 asks for). @@ -32,6 +33,7 @@ typedef struct NativeValue { } NativeValue; static wchar_t g_folder[MAX_PATH]; +static wchar_t g_nav_dir[MAX_PATH]; static CRITICAL_SECTION g_log_lock; static FILE *g_log; static int g_log_enabled = 1; @@ -87,10 +89,16 @@ static void read_native_value(const char *line) g_native_count++; } +static void read_nav_dir(const char *utf8) +{ + if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8, -1, g_nav_dir, MAX_PATH) == 0) + g_nav_dir[0] = L'\0'; +} + static void read_settings(void) { wchar_t path[MAX_PATH]; - char line[160]; + char line[1024]; FILE *file; if (_snwprintf_s(path, MAX_PATH, _TRUNCATE, L"%swto_ws.cfg", g_folder) < 0) return; @@ -108,10 +116,17 @@ static void read_settings(void) parse_value(line + 18, &g_exe_size_of_image); else if (strncmp(line, NATIVE_PREFIX, sizeof(NATIVE_PREFIX) - 1) == 0) read_native_value(line); + else if (strncmp(line, "nav.dir=", 8) == 0) + read_nav_dir(line + 8); } fclose(file); } +const wchar_t *config_nav_dir(void) +{ + return g_nav_dir; +} + int config_native_value(const char *name, int64_t *value) { size_t i; diff --git a/native/wto-net/src/hook_config.h b/native/wto-net/src/hook_config.h index 5e232f8..db45fb4 100644 --- a/native/wto-net/src/hook_config.h +++ b/native/wto-net/src/hook_config.h @@ -13,3 +13,5 @@ void describe_address(const struct sockaddr *name, int length, char *text, size_ int config_native_value(const char *name, int64_t *value); /* Whether the settings were resolved for the executable this process runs (PE time stamp and size). */ int config_native_matches_executable(void); +/* Folder of the ground AI navigation packs (wto_ws.cfg "nav.dir="); empty when not configured. */ +const wchar_t *config_nav_dir(void); diff --git a/native/wto-net/src/local_mp_ground_ai.c b/native/wto-net/src/local_mp_ground_ai.c index 9dbbcf7..37a13be 100644 --- a/native/wto-net/src/local_mp_ground_ai.c +++ b/native/wto-net/src/local_mp_ground_ai.c @@ -19,6 +19,7 @@ #define SCRIPT_READY_ACTION "wtoGroundAiScriptReady" #define DRIVE_CONTROL_ACTION "wtoGroundAiDriveControl" +#define NAV_ACTION "wtoNav" typedef void (__fastcall *MissionActionFn)(const char *name, const void *blk); typedef uint8_t *(__fastcall *AsGroundModelFn)(uint8_t *unit); @@ -139,6 +140,11 @@ static void __fastcall hook_mission_action(const char *name, const void *blk) } return; } + if (name != NULL && strcmp(name, NAV_ACTION) == 0) { + /* The script's request block doubles as the reply (local_mp_nav.c). */ + local_mp_nav_request((void *)blk); + return; + } if (name == NULL || strcmp(name, DRIVE_CONTROL_ACTION) != 0) { orig_mission_action(name, blk); return; @@ -162,6 +168,8 @@ void local_mp_ground_ai_update(float dt) if (orig_mission_action == NULL) return; hosting = local_mp_is_host(); + if (!hosting) + local_mp_nav_session_ended(); AcquireSRWLockExclusive(&control_lock); for (i = 0; i < sizeof(controls) / sizeof(controls[0]); i++) { GroundAiDriveControl *control = &controls[i]; diff --git a/native/wto-net/src/local_mp_internal.h b/native/wto-net/src/local_mp_internal.h index a0c84b6..fba5627 100644 --- a/native/wto-net/src/local_mp_internal.h +++ b/native/wto-net/src/local_mp_internal.h @@ -112,3 +112,7 @@ void local_mp_zones_reset(void); int install_local_mp_air_event_hooks(void); int install_local_mp_ground_ai_hooks(void); void local_mp_ground_ai_update(float dt); + +/* "wtoNav" requests of the ground AI script and the battle's navigation pack (local_mp_nav.c). */ +void local_mp_nav_request(void *blk); +void local_mp_nav_session_ended(void); diff --git a/native/wto-net/src/local_mp_nav.c b/native/wto-net/src/local_mp_nav.c new file mode 100644 index 0000000..3377b54 --- /dev/null +++ b/native/wto-net/src/local_mp_nav.c @@ -0,0 +1,352 @@ +/* + * "wtoNav" requests of the ground AI script (call_mission_action, local_mp_ground_ai.c) and the + * battle's navigation pack (native/wto-nav). The script fills a DataBlock with the request, this + * module answers synchronously by writing into the same block: + * + * op=load_map allowFallback="0|1", tracked/wheeled costs t_, w_ + * -> state=loaded|fallback|failed, fingerprint=match|mismatch|unknown, level, + * reason, tiers, covers + * op=unload_map -> ok + * op=find_path tier, filter (0 tracked, 1 wheeled), max, snap, sx..sz, gx..gz + * -> status=full|partial|no_start|no_goal|failed, count, lenCm, + * px/py/pz in centimetres (ints) + * op=get_stats -> loaded, queries, failures, avgUs, maxUs + * + * Request values are strings: the script only uses the DataBlock string add it already relies on. + * Replies are ints and strings written with the setters local_mp_awards resolves. + * + * The level comes from the mission settings (customBots wtoLevel, written by the local server), + * the pack folder from wto_ws.cfg (nav.dir). Whether the battle uses the pack, falls back to the + * script's own navigation or refuses to drive is decided by the first load_map of the battle and + * kept until unload_map or the end of the session; it never changes in the middle of a battle. + */ +#include "hook_config.h" +#include "local_mp_internal.h" +#include "local_mp_offsets.h" +#include "local_mp_values.h" +#include "wto_nav_runtime.h" + +#include +#include +#include + +#define NAV_MAX_POINTS 96 +#define NAV_LEVEL_MAX 64 + +typedef void (__fastcall *BlkSetStrFn)(void *blk, const char *name, const char *value); +typedef void (__fastcall *BlkSetIntFn)(void *blk, const char *name, const int32_t *value); +typedef void (__fastcall *BlkToOwnedFn)(void *blk); + +typedef enum NavDecision { + NAV_UNDECIDED = 0, + NAV_LOADED, + NAV_FALLBACK, + NAV_FAILED, +} NavDecision; + +typedef struct NavBattle { + NavDecision decision; + char level[NAV_LEVEL_MAX]; + char fingerprint[16]; + char reason[96]; + uint32_t tiers; + uint32_t covers; +} NavBattle; + +/* Costs in the order of WtoPolyArea; empty names are areas the mesh never carries. */ +static const char *const AREA_KEYS[WTO_NAV_RT_AREA_COUNT] = { + "", "road", "bridge", "ground", "rough", "forest", "crushable", "shallowWater", "", "exposed", "", "", +}; + +static NavBattle g_battle; +static SRWLOCK g_battle_lock = SRWLOCK_INIT; +static LONG g_missing_values_logged; + +static int values_ready(void) +{ + if (g_lmp.blk_set_str && g_lmp.blk_set_int && g_lmp.blk_to_owned && + g_lmp_datablock_get_str && g_local_mp_mission_settings) + return 1; + if (InterlockedExchange(&g_missing_values_logged, 1) == 0) + log_line("WTO_NAV|UNAVAILABLE|reason=DataBlock setters of local_mp_awards not resolved"); + return 0; +} + +static void set_str(void *blk, const char *name, const char *value) +{ + ((BlkSetStrFn)g_lmp.blk_set_str)(blk, name, value ? value : ""); +} + +/* Integer setters expect an owned DataBlock (as in local_mp_awards.c). */ +static void set_int(void *blk, const char *name, int32_t value) +{ + if (*(int32_t *)((uint8_t *)blk + LMP_BLK_OFF_OWNED_STATE) != -1) + ((BlkToOwnedFn)g_lmp.blk_to_owned)(blk); + ((BlkSetIntFn)g_lmp.blk_set_int)(blk, name, &value); +} + +static float get_real(const void *blk, const char *name, float def) +{ + const char *text = g_lmp_datablock_get_str(blk, name, ""); + char *end; + float value; + if (text == NULL || text[0] == '\0') + return def; + value = strtof(text, &end); + return (*end == '\0' && value == value) ? value : def; +} + +static long get_long(const void *blk, const char *name, long def) +{ + const char *text = g_lmp_datablock_get_str(blk, name, ""); + char *end; + long value; + if (text == NULL || text[0] == '\0') + return def; + value = strtol(text, &end, 10); + return *end == '\0' ? value : def; +} + +static int32_t to_cm(float metres) +{ + const float cm = metres * 100.0f; + if (cm > 2.0e9f) + return INT32_MAX; + if (cm < -2.0e9f) + return INT32_MIN; + return (int32_t)(cm >= 0.0f ? cm + 0.5f : cm - 0.5f); +} + +static void hex20(const uint8_t *sha1, char out[41]) +{ + static const char digits[] = "0123456789abcdef"; + int i; + for (i = 0; i < 20; i++) { + out[i * 2] = digits[sha1[i] >> 4]; + out[i * 2 + 1] = digits[sha1[i] & 15]; + } + out[40] = '\0'; +} + +/* "levels/avg_berlin.bin" -> "avg_berlin"; only names the bake could have produced. */ +static int battle_level(char out[NAV_LEVEL_MAX]) +{ + const char *path = g_lmp_datablock_get_str(g_local_mp_mission_settings + LMP_MIS_OFF_CUSTOM_BOTS, "wtoLevel", ""); + const char *name, *dot; + size_t len, i; + + if (path == NULL || path[0] == '\0') + return 0; + name = strrchr(path, '/'); + name = name ? name + 1 : path; + dot = strrchr(name, '.'); + len = dot ? (size_t)(dot - name) : strlen(name); + if (len == 0 || len >= NAV_LEVEL_MAX) + return 0; + for (i = 0; i < len; i++) { + const char c = name[i]; + if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_')) + return 0; + out[i] = c; + } + out[len] = '\0'; + return 1; +} + +/* \levels\.bin, the game folder being the parent of the executable's win64 folder. */ +static int level_file_path(const char *level, wchar_t *out, size_t out_count) +{ + wchar_t exe[MAX_PATH]; + wchar_t *slash; + DWORD length = GetModuleFileNameW(NULL, exe, MAX_PATH); + int i; + + if (length == 0 || length >= MAX_PATH) + return 0; + for (i = 0; i < 2; i++) { + slash = wcsrchr(exe, L'\\'); + if (slash == NULL) + return 0; + *slash = L'\0'; + } + return _snwprintf_s(out, out_count, _TRUNCATE, L"%s\\levels\\%S.bin", exe, level) > 0; +} + +static void read_costs(const void *blk, const char *prefix, WtoNavCosts *costs) +{ + char key[48]; + int area; + for (area = 0; area < WTO_NAV_RT_AREA_COUNT; area++) { + costs->area[area] = 1.0f; + if (AREA_KEYS[area][0] == '\0') + continue; + snprintf(key, sizeof(key), "%s_%s", prefix, AREA_KEYS[area]); + costs->area[area] = get_real(blk, key, 1.0f); + if (!(costs->area[area] > 0.0f)) + costs->area[area] = 1.0f; + } + snprintf(key, sizeof(key), "%s_chokepoint", prefix); + costs->chokepointMul = get_real(blk, key, 1.0f); + if (!(costs->chokepointMul > 0.0f)) + costs->chokepointMul = 1.0f; +} + +static void decide_locked(const void *blk, int allow_fallback) +{ + wchar_t pack[MAX_PATH], level_path[MAX_PATH]; + const wchar_t *dir = config_nav_dir(); + uint8_t level_sha1[20]; + int have_level_sha1 = 0; + WtoNavLoadInfo info; + double began = (double)GetTickCount64(); + WtoNavCosts costs; + + memset(&info, 0, sizeof(info)); + if (!battle_level(g_battle.level)) { + snprintf(g_battle.reason, sizeof(g_battle.reason), "battle level unknown (customBots wtoLevel)"); + } else if (dir[0] == L'\0') { + snprintf(g_battle.reason, sizeof(g_battle.reason), "no pack folder (wto_ws.cfg nav.dir)"); + } else if (_snwprintf_s(pack, MAX_PATH, _TRUNCATE, L"%s\\%S.wtonav", dir, g_battle.level) <= 0) { + snprintf(g_battle.reason, sizeof(g_battle.reason), "pack path too long"); + } else { + have_level_sha1 = level_file_path(g_battle.level, level_path, MAX_PATH) && + wto_nav_read_level_fingerprint(level_path, level_sha1); + read_costs(blk, "t", &costs); + wto_nav_set_costs(0, &costs); + read_costs(blk, "w", &costs); + wto_nav_set_costs(1, &costs); + wto_nav_load(pack, have_level_sha1 ? level_sha1 : NULL, &info); + if (info.result != WTO_NAV_LOAD_OK) + snprintf(g_battle.reason, sizeof(g_battle.reason), "%s", info.detail); + } + + if (info.result == WTO_NAV_LOAD_OK && g_battle.reason[0] == '\0') { + char expected[41], actual[41]; + g_battle.decision = NAV_LOADED; + g_battle.tiers = info.tiers; + g_battle.covers = info.covers; + snprintf(g_battle.fingerprint, sizeof(g_battle.fingerprint), "%s", + !info.fingerprintKnown ? "unknown" : info.fingerprintMatch ? "match" : "mismatch"); + hex20(info.packSha1, expected); + hex20(info.levelSha1, actual); + if (info.fingerprintKnown && !info.fingerprintMatch) + log_line("WTO_NAV|FINGERPRINT_MISMATCH|level=%s|expected=%s|actual=%s", g_battle.level, expected, actual); + log_line("WTO_NAV|LOADED|level=%s|fingerprint=%s|tiers=%u|covers=%u|polys=%u/%u/%u|ms=%.0f", + g_battle.level, g_battle.fingerprint, info.tiers, info.covers, + info.polys[0], info.polys[1], info.polys[2], (double)GetTickCount64() - began); + return; + } + snprintf(g_battle.fingerprint, sizeof(g_battle.fingerprint), "unknown"); + g_battle.decision = allow_fallback ? NAV_FALLBACK : NAV_FAILED; + if (allow_fallback) + log_line("WTO_NAV|FALLBACK_STOCK_NAV|level=%s|reason=%s", g_battle.level, g_battle.reason); + else + log_line("WTO_NAV|LOAD_FAILED_NO_FALLBACK|level=%s|reason=%s", g_battle.level, g_battle.reason); +} + +static void load_map(void *blk) +{ + static const char *const STATES[] = { "", "loaded", "fallback", "failed" }; + const int allow_fallback = get_long(blk, "allowFallback", 1) != 0; + + AcquireSRWLockExclusive(&g_battle_lock); + if (g_battle.decision == NAV_UNDECIDED) + decide_locked(blk, allow_fallback); + set_str(blk, "state", STATES[g_battle.decision]); + set_str(blk, "fingerprint", g_battle.fingerprint); + set_str(blk, "level", g_battle.level); + set_str(blk, "reason", g_battle.reason); + set_int(blk, "tiers", (int32_t)g_battle.tiers); + set_int(blk, "covers", (int32_t)g_battle.covers); + ReleaseSRWLockExclusive(&g_battle_lock); +} + +static void unload_locked(const char *why) +{ + if (g_battle.decision == NAV_UNDECIDED) + return; + if (wto_nav_is_loaded()) { + WtoNavStats stats; + wto_nav_get_stats(&stats); + log_line("WTO_NAV|UNLOADED|level=%s|why=%s|queries=%u|failures=%u|avgUs=%.0f|maxUs=%.0f", + g_battle.level, why, stats.queries, stats.failures, + stats.queries ? stats.totalMicros / stats.queries : 0.0, stats.maxMicros); + wto_nav_unload(); + } + memset(&g_battle, 0, sizeof(g_battle)); +} + +static void find_path(void *blk) +{ + static const char *const STATUS[] = { "full", "partial", "no_start", "no_goal", "failed" }; + float points[NAV_MAX_POINTS * 3]; + const float start[3] = { get_real(blk, "sx", 0.0f), get_real(blk, "sy", 0.0f), get_real(blk, "sz", 0.0f) }; + const float goal[3] = { get_real(blk, "gx", 0.0f), get_real(blk, "gy", 0.0f), get_real(blk, "gz", 0.0f) }; + const long tier = get_long(blk, "tier", -1), filter = get_long(blk, "filter", 0); + long max = get_long(blk, "max", NAV_MAX_POINTS); + int count = 0, i; + float length = 0.0f; + char key[16]; + WtoNavPathStatus status; + + if (max < 2 || max > NAV_MAX_POINTS) + max = NAV_MAX_POINTS; + status = (tier < 0 || filter < 0) ? WTO_NAV_PATH_FAILED + : wto_nav_find_path((uint32_t)tier, (uint32_t)filter, get_real(blk, "snap", 0.0f), + start, goal, points, (int)max, &count, &length); + set_str(blk, "status", STATUS[status]); + set_int(blk, "count", count); + set_int(blk, "lenCm", to_cm(length)); + for (i = 0; i < count; i++) { + snprintf(key, sizeof(key), "p%dx", i); + set_int(blk, key, to_cm(points[i * 3])); + snprintf(key, sizeof(key), "p%dy", i); + set_int(blk, key, to_cm(points[i * 3 + 1])); + snprintf(key, sizeof(key), "p%dz", i); + set_int(blk, key, to_cm(points[i * 3 + 2])); + } +} + +static void get_stats(void *blk) +{ + WtoNavStats stats; + wto_nav_get_stats(&stats); + set_int(blk, "loaded", stats.loaded); + set_int(blk, "queries", (int32_t)stats.queries); + set_int(blk, "failures", (int32_t)stats.failures); + set_int(blk, "avgUs", stats.queries ? (int32_t)(stats.totalMicros / stats.queries) : 0); + set_int(blk, "maxUs", (int32_t)stats.maxMicros); +} + +void local_mp_nav_request(void *blk) +{ + const char *op; + + if (blk == NULL || !values_ready()) + return; + op = g_lmp_datablock_get_str(blk, "op", ""); + if (op == NULL) + return; + if (strcmp(op, "find_path") == 0) { + find_path(blk); + } else if (strcmp(op, "load_map") == 0) { + load_map(blk); + } else if (strcmp(op, "unload_map") == 0) { + AcquireSRWLockExclusive(&g_battle_lock); + unload_locked("battle ended"); + ReleaseSRWLockExclusive(&g_battle_lock); + set_int(blk, "ok", 1); + } else if (strcmp(op, "get_stats") == 0) { + get_stats(blk); + } else { + log_line("WTO_NAV|BAD_REQUEST|op=%s", op); + } +} + +void local_mp_nav_session_ended(void) +{ + if (TryAcquireSRWLockExclusive(&g_battle_lock)) { + unload_locked("session ended"); + ReleaseSRWLockExclusive(&g_battle_lock); + } +} diff --git a/packages/patcher/src/build-game-copy.ts b/packages/patcher/src/build-game-copy.ts index 2666592..de01a2f 100644 --- a/packages/patcher/src/build-game-copy.ts +++ b/packages/patcher/src/build-game-copy.ts @@ -69,6 +69,8 @@ export interface GameCopyInputs { readonly extraStockPacks?: Partial>; /** Optional modular ground AI scripts and tuning compiled into `game.vromfs.bin` when active. */ readonly groundAi?: GroundAiBuildInputs; + /** Absolute folder of the `.wtonav` navigation packs the ground AI loads per battle. */ + readonly mapNavFolder?: string; } /** One file of the game copy, by its path relative to the copy folder. */ @@ -140,6 +142,7 @@ export function buildGameCopy(inputs: GameCopyInputs): GameCopyBuild { const executableFolder = dirname(GAME_FILES.executable); const hookSettings = networkHookSettings(endpoint, stockImage, native.values, { loggingEnabled: inputs.hookLogging ?? true, + ...(inputs.mapNavFolder !== undefined ? { mapNavFolder: inputs.mapNavFolder } : {}), }); const files: GameCopyFile[] = [ { path: GAME_FILES.charPack, content: core.charPack }, diff --git a/packages/patcher/src/ground-ai/ground-ai-config.ts b/packages/patcher/src/ground-ai/ground-ai-config.ts index 471fab1..72c188c 100644 --- a/packages/patcher/src/ground-ai/ground-ai-config.ts +++ b/packages/patcher/src/ground-ai/ground-ai-config.ts @@ -23,6 +23,22 @@ export interface GroundAiLoadoutConfig { readonly penetrationCompareDistM: number; } +/** Path cost multipliers per baked surface; chokepoint multiplies the surface cost. */ +export interface GroundAiNavCosts { + readonly road: number; + readonly bridge: number; + readonly ground: number; + readonly rough: number; + readonly forest: number; + readonly crushable: number; + readonly shallowWater: number; + readonly chokepoint: number; +} + +export const GROUND_AI_NAV_COST_KEYS = [ + 'road', 'bridge', 'ground', 'rough', 'forest', 'crushable', 'shallowWater', 'chokepoint', +] as const satisfies readonly (keyof GroundAiNavCosts)[]; + export interface GroundAiConfig { readonly mode: GroundAiMode; readonly loadout: GroundAiLoadoutConfig; @@ -99,6 +115,14 @@ export interface GroundAiConfig { readonly tacticalReverseDistM: number; readonly tacticalReverseMaxSec: number; }; + /** Baked navigation packs loaded by the native engine (native/wto-nav). */ + readonly navEngine: { + readonly enabled: boolean; + readonly allowFallback: boolean; + readonly snapRadiusM: number; + }; + readonly navCostsTracked: GroundAiNavCosts; + readonly navCostsWheeled: GroundAiNavCosts; readonly perception: { readonly foliageTransparency: number; readonly nearSpotRangeM: number; @@ -282,6 +306,11 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['WTO_AI_NAV_UNSTICK_REV_SEC', 'float', c.navigation.unstickReverseSec], ['WTO_AI_NAV_TAC_REV_DIST_M', 'float', c.navigation.tacticalReverseDistM], ['WTO_AI_NAV_TAC_REV_MAX_SEC', 'float', c.navigation.tacticalReverseMaxSec], + ['WTO_AI_NAVMESH_ENABLED', 'bool', c.navEngine.enabled], + ['WTO_AI_NAVMESH_ALLOW_FALLBACK', 'bool', c.navEngine.allowFallback], + ['WTO_AI_NAVMESH_SNAP_M', 'float', c.navEngine.snapRadiusM], + ...navCostEntries('T', c.navCostsTracked), + ...navCostEntries('W', c.navCostsWheeled), ['WTO_AI_PERC_FOLIAGE_TRANS', 'float', c.perception.foliageTransparency], ['WTO_AI_PERC_NEAR_SPOT_M', 'float', c.perception.nearSpotRangeM], ['WTO_AI_PERC_FIRING_SPOT_M', 'float', c.perception.firingSpotRangeM], @@ -351,6 +380,13 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ]; } +/** WTO_AI_NAVMESH__, e.g. WTO_AI_NAVMESH_T_SHALLOW_WATER. */ +function navCostEntries(prefix: 'T' | 'W', costs: GroundAiNavCosts): readonly DasEntry[] { + return GROUND_AI_NAV_COST_KEYS.map((key): DasEntry => [ + `WTO_AI_NAVMESH_${prefix}_${key.replace(/[A-Z]/g, (c) => `_${c}`).toUpperCase()}`, 'float', costs[key], + ]); +} + function formatDasLiteral(name: string, kind: 'bool' | 'int' | 'float' | 'string', value: boolean | number | string): string { if (kind === 'bool') { if (typeof value !== 'boolean') throw new Error(`ground AI config ${name} must be boolean`); diff --git a/packages/patcher/src/index.ts b/packages/patcher/src/index.ts index f44934a..f820fb3 100644 --- a/packages/patcher/src/index.ts +++ b/packages/patcher/src/index.ts @@ -70,11 +70,13 @@ export { compileGroundAiConfigDas, GROUND_AI_DRIVE_MODES, GROUND_AI_MODES, + GROUND_AI_NAV_COST_KEYS, isGroundAiActive, type GroundAiConfig, type GroundAiDriveMode, type GroundAiLoadoutConfig, type GroundAiMode, + type GroundAiNavCosts, } from './ground-ai/ground-ai-config.ts'; export { rebuildGuiPack, type AppliedGuiPatch, type GuiPackResult } from './gui-pack.ts'; export { loadGuiPatches, type GuiScriptEdit, type GuiScriptPatch, type GuiScriptVariant } from './gui-patch-definition.ts'; diff --git a/packages/patcher/src/network/network-hook.ts b/packages/patcher/src/network/network-hook.ts index 583dbbf..911ccba 100644 --- a/packages/patcher/src/network/network-hook.ts +++ b/packages/patcher/src/network/network-hook.ts @@ -3,8 +3,10 @@ * online/network-hook-library makes aces.exe load win64/wto_ws.dll, which reads its settings * from win64/wto_ws.cfg: the local server port, and the values its LocalMP modules need from the * executable (native/native-settings.ts). Both files are written next to the executable; the DLL - * is built from native/wto-net (build.ps1). + * is built from native/wto-net (build.ps1). `mapNavFolder` tells the ground AI where the + * `.wtonav` navigation packs are (native/wto-net/src/local_mp_nav.c). */ +import { isAbsolute, win32 } from 'node:path'; import type { PeImage } from '@wto/exepatch'; import { nativeSettingsLines } from '../native/native-settings.ts'; import type { LocalEndpoint } from './local-endpoint.ts'; @@ -17,12 +19,17 @@ export function networkHookSettings( endpoint: LocalEndpoint, stock: PeImage, nativeValues: ReadonlyMap, - options?: { readonly loggingEnabled?: boolean }, + options?: { readonly loggingEnabled?: boolean; readonly mapNavFolder?: string }, ): { name: string; content: Uint8Array } { + const navFolder = options?.mapNavFolder; + if (navFolder !== undefined && (/[\r\n\0]/.test(navFolder) || !isAbsolute(navFolder))) { + throw new Error(`map navigation folder must be a single-line absolute path: ${navFolder}`); + } const lines = [ `port=${endpoint.port}`, ...(options?.loggingEnabled === false ? ['log=0'] : []), ...nativeSettingsLines(stock, nativeValues), + ...(navFolder !== undefined ? [`nav.dir=${win32.normalize(navFolder).replace(/\\+$/, '')}`] : []), ]; return { name: SETTINGS, content: new TextEncoder().encode(`${lines.join('\n')}\n`) }; } diff --git a/patches/native/local_mp_ground_ai.jsonc b/patches/native/local_mp_ground_ai.jsonc index 2c6d023..e7dd07e 100644 --- a/patches/native/local_mp_ground_ai.jsonc +++ b/patches/native/local_mp_ground_ai.jsonc @@ -1,10 +1,12 @@ // Temporary movement ownership for custom ground AI on a LocalMP host. // The local server cannot restore the MoveSystem flag if a game script stops running. // Without this module, stock tank movement keeps ownership of the vehicle. +// The same mission action carries the script's "wtoNav" navigation queries, answered through the +// DataBlock setters of local_mp_awards. { "module": "local_mp_ground_ai", "features": ["K-AI opponents and teammates"], - "requires": ["local_mp_core", "local_mp_players"], + "requires": ["local_mp_core", "local_mp_players", "local_mp_awards"], "sites": { // daScript call_mission_action binding, capturing the registered native function. // 2.61.0.37: 0xa6be4d -> 0xa63750. 2.61.0.58: 0xa6eb0d -> 0xa66410. diff --git a/scripts/build-game-copy.ts b/scripts/build-game-copy.ts index cfd760a..2e87ada 100644 --- a/scripts/build-game-copy.ts +++ b/scripts/build-game-copy.ts @@ -5,6 +5,7 @@ * --data * [--patches ] * [--native ] [--decal-cache ] + * [--map-nav .wtonav packs>] * [--skip-unavailable] [--verbose] * * Writes /char.vromfs.bin, /aces.vromfs.bin, /gui.vromfs.bin, /win64/aces.exe @@ -13,14 +14,15 @@ * --data is the folder the local server will run with: the store packs it sells there (its tuning * with that folder's overrides) get bundle GUIDs in gui.blk. --decal-cache names the cache/content * folder of the player's online installation; it is copied to /cache/content, otherwise - * char.vromfs.bin gets the placeholder decal index. + * char.vromfs.bin gets the placeholder decal index. --map-nav names the folder of the baked + * ground AI navigation packs (tools/navgen); wto_ws.dll loads them from there, nothing is copied. * When a patch is unavailable nothing is written, unless --skip-unavailable is given and none of * the unavailable patches is essential (the patcher's essential-features.ts). * The patch set (exe, GUI and native definitions) and the hook library default to this * repository's patches/ and build/native. The launcher runs the same build at every launch, with the port the player chose. */ import { existsSync, readFileSync } from 'node:fs'; -import { join } from 'node:path'; +import { join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { parseArgs } from 'node:util'; import type { PatchFailure } from '@wto/exepatch'; @@ -47,7 +49,7 @@ import { loadGroundAiTuning, multiVehiclePackIds } from '@wto/server'; const REPOSITORY = fileURLToPath(new URL('..', import.meta.url)); const USAGE = 'usage: build-game-copy.ts --game --out --port --data ' + '[--patches ] [--native ] [--ground-ai ] ' - + '[--mods-dir --mod ...] [--decal-cache ] [--skip-unavailable] [--verbose]'; + + '[--mods-dir --mod ...] [--decal-cache ] [--map-nav ] [--skip-unavailable] [--verbose]'; function resolveCliMods(modsDir: string | undefined, modIds: readonly string[] | undefined): DiscoveredMod[] { if (!modsDir || !modIds || modIds.length === 0) return []; @@ -73,6 +75,7 @@ function parseCliOptions() { 'mods-dir': { type: 'string' }, mod: { type: 'string', multiple: true }, 'decal-cache': { type: 'string' }, + 'map-nav': { type: 'string' }, 'skip-unavailable': { type: 'boolean', default: false }, verbose: { type: 'boolean', default: false }, }, @@ -99,6 +102,12 @@ function main(): number { return 1; } + const mapNav = values['map-nav'] === undefined ? undefined : resolve(values['map-nav']); + if (mapNav !== undefined && !existsSync(mapNav)) { + console.error(`--map-nav: ${mapNav} not found; nothing was written`); + return 1; + } + const port = Number(values.port); const enabledMods = resolveCliMods(values['mods-dir'], values.mod); const groundAiConfig = loadGroundAiTuning(values.data, (line) => console.log(line), enabledMods); @@ -123,6 +132,7 @@ function main(): number { ...(enabledMods.length > 0 ? { mods: enabledMods } : {}), ...(extraStockPacks ? { extraStockPacks } : {}), groundAi: { scriptsFolder: values['ground-ai'], config: groundAiConfig }, + ...(mapNav !== undefined ? { mapNavFolder: mapNav } : {}), }); report(build, values.verbose); return finishCliWrite(values, build, enabledMods, optionalPacksInBuild, groundAiConfig, port); From ba947fe5b6201fc8f5d74cef1cd9bfa527662dd4 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sat, 5 Dec 2026 17:38:41 +0800 Subject: [PATCH 07/19] feat(ground-ai): follow baked navmesh paths with sliced searches Native engine (native/wto-nav): - Path searches are queued per slot and advanced with Detour's sliced search inside a per-frame time budget (navEngine.pathBudgetMsPerFrame), so a 4 km search no longer stalls a frame. The synchronous find_path op is gone. - The battle's pack is read on a background thread when the mission finishes loading (prefetch); load_map only takes the result. - New mesh queries: probe (surface, flags, room to the mesh edge), raycast, nearest walkable point, and dynamic cost circles for wrecks, jams and fresh obstacles that later searches route around. Ground AI scripts: - route picks the mesh tier by vehicle width and the cost filter by tracked or wheeled, plans on goal change, drift off the corridor, a timer or reported obstacles, and falls back to the stock road mesh only when the battle decided on the fallback. - follow steers at a speed-scaled lookahead point and brakes ahead of sharp corners, narrow passages and the destination. - avoid casts rays from both front hull corners that drive through objects the bake marks crushable, follows slower traffic, steps aside or yields by size priority in narrow passages. - unstick escalates deterministically: back up along the corridor, mark a jam and replan, then log the spot and hand the order back. - Flank lanes are built through the queued searches; rallies are not released while their lanes are still being built. - Removed the 9-arc forward probing, 7-arc reverse probing, 145 m straight shortcuts, 165 m snapping and random sideways detours. Tuning: new pathFollow section, navEngine.goalSnapRadiusM and pathBudgetMsPerFrame, navBake.crushableMaxRiExtraHp passed to the scripts; retired navigation.cornerBrakeAccel, stuckWindowSec, stuckMinMoveM and unstickReverseSec. Launcher fields and en/zh-CN labels updated. Checked: root and launcher typecheck, MSVC build with no warnings in project code, check-patches for 2.61.0.58 and 2.61.0.60, offline engine run on avg_poland (prefetch, sliced searches within budget, slot replacement, dynamic costs), isolated game copy build. daScript compilation and in-battle behaviour still need the in-game run. --- .../src/renderer/src/i18n/locales/en.json | 50 ++- .../src/renderer/src/i18n/locales/zh-CN.json | 50 ++- .../src/pages/tuning/bot-tuning-fields.ts | 49 ++- apps/launcher/src/shared/schemas/tuning.ts | 47 ++- apps/server/src/tuning/ground-ai-tuning.ts | 59 ++- apps/server/tuning/ground-ai.jsonc | 62 ++- game-ai/ground/wto_ai_avoid_common.das | 176 +++++++++ game-ai/ground/wto_ai_commander_common.das | 4 +- game-ai/ground/wto_ai_diag_common.das | 17 +- game-ai/ground/wto_ai_drive_common.das | 7 +- game-ai/ground/wto_ai_follow_common.das | 88 +++++ game-ai/ground/wto_ai_lanes_build_common.das | 236 +++++++++++ game-ai/ground/wto_ai_lanes_common.das | 145 +------ game-ai/ground/wto_ai_nav_common.das | 366 +++++++----------- game-ai/ground/wto_ai_nav_types_common.das | 65 ++++ game-ai/ground/wto_ai_navmesh_common.das | 136 ++++--- game-ai/ground/wto_ai_navquery_common.das | 173 +++++++++ game-ai/ground/wto_ai_polyline_common.das | 97 +++++ game-ai/ground/wto_ai_route_common.das | 297 +++++++------- game-ai/ground/wto_ai_runtime.das | 83 ++-- game-ai/ground/wto_ai_stockpath_common.das | 53 +++ .../ground/wto_ai_tactics_actions_common.das | 1 + game-ai/ground/wto_ai_tactics_common.das | 1 + game-ai/ground/wto_ai_types_common.das | 38 +- game-ai/ground/wto_ai_unstick_common.das | 115 ++++++ native/wto-nav/wto_nav_internal.h | 81 ++++ native/wto-nav/wto_nav_paths.cpp | 246 ++++++++++++ native/wto-nav/wto_nav_queries.cpp | 164 ++++++++ native/wto-nav/wto_nav_runtime.cpp | 311 ++++++++------- native/wto-nav/wto_nav_runtime.h | 106 ++++- native/wto-net/build.ps1 | 2 +- native/wto-net/src/local_mp_nav.c | 289 ++++++++++---- .../patcher/src/ground-ai/ground-ai-config.ts | 106 ++++- packages/patcher/src/index.ts | 1 + 34 files changed, 2810 insertions(+), 911 deletions(-) create mode 100644 game-ai/ground/wto_ai_avoid_common.das create mode 100644 game-ai/ground/wto_ai_follow_common.das create mode 100644 game-ai/ground/wto_ai_lanes_build_common.das create mode 100644 game-ai/ground/wto_ai_nav_types_common.das create mode 100644 game-ai/ground/wto_ai_navquery_common.das create mode 100644 game-ai/ground/wto_ai_polyline_common.das create mode 100644 game-ai/ground/wto_ai_stockpath_common.das create mode 100644 game-ai/ground/wto_ai_unstick_common.das create mode 100644 native/wto-nav/wto_nav_internal.h create mode 100644 native/wto-nav/wto_nav_paths.cpp create mode 100644 native/wto-nav/wto_nav_queries.cpp diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 559c22e..7642034 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -516,6 +516,7 @@ "fireControl": "Fire control & fire gate", "navigation": "Driving & navigation", "navEngine": "Map navigation mesh & path costs", + "pathFollow": "Path following & unstick", "crowd": "Spacing & crowd dispersal", "terrain": "Terrain & ridge limits", "runtime": "Tick cadence & diagnostics" @@ -531,8 +532,9 @@ "tactics": "Vision range, audio detection, radio sharing and target memory", "estimation": "Sample-based velocity lead, exit watch and natural shot spread", "fireControl": "Range bands, speed gates, barrel settle and ballistic safety", - "navigation": "Drive backend, corner braking, pivot turns and unstick reverse", + "navigation": "Drive backend, pivot turns and tactical reverse", "navEngine": "Baked map navigation packs, their fallback, and path costs per surface for tracked and wheeled vehicles", + "pathFollow": "Replanning, lookahead steering, corner and arrival braking, narrow passages, bumper rays, traffic yielding, three-level unstick and temporary path costs", "crowd": "Personal space and ally cluster dispersal", "terrain": "Climb/drop slope limits, water depth and ridge peek caps", "runtime": "Script update intervals and telemetry logging" @@ -670,19 +672,17 @@ "steerSign": "Steering input polarity", "deadEchoSec": "Dead-echo detection timeout", "controlTimeoutSec": "Native control release timeout", - "cornerBrakeAccel": "Corner braking deceleration", "movingFireSpeedRampMps": "Speed error for full throttle or braking while firing on the move", "pivotAngleDeg": "Neutral pivot turn angle threshold", - "stuckWindowSec": "Stuck detection window", - "stuckMinMoveM": "Stuck min movement distance", - "unstickReverseSec": "Unstick reverse duration", "tacticalReverseDistM": "Tactical reverse max distance", "tacticalReverseMaxSec": "Tactical reverse max duration" }, "navEngine": { "enabled": "Use map navigation packs", "allowFallback": "Fall back to the old pathing for the battle when a pack is missing or broken", - "snapRadiusM": "Max distance from a path's start or goal to the mesh" + "snapRadiusM": "Max distance from a path's start or goal to the mesh", + "goalSnapRadiusM": "Max distance a path goal may be moved onto the mesh", + "pathBudgetMsPerFrame": "Path search time per frame" }, "navCostsTracked": { "road": "Tracked · road cost", @@ -704,6 +704,44 @@ "shallowWater": "Wheeled · shallow water cost", "chokepoint": "Wheeled · chokepoint multiplier" }, + "pathFollow": { + "replanIntervalSec": "Regular path replanning interval", + "replanGoalMoveM": "Goal movement that triggers a new path", + "offCorridorReplanM": "Distance off the path that triggers a new path", + "lookaheadTimeSec": "Lookahead time at current speed", + "trackedLookaheadMinM": "Tracked · min lookahead distance", + "trackedLookaheadMaxM": "Tracked · max lookahead distance", + "wheeledLookaheadMinM": "Wheeled · min lookahead distance", + "wheeledLookaheadMaxM": "Wheeled · max lookahead distance", + "cornerAngleDeg": "Path corner angle that needs slowing down", + "cornerLateralAccelMps2": "Allowed sideways acceleration in corners", + "cornerBrakeDecelMps2": "Braking deceleration before corners and the destination", + "arriveRadiusM": "Arrival radius at the destination", + "arriveMinSpeedMps": "Min speed while approaching the destination", + "narrowWallMarginM": "Room to the mesh edge below which a passage counts as narrow", + "narrowSpeedMps": "Speed cap in narrow passages", + "bumperRayM": "Front corner ray length", + "bumperStopM": "Stop distance before an obstacle hit by the front rays", + "bumperBlockSec": "Time blocked before an obstacle is reported", + "trafficTtcSec": "Vehicle collision look-ahead time", + "avoidShiftM": "Sideways step around vehicles and wrecks", + "yieldWaitMaxSec": "Max wait while giving way in narrow passages", + "stuckWindowSec": "Stuck detection window", + "stuckMinProgressM": "Min progress within the stuck window", + "unstickReverseM": "Unstick reverse distance", + "unstickReverseSec": "Unstick reverse max duration", + "unstickRepeatSec": "Time within which a repeated stuck escalates", + "unstickMaxAttempts": "Unstick attempts before giving up the order", + "jamRadiusM": "Jam cost radius", + "jamCostMul": "Jam path cost multiplier", + "jamTtlSec": "Jam cost duration", + "rubbleRadiusM": "Fresh obstacle cost radius", + "rubbleCostMul": "Fresh obstacle path cost multiplier", + "rubbleTtlSec": "Fresh obstacle cost duration", + "wreckRadiusM": "Wreck cost radius", + "wreckCostMul": "Wreck path cost multiplier", + "wreckTtlSec": "Wreck cost duration" + }, "crowd": { "personalSpaceM": "Personal spacing distance", "clusterRadiusM": "Ally cluster detection radius", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index 12b25c4..94ee57a 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -516,6 +516,7 @@ "fireControl": "火控与开火许可", "navigation": "机动与寻路控制", "navEngine": "地图导航网格与通行代价", + "pathFollow": "跟路驾驶与脱困", "crowd": "编队间距与避让", "terrain": "地形与棱线约束", "runtime": "运行频率与诊断" @@ -531,8 +532,9 @@ "tactics": "视距、听觉发现范围、电台共享与记忆时长", "estimation": "本车目击测速、守出口时长与自然散布", "fireControl": "距离分档、车速门槛、稳定等待与弹道防误伤", - "navigation": "底层驱动方式、转向刹车与脱困倒车", + "navigation": "驱动方式、原地转向与战术倒车", "navEngine": "离线地图导航包的启用与降级,以及履带 / 轮式车在各类地表上的寻路代价", + "pathFollow": "重新寻路、前瞻跟路、弯道与到达前减速、窄路限速、车头射线、会车让路、三级脱困与临时寻路代价", "crowd": "友军安全间距与扎堆疏散", "terrain": "爬坡 / 下坡角度、涉水深度与探头限制", "runtime": "脚本刷新间隔与调试遥测日志" @@ -670,19 +672,17 @@ "steerSign": "转向输入方向", "deadEchoSec": "无响应回声判定时长", "controlTimeoutSec": "原生控制超时归还时长", - "cornerBrakeAccel": "弯道减速制动强度", "movingFireSpeedRampMps": "行进射击时全油门或全制动对应的速度差", "pivotAngleDeg": "原地中性转向角度阈值", - "stuckWindowSec": "卡死检测窗口时长", - "stuckMinMoveM": "卡死判定最小位移", - "unstickReverseSec": "脱困倒车持续时长", "tacticalReverseDistM": "战术倒车最大距离", "tacticalReverseMaxSec": "战术倒车最长时长" }, "navEngine": { "enabled": "启用地图导航包", "allowFallback": "缺少或损坏时整局退回旧寻路", - "snapRadiusM": "起终点吸附到导航网格的最大距离" + "snapRadiusM": "起终点吸附到导航网格的最大距离", + "goalSnapRadiusM": "目标点吸附到导航网格的最远距离", + "pathBudgetMsPerFrame": "每帧寻路计算时间上限" }, "navCostsTracked": { "road": "履带车 · 道路代价", @@ -704,6 +704,44 @@ "shallowWater": "轮式车 · 浅滩涉水代价", "chokepoint": "轮式车 · 窄口代价倍率" }, + "pathFollow": { + "replanIntervalSec": "定时重新寻路间隔", + "replanGoalMoveM": "目标移动多远后重新寻路", + "offCorridorReplanM": "偏离路线多远后重新寻路", + "lookaheadTimeSec": "按当前车速前瞻的时间", + "trackedLookaheadMinM": "履带车 · 最短前瞻距离", + "trackedLookaheadMaxM": "履带车 · 最长前瞻距离", + "wheeledLookaheadMinM": "轮式车 · 最短前瞻距离", + "wheeledLookaheadMaxM": "轮式车 · 最长前瞻距离", + "cornerAngleDeg": "需要减速的路线拐角角度", + "cornerLateralAccelMps2": "过弯允许的横向加速度", + "cornerBrakeDecelMps2": "弯前和到达前的减速度", + "arriveRadiusM": "到达目标的判定半径", + "arriveMinSpeedMps": "接近目标时的最低车速", + "narrowWallMarginM": "离网格边缘小于多少算窄路", + "narrowSpeedMps": "窄路限速", + "bumperRayM": "车头两侧射线长度", + "bumperStopM": "车头射线碰到障碍时的停车距离", + "bumperBlockSec": "被挡多久后上报障碍", + "trafficTtcSec": "车辆碰撞预判时间", + "avoidShiftM": "绕开车辆和残骸的横移距离", + "yieldWaitMaxSec": "窄路让路最长等待时间", + "stuckWindowSec": "卡住检测窗口时长", + "stuckMinProgressM": "检测窗口内的最小前进距离", + "unstickReverseM": "脱困倒车距离", + "unstickReverseSec": "脱困倒车最长时长", + "unstickRepeatSec": "多久内再次卡住就升级处理", + "unstickMaxAttempts": "放弃当前任务前的脱困次数", + "jamRadiusM": "堵车点代价半径", + "jamCostMul": "堵车点寻路代价倍率", + "jamTtlSec": "堵车点代价持续时间", + "rubbleRadiusM": "新障碍代价半径", + "rubbleCostMul": "新障碍寻路代价倍率", + "rubbleTtlSec": "新障碍代价持续时间", + "wreckRadiusM": "残骸代价半径", + "wreckCostMul": "残骸寻路代价倍率", + "wreckTtlSec": "残骸代价持续时间" + }, "crowd": { "personalSpaceM": "单车安全个人空间", "clusterRadiusM": "扎堆检测半径", diff --git a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts index c9238ad..f94425d 100644 --- a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts +++ b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts @@ -262,12 +262,8 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ { id: 'groundAi.navigation.steerSign', section: 'navigation', field: 'steerSign', kind: 'steerSign' }, num('navigation', 'deadEchoSec', 0.3, 10, 's'), num('navigation', 'controlTimeoutSec', 0.3, 10, 's'), - num('navigation', 'cornerBrakeAccel', 0.5, 8), num('navigation', 'movingFireSpeedRampMps', 0.2, 5, 'm/s'), num('navigation', 'pivotAngleDeg', 25, 150, '°'), - num('navigation', 'stuckWindowSec', 1, 15, 's'), - num('navigation', 'stuckMinMoveM', 0.5, 10, 'm'), - num('navigation', 'unstickReverseSec', 0.8, 10, 's'), num('navigation', 'tacticalReverseDistM', 10, 90, 'm'), num('navigation', 'tacticalReverseMaxSec', 2, 25, 's'), ], @@ -280,10 +276,55 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ { id: 'groundAi.navEngine.enabled', section: 'navEngine', field: 'enabled', kind: 'bool' }, { id: 'groundAi.navEngine.allowFallback', section: 'navEngine', field: 'allowFallback', kind: 'bool' }, num('navEngine', 'snapRadiusM', 2, 40, 'm'), + num('navEngine', 'goalSnapRadiusM', 5, 150, 'm'), + num('navEngine', 'pathBudgetMsPerFrame', 0.05, 5, 'ms'), ...NAV_COST_FIELDS.map((field) => num('navCostsTracked', field, 0.1, 20)), ...NAV_COST_FIELDS.map((field) => num('navCostsWheeled', field, 0.1, 20)), ], }, + { + id: 'pathFollow', + defaultOpen: false, + customOnly: true, + fields: [ + num('pathFollow', 'replanIntervalSec', 1, 15, 's'), + num('pathFollow', 'replanGoalMoveM', 3, 80, 'm'), + num('pathFollow', 'offCorridorReplanM', 3, 60, 'm'), + num('pathFollow', 'lookaheadTimeSec', 0.3, 5, 's'), + num('pathFollow', 'trackedLookaheadMinM', 2, 40, 'm'), + num('pathFollow', 'trackedLookaheadMaxM', 4, 60, 'm'), + num('pathFollow', 'wheeledLookaheadMinM', 2, 40, 'm'), + num('pathFollow', 'wheeledLookaheadMaxM', 4, 60, 'm'), + num('pathFollow', 'cornerAngleDeg', 10, 120, '°'), + num('pathFollow', 'cornerLateralAccelMps2', 0.5, 10, 'm/s²'), + num('pathFollow', 'cornerBrakeDecelMps2', 0.5, 10, 'm/s²'), + num('pathFollow', 'arriveRadiusM', 1, 20, 'm'), + num('pathFollow', 'arriveMinSpeedMps', 0.3, 6, 'm/s'), + num('pathFollow', 'narrowWallMarginM', 0.2, 6, 'm'), + num('pathFollow', 'narrowSpeedMps', 1, 15, 'm/s'), + num('pathFollow', 'bumperRayM', 2, 20, 'm'), + num('pathFollow', 'bumperStopM', 0.3, 6, 'm'), + num('pathFollow', 'bumperBlockSec', 0.2, 5, 's'), + num('pathFollow', 'trafficTtcSec', 0.5, 8, 's'), + num('pathFollow', 'avoidShiftM', 0.5, 10, 'm'), + num('pathFollow', 'yieldWaitMaxSec', 0.5, 15, 's'), + num('pathFollow', 'stuckWindowSec', 1, 15, 's'), + num('pathFollow', 'stuckMinProgressM', 0.2, 10, 'm'), + num('pathFollow', 'unstickReverseM', 2, 25, 'm'), + num('pathFollow', 'unstickReverseSec', 0.8, 10, 's'), + num('pathFollow', 'unstickRepeatSec', 2, 60, 's'), + int('pathFollow', 'unstickMaxAttempts', 1, 10), + num('pathFollow', 'jamRadiusM', 2, 50, 'm'), + num('pathFollow', 'jamCostMul', 1, 50), + num('pathFollow', 'jamTtlSec', 5, 600, 's'), + num('pathFollow', 'rubbleRadiusM', 1, 40, 'm'), + num('pathFollow', 'rubbleCostMul', 1, 50), + num('pathFollow', 'rubbleTtlSec', 5, 600, 's'), + num('pathFollow', 'wreckRadiusM', 1, 40, 'm'), + num('pathFollow', 'wreckCostMul', 1, 50), + num('pathFollow', 'wreckTtlSec', 5, 600, 's'), + ], + }, { id: 'crowd', defaultOpen: false, diff --git a/apps/launcher/src/shared/schemas/tuning.ts b/apps/launcher/src/shared/schemas/tuning.ts index e953f6d..be651db 100644 --- a/apps/launcher/src/shared/schemas/tuning.ts +++ b/apps/launcher/src/shared/schemas/tuning.ts @@ -90,12 +90,8 @@ const GroundAiNavigationSchema = z.object({ steerSign: z.union([z.literal(1), z.literal(-1)]), deadEchoSec: z.number().min(0.3).max(10), controlTimeoutSec: z.number().min(0.3).max(10), - cornerBrakeAccel: z.number().min(0.5).max(8), movingFireSpeedRampMps: z.number().min(0.2).max(5), pivotAngleDeg: z.number().min(25).max(150), - stuckWindowSec: z.number().min(1).max(15), - stuckMinMoveM: z.number().min(0.5).max(10), - unstickReverseSec: z.number().min(0.8).max(10), tacticalReverseDistM: z.number().min(10).max(90), tacticalReverseMaxSec: z.number().min(2).max(25), }); @@ -104,6 +100,8 @@ const GroundAiNavEngineSchema = z.object({ enabled: z.boolean(), allowFallback: z.boolean(), snapRadiusM: z.number().min(2).max(40), + goalSnapRadiusM: z.number().min(5).max(150), + pathBudgetMsPerFrame: z.number().min(0.05).max(5), }); const navCost = z.number().min(0.1).max(20); @@ -118,6 +116,45 @@ const GroundAiNavCostsSchema = z.object({ chokepoint: navCost, }); +const GroundAiPathFollowSchema = z.object({ + replanIntervalSec: z.number().min(1).max(15), + replanGoalMoveM: z.number().min(3).max(80), + offCorridorReplanM: z.number().min(3).max(60), + lookaheadTimeSec: z.number().min(0.3).max(5), + trackedLookaheadMinM: z.number().min(2).max(40), + trackedLookaheadMaxM: z.number().min(4).max(60), + wheeledLookaheadMinM: z.number().min(2).max(40), + wheeledLookaheadMaxM: z.number().min(4).max(60), + cornerAngleDeg: z.number().min(10).max(120), + cornerLateralAccelMps2: z.number().min(0.5).max(10), + cornerBrakeDecelMps2: z.number().min(0.5).max(10), + arriveRadiusM: z.number().min(1).max(20), + arriveMinSpeedMps: z.number().min(0.3).max(6), + narrowWallMarginM: z.number().min(0.2).max(6), + narrowSpeedMps: z.number().min(1).max(15), + bumperRayM: z.number().min(2).max(20), + bumperStopM: z.number().min(0.3).max(6), + bumperBlockSec: z.number().min(0.2).max(5), + trafficTtcSec: z.number().min(0.5).max(8), + avoidShiftM: z.number().min(0.5).max(10), + yieldWaitMaxSec: z.number().min(0.5).max(15), + stuckWindowSec: z.number().min(1).max(15), + stuckMinProgressM: z.number().min(0.2).max(10), + unstickReverseM: z.number().min(2).max(25), + unstickReverseSec: z.number().min(0.8).max(10), + unstickRepeatSec: z.number().min(2).max(60), + unstickMaxAttempts: z.number().int().min(1).max(10), + jamRadiusM: z.number().min(2).max(50), + jamCostMul: z.number().min(1).max(50), + jamTtlSec: z.number().min(5).max(600), + rubbleRadiusM: z.number().min(1).max(40), + rubbleCostMul: z.number().min(1).max(50), + rubbleTtlSec: z.number().min(5).max(600), + wreckRadiusM: z.number().min(1).max(40), + wreckCostMul: z.number().min(1).max(50), + wreckTtlSec: z.number().min(5).max(600), +}); + const GroundAiPerceptionSchema = z.object({ foliageTransparency: z.number().min(0.001).max(1), nearSpotRangeM: z.number().min(20).max(250), @@ -215,6 +252,7 @@ export const GroundAiTuningSchema = z.object({ navEngine: GroundAiNavEngineSchema, navCostsTracked: GroundAiNavCostsSchema, navCostsWheeled: GroundAiNavCostsSchema, + pathFollow: GroundAiPathFollowSchema, perception: GroundAiPerceptionSchema, stateMachine: GroundAiStateMachineSchema, tactics: GroundAiTacticsSchema, @@ -236,6 +274,7 @@ export const GroundAiTuningPatchSchema = z.object({ navEngine: GroundAiNavEngineSchema.partial().optional(), navCostsTracked: GroundAiNavCostsSchema.partial().optional(), navCostsWheeled: GroundAiNavCostsSchema.partial().optional(), + pathFollow: GroundAiPathFollowSchema.partial().optional(), perception: GroundAiPerceptionSchema.partial().optional(), stateMachine: GroundAiStateMachineSchema.partial().optional(), tactics: GroundAiTacticsSchema.partial().optional(), diff --git a/apps/server/src/tuning/ground-ai-tuning.ts b/apps/server/src/tuning/ground-ai-tuning.ts index 5302a95..53c7014 100644 --- a/apps/server/src/tuning/ground-ai-tuning.ts +++ b/apps/server/src/tuning/ground-ai-tuning.ts @@ -9,6 +9,7 @@ import { type GroundAiDriveMode, type GroundAiMode, type GroundAiNavCosts, + type GroundAiPathFollow, } from '@wto/patcher'; import type { TankLineupWeights } from '../battle/battle-ranks.ts'; import { tuningFiles } from './tuning-loader.ts'; @@ -48,6 +49,10 @@ export function readGroundAiTuning(reader: TuningReader): GroundAiTuning { navEngine: readNavEngineSection(reader.object('navEngine')), navCostsTracked: readNavCosts(reader.object('navCostsTracked')), navCostsWheeled: readNavCosts(reader.object('navCostsWheeled')), + pathFollow: readPathFollowSection(reader.object('pathFollow')), + navBake: { + crushableMaxRiExtraHp: reader.object('navBake').number('crushableMaxRiExtraHp', { min: 0, max: 1000 }), + }, perception: readPerceptionSection(reader.object('perception')), stateMachine: readStateMachineSection(reader.object('stateMachine')), tactics: readTacticsSection(reader.object('tactics')), @@ -182,6 +187,8 @@ function readNavEngineSection(engine: TuningReader): GroundAiTuning['navEngine'] enabled: engine.bool('enabled'), allowFallback: engine.bool('allowFallback'), snapRadiusM: engine.number('snapRadiusM', { min: 2, max: 40 }), + goalSnapRadiusM: engine.number('goalSnapRadiusM', { min: 5, max: 150 }), + pathBudgetMsPerFrame: engine.number('pathBudgetMsPerFrame', { min: 0.05, max: 5 }), }; } @@ -199,6 +206,54 @@ function readNavCosts(costs: TuningReader): GroundAiNavCosts { }; } +function readPathFollowSection(pf: TuningReader): GroundAiPathFollow { + const n = (key: keyof GroundAiPathFollow, min: number, max: number) => pf.number(key, { min, max }); + const lookahead = { + trackedLookaheadMinM: n('trackedLookaheadMinM', 2, 40), + trackedLookaheadMaxM: n('trackedLookaheadMaxM', 4, 60), + wheeledLookaheadMinM: n('wheeledLookaheadMinM', 2, 40), + wheeledLookaheadMaxM: n('wheeledLookaheadMaxM', 4, 60), + }; + if (lookahead.trackedLookaheadMaxM < lookahead.trackedLookaheadMinM || lookahead.wheeledLookaheadMaxM < lookahead.wheeledLookaheadMinM) { + throw new TuningError('tuning file ground-ai.jsonc: pathFollow lookahead maximum must not be below its minimum'); + } + return { + replanIntervalSec: n('replanIntervalSec', 1, 15), + replanGoalMoveM: n('replanGoalMoveM', 3, 80), + offCorridorReplanM: n('offCorridorReplanM', 3, 60), + lookaheadTimeSec: n('lookaheadTimeSec', 0.3, 5), + ...lookahead, + cornerAngleDeg: n('cornerAngleDeg', 10, 120), + cornerLateralAccelMps2: n('cornerLateralAccelMps2', 0.5, 10), + cornerBrakeDecelMps2: n('cornerBrakeDecelMps2', 0.5, 10), + arriveRadiusM: n('arriveRadiusM', 1, 20), + arriveMinSpeedMps: n('arriveMinSpeedMps', 0.3, 6), + narrowWallMarginM: n('narrowWallMarginM', 0.2, 6), + narrowSpeedMps: n('narrowSpeedMps', 1, 15), + bumperRayM: n('bumperRayM', 2, 20), + bumperStopM: n('bumperStopM', 0.3, 6), + bumperBlockSec: n('bumperBlockSec', 0.2, 5), + trafficTtcSec: n('trafficTtcSec', 0.5, 8), + avoidShiftM: n('avoidShiftM', 0.5, 10), + yieldWaitMaxSec: n('yieldWaitMaxSec', 0.5, 15), + stuckWindowSec: n('stuckWindowSec', 1, 15), + stuckMinProgressM: n('stuckMinProgressM', 0.2, 10), + unstickReverseM: n('unstickReverseM', 2, 25), + unstickReverseSec: n('unstickReverseSec', 0.8, 10), + unstickRepeatSec: n('unstickRepeatSec', 2, 60), + unstickMaxAttempts: pf.int('unstickMaxAttempts', { min: 1, max: 10 }), + jamRadiusM: n('jamRadiusM', 2, 50), + jamCostMul: n('jamCostMul', 1, 50), + jamTtlSec: n('jamTtlSec', 5, 600), + rubbleRadiusM: n('rubbleRadiusM', 1, 40), + rubbleCostMul: n('rubbleCostMul', 1, 50), + rubbleTtlSec: n('rubbleTtlSec', 5, 600), + wreckRadiusM: n('wreckRadiusM', 1, 40), + wreckCostMul: n('wreckCostMul', 1, 50), + wreckTtlSec: n('wreckTtlSec', 5, 600), + }; +} + function readNavigationSection(nav: TuningReader): GroundAiTuning['navigation'] { const driveModeRaw = nav.string('driveMode'); const driveMode = GROUND_AI_DRIVE_MODES.find((candidate): candidate is GroundAiDriveMode => candidate === driveModeRaw); @@ -215,12 +270,8 @@ function readNavigationSection(nav: TuningReader): GroundAiTuning['navigation'] steerSign, deadEchoSec: nav.number('deadEchoSec', { min: 0.3, max: 10 }), controlTimeoutSec: nav.number('controlTimeoutSec', { min: 0.3, max: 10 }), - cornerBrakeAccel: nav.number('cornerBrakeAccel', { min: 0.5, max: 8 }), movingFireSpeedRampMps: nav.number('movingFireSpeedRampMps', { min: 0.2, max: 5 }), pivotAngleDeg: nav.number('pivotAngleDeg', { min: 25, max: 150 }), - stuckWindowSec: nav.number('stuckWindowSec', { min: 1, max: 15 }), - stuckMinMoveM: nav.number('stuckMinMoveM', { min: 0.5, max: 10 }), - unstickReverseSec: nav.number('unstickReverseSec', { min: 0.8, max: 10 }), tacticalReverseDistM: nav.number('tacticalReverseDistM', { min: 10, max: 90 }), tacticalReverseMaxSec: nav.number('tacticalReverseMaxSec', { min: 2, max: 25 }), }; diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index c3ad4ac..95d6aba 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -123,13 +123,9 @@ "steerSign": 1.0, "deadEchoSec": 1.2, "controlTimeoutSec": 1.0, - "cornerBrakeAccel": 1.75, // Speed error at which the moving-fire controller applies full throttle or braking. "movingFireSpeedRampMps": 1.0, "pivotAngleDeg": 75.0, - "stuckWindowSec": 3.6, - "stuckMinMoveM": 2.0, - "unstickReverseSec": 3.0, "tacticalReverseDistM": 34.0, "tacticalReverseMaxSec": 9.5 }, @@ -142,7 +138,13 @@ // battle start, never in the middle of a battle. "allowFallback": true, // Farthest a path's start or goal may lie from the mesh. - "snapRadiusM": 12.0 + "snapRadiusM": 12.0, + // A goal farther than snapRadiusM from the mesh (a position chosen by tactics inside a building + // or on a slope) is moved to the nearest walkable point within this distance; beyond it the + // goal counts as unreachable. Also used to find the way back onto the mesh. + "goalSnapRadiusM": 40.0, + // Path searches are spread over frames; this is the search time allowed per frame. + "pathBudgetMsPerFrame": 0.5 }, // Path cost multipliers per surface for tracked vehicles; chokepoint multiplies the surface cost @@ -170,6 +172,56 @@ "chokepoint": 2.2 }, + // Following the path, local avoidance and unstick (offline values). + "pathFollow": { + // Plan again after this long, when the goal moved this far, or when the bot is this far off its path. + "replanIntervalSec": 3.5, + "replanGoalMoveM": 15.0, + "offCorridorReplanM": 12.0, + // Steering point: speed times lookaheadTimeSec, kept within the range of the vehicle kind. + "lookaheadTimeSec": 1.4, + "trackedLookaheadMinM": 6.0, + "trackedLookaheadMaxM": 18.0, + "wheeledLookaheadMinM": 10.0, + "wheeledLookaheadMaxM": 24.0, + // Path corners sharper than cornerAngleDeg are taken at the speed the sideways acceleration + // allows; the vehicle brakes toward it (and toward its destination) at cornerBrakeDecelMps2. + "cornerAngleDeg": 35.0, + "cornerLateralAccelMps2": 2.8, + "cornerBrakeDecelMps2": 2.0, + "arriveRadiusM": 3.0, + "arriveMinSpeedMps": 1.5, + // The mesh already keeps the vehicle's half width from walls; less room than this beyond it, + // or a baked chokepoint, counts as a narrow passage. + "narrowWallMarginM": 1.5, + "narrowSpeedMps": 4.5, + // Rays from both front corners of the hull for obstacles the baked mesh does not know. + "bumperRayM": 7.0, + "bumperStopM": 1.5, + "bumperBlockSec": 0.6, + // Vehicles and wrecks that come within reach in trafficTtcSec: follow, step aside, or give way. + "trafficTtcSec": 2.5, + "avoidShiftM": 3.0, + "yieldWaitMaxSec": 3.0, + // Less progress than stuckMinProgressM within stuckWindowSec while wanting to move is stuck. + "stuckWindowSec": 3.0, + "stuckMinProgressM": 0.8, + "unstickReverseM": 6.5, + "unstickReverseSec": 3.0, + "unstickRepeatSec": 8.0, + "unstickMaxAttempts": 3, + // Temporary path costs: jams found by unstick, fresh obstacles hit by the front rays, wrecks. + "jamRadiusM": 10.0, + "jamCostMul": 4.0, + "jamTtlSec": 45.0, + "rubbleRadiusM": 6.0, + "rubbleCostMul": 8.0, + "rubbleTtlSec": 90.0, + "wreckRadiusM": 6.0, + "wreckCostMul": 6.0, + "wreckTtlSec": 120.0 + }, + // Exposure-based visual perception (offline values; foliageTransparency matches stock infantry AI). "perception": { "foliageTransparency": 0.01, diff --git a/game-ai/ground/wto_ai_avoid_common.das b/game-ai/ground/wto_ai_avoid_common.das new file mode 100644 index 0000000..c784f06 --- /dev/null +++ b/game-ai/ground/wto_ai_avoid_common.das @@ -0,0 +1,176 @@ +// Local avoidance on top of the path: what the baked mesh cannot know. Two short physical rays +// from the front corners of the hull catch fresh obstacles (rubble, collapsed buildings) and let +// the vehicle drive through what it can knock down (fences, light walls); a +// time-to-collision check against vehicles and wrecks makes a bot follow slower traffic, step +// aside, or (in narrow passages) wait while the vehicle with priority passes. +options indenting = 2 +options no_global_heap = true +module wto_ai_avoid_common shared + +require ecs +require math +require DagorMath +require Dacoll +require RendInst +require PhysMat +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_nav_types_common + +let private AVOID_STATIC_MASK = ETF_STRUCTURES | ETF_FRT + +// Placed objects a tank cannot knock down. Matches the bake: riExtra objects up to +// navBake.crushableMaxRiExtraHp are crushable, destructible generated objects (fences, posts) +// fall over, indestructible ones block. +[never_inline] +def private wto_avoid_ri_blocks(desc : RendInstDesc const&) : bool + if desc.isValid && desc.isRiExtra && desc.riExtraHandle != RIEX_HANDLE_NULL + let handle = desc.riExtraHandle + let poolId = uint(handle_to_ri_type(handle)) + if rendinst_isRIExtraGenPosInst(poolId) + return false + if riex_isImmortal(poolId) || riex_isInvincible(handle) + return true + return riex_getInitialHP(handle) > WTO_AI_NAVBAKE_CRUSH_MAX_HP + if !desc.isValid + return true + if rendinst_isRIGenPosInst(desc) + return false + return !rendinst_isRIGenDestr(desc) + +// Clear distance along dir up to the first wall-like surface a tank cannot drive through. +[never_inline] +def private wto_avoid_drive_ray(startPos, dir : float3; maxRange : float) : float + var structDist = maxRange + var sTraveled = 0.0 + for _hop in range(0, 4) + var hitD = maxRange - sTraveled + if hitD <= 0.0 + break + var mat = PHYSMAT_INVALID + var norm = float3(0.0) + var desc = RendInstDesc() + let sOrigin = startPos + dir * sTraveled + if !traceray_normalized(sOrigin, dir, hitD, mat, norm, AVOID_STATIC_MASK, desc, PHYSMAT_INVALID) + break + if norm.y < 0.72 + structDist = clamp(sTraveled + hitD, 0.0, maxRange) + break + sTraveled += max(0.0, hitD) + 0.5 + var traveled = 0.0 + for _hop in range(0, 4) + var hitDist = structDist - traveled + if hitDist <= 0.0 + break + var riMat = PHYSMAT_INVALID + var riNorm = float3(0.0) + var riDesc = RendInstDesc() + let origin = startPos + dir * traveled + if !traceray_normalized(origin, dir, hitDist, riMat, riNorm, ETF_RI | ETF_RI_PHYS, riDesc, PHYSMAT_INVALID) + break + if riNorm.y < 0.72 && wto_avoid_ri_blocks(riDesc) + return clamp(traveled + hitDist, 0.0, structDist) + traveled += max(0.0, hitDist) + 0.35 + return structDist + +// Clear distance ahead along `dir` from both front corners of the hull (the shorter of the two). +[never_inline] +def public wto_avoid_bumper(myPos, dir : float3; spec : WtoVehicleSpec const&) : float + let left = float3(-dir.z, 0.0, dir.x) + let base = myPos + dir * max(0.5, spec.halfLen - 0.4) + float3(0.0, 1.0, 0.0) + let side = max(0.4, spec.halfWid - 0.25) + let clearL = wto_avoid_drive_ray(base + left * side, dir, WTO_AI_PF_BUMPER_RAY_M) + let clearR = wto_avoid_drive_ray(base - left * side, dir, WTO_AI_PF_BUMPER_RAY_M) + return min(clearL, clearR) + +// Whether another body ahead comes within reach in the next trafficTtcSec; `tHit` is when. +[never_inline] +def private wto_avoid_conflict(myPos, myVel, dir : float3; selfRad : float; otherPos, otherVel : float3; + otherRad : float; var tHit : float&) : bool + let rel = float3(otherPos.x - myPos.x, 0.0, otherPos.z - myPos.z) + if dot(rel, dir) <= 0.0 || dot(rel, rel) > 1600.0 + return false + let relVel = float3(otherVel.x - myVel.x, 0.0, otherVel.z - myVel.z) + let vv = dot(relVel, relVel) + tHit = vv > 0.01 ? clamp(-dot(rel, relVel) / vv, 0.0, WTO_AI_PF_TRAFFIC_TTC_SEC) : 0.0 + let closest = rel + relVel * tHit + let reach = selfRad + otherRad + 0.8 + return dot(closest, closest) < reach * reach + +// Earliest conflict among vehicles and wrecks; -1 when there is none. +[never_inline] +def private wto_avoid_find(world : WtoWorldSnap const&; myPos, dir : float3; speedMps : float; + slot : WtoBotSlot const&; var isWreck : bool&) : int + let selfRad = max(slot.spec.halfWid, 1.2) + let myVel = dir * speedMps + var best = 99.0 + var found = -1 + for i in range(world.unitCount) + assume u = world.units[i] + if !u.isAlive || !u.isGround || u.eid == slot.eid + continue + var tUnit = 0.0 + if wto_avoid_conflict(myPos, myVel, dir, selfRad, u.pos, u.vel, max(u.halfWid, 1.0), tUnit) && tUnit < best + best = tUnit + found = i + isWreck = false + for w in range(world.wreckCount) + var tWreck = 0.0 + let still = float3(0.0, 0.0, 0.0) + if wto_avoid_conflict(myPos, myVel, dir, selfRad, world.wrecks[w].pos, still, max(world.wrecks[w].halfWid, 1.0), tWreck) && tWreck < best + best = tWreck + found = w + isWreck = true + return found + +// The bigger vehicle goes first; equal sizes by entity id. Players always keep their way. +[never_inline] +def private wto_avoid_has_priority(slot : WtoBotSlot const&; other : WtoUnitSnap const&) : bool + if other.isHuman + return false + let mine = slot.spec.halfLen * slot.spec.halfWid + let theirs = other.halfLen * other.halfWid + if abs(mine - theirs) > 0.5 + return mine > theirs + return uint(slot.eid) < uint(other.eid) + +// Waits for the vehicle with priority, at most yieldWaitMaxSec, then not again for as long. +[never_inline] +def private wto_avoid_yield(now : float; var nav : WtoNavState&) + if nav.yieldUntil < now && now >= nav.yieldCooldownUntil + nav.yieldUntil = now + WTO_AI_PF_YIELD_WAIT_SEC + nav.yieldCooldownUntil = nav.yieldUntil + WTO_AI_PF_YIELD_WAIT_SEC + nav.avoidSpeedCap = now < nav.yieldUntil ? 0.0 : 2.0 + +// Sets slot.nav.avoidShiftM (sideways step, left positive) and avoidSpeedCap for this tick. +[never_inline] +def public wto_avoid_traffic(world : WtoWorldSnap const&; now : float; myPos, dir : float3; + speedMps : float; narrow : bool; var slot : WtoBotSlot&) + assume nav = slot.nav + nav.avoidShiftM = 0.0 + nav.avoidSpeedCap = 99.0 + var isWreck = false + let idx = wto_avoid_find(world, myPos, dir, speedMps, slot, isWreck) + if idx < 0 + nav.yieldUntil = -100.0 + return + let otherPos = isWreck ? world.wrecks[idx].pos : world.units[idx].pos + let otherVel = isWreck ? float3(0.0, 0.0, 0.0) : world.units[idx].vel + let along = dot(otherVel, dir) + if !isWreck && along > 1.0 && along > 0.7 * length(otherVel) + let gap = sqrt(wto_xz_dist_sq(myPos, otherPos)) + nav.avoidSpeedCap = along + max(0.0, gap - 12.0) * 0.4 + return + if !isWreck && wto_avoid_has_priority(slot, world.units[idx]) + return + let lateral = dot(otherPos - myPos, float3(-dir.z, 0.0, dir.x)) + if !narrow + nav.avoidShiftM = (lateral >= 0.0 ? -1.0 : 1.0) * WTO_AI_PF_AVOID_SHIFT_M + nav.avoidSpeedCap = max(2.0, speedMps * 0.7) + return + if isWreck + slot.route.replanRequested = true + nav.avoidSpeedCap = 2.0 + return + wto_avoid_yield(now, nav) diff --git a/game-ai/ground/wto_ai_commander_common.das b/game-ai/ground/wto_ai_commander_common.das index d766afd..dc332a2 100644 --- a/game-ai/ground/wto_ai_commander_common.das +++ b/game-ai/ground/wto_ai_commander_common.das @@ -13,6 +13,7 @@ require %appGame.wtoai.wto_ai_order_common require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_world_common require %appGame.wtoai.wto_ai_lanes_common +require %appGame.wtoai.wto_ai_lanes_build_common require %appGame.wtoai.wto_ai_commander_anchors_common require %appGame.wtoai.wto_ai_commander_plans_common @@ -193,5 +194,4 @@ def public wto_commander_update_all(world : WtoWorldSnap const&; now : float; wto_lanes_update_team_intel(world, now, lanes) wto_cmd_assign_army(world, 1, now, forceRebalance, lanes, bots) wto_cmd_assign_army(world, 2, now, forceRebalance, lanes, bots) - wto_lanes_update_rallies(world, 1, now, lanes, bots) - wto_lanes_update_rallies(world, 2, now, lanes, bots) + wto_lanes_tick_rallies(world, now, lanes, bots) diff --git a/game-ai/ground/wto_ai_diag_common.das b/game-ai/ground/wto_ai_diag_common.das index d8348e5..db2205d 100644 --- a/game-ai/ground/wto_ai_diag_common.das +++ b/game-ai/ground/wto_ai_diag_common.das @@ -5,8 +5,8 @@ module wto_ai_diag_common shared require ecs require math -require pathfinder require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_nav_types_common require %appGame.wtoai.wto_ai_world_common [never_inline] @@ -16,7 +16,7 @@ def private wto_log_bot_and_cap_samples(world : WtoWorldSnap const&; bots : WtoB if !bots[i].used || sampled >= 2 continue assume b = bots[i] - print("WTO_AI|BOT_SAMPLE|eid={uint(b.eid)}|role={b.spec.role}|stab={b.spec.hasVertStab}|v0={b.fire.activeSpeedMps}|st={b.tactics.state}|allyD={b.crowd.nearestAllyDistM}|clust={b.crowd.clusterAllyCount}|ridge={b.tactics.onExposedRidge}|los={b.perceive.hasClearLos}|fc={b.fire.gunReady}/{b.fire.reloading}/{b.fire.lastAligned}|err={b.fire.lastAimErrDeg}|drift={b.fire.aimDriftDegSec}|mode={b.driveCmd.mode}|v={b.drive.lastVFwd}|clr={b.nav.frontClearM}/{b.nav.rearClearM}|wp={b.route.corridorIdx}/{b.route.corridorLen}|proj={b.route.lastStartOk}/{b.route.lastGoalOk}\n") + print("WTO_AI|BOT_SAMPLE|eid={uint(b.eid)}|role={b.spec.role}|stab={b.spec.hasVertStab}|v0={b.fire.activeSpeedMps}|st={b.tactics.state}|allyD={b.crowd.nearestAllyDistM}|clust={b.crowd.clusterAllyCount}|ridge={b.tactics.onExposedRidge}|los={b.perceive.hasClearLos}|fc={b.fire.gunReady}/{b.fire.reloading}/{b.fire.lastAligned}|err={b.fire.lastAimErrDeg}|drift={b.fire.aimDriftDegSec}|mode={b.driveCmd.mode}|v={b.drive.lastVFwd}|clr={b.nav.frontClearM}/{b.nav.rearClearM}|bump={b.nav.bumperClearM}|wall={b.nav.wallDistM}|seg={b.route.segIdx}/{b.route.corridorLen}|src={b.route.source}|path={b.route.lastStatus}|off={b.route.offTrackM}\n") sampled++ for c in range(world.capCount) assume z = world.caps[c] @@ -33,7 +33,10 @@ def public wto_diag_log_telemetry(world : WtoWorldSnap const&; now : float; var ridgeNow = 0 var revEvents = 0 var ridgeWithdraws = 0 - var detours = 0 + var stuckEv = 0 + var unreachable = 0 + var noGoal = 0 + var paths = 0 var shots = 0 var errSum = 0.0 var maxErr = 0.0 @@ -53,12 +56,14 @@ def public wto_diag_log_telemetry(world : WtoWorldSnap const&; now : float; ridgeNow += b.tactics.onExposedRidge ? 1 : 0 revEvents += b.nav.reverseCount ridgeWithdraws += b.nav.ridgeWithdrawEvents - detours += b.route.detourCount + stuckEv += b.nav.unstickEvents + unreachable += b.nav.unreachableEvents + noGoal += b.route.noGoalCount + paths += b.route.requests shots += b.fire.shotCount errSum += b.fire.shotErrSumDeg maxErr = max(maxErr, b.fire.maxShotErrDeg) let avgErr = shots > 0 ? (errSum / float(shots)) : 0.0 let jams = wto_world_active_jams(world, now) - let nm1 = pathfinder_is_loaded_ex(1) - print("WTO_AI|STAT|t={now}|bots={active}|roles={roles[0]}/{roles[1]}/{roles[2]}/{roles[3]}/{roles[4]}|crowd={crowd.crowdedBotCount}|maxClust={crowd.maxClusterSize}|minAllyD={crowd.minPairDistM}|dispNow={dispNow}|dispEv={crowd.disperseEvents}|ridgeNow={ridgeNow}|ridgeRevEv={ridgeWithdraws}|eng={engNow}|revNow={revNow}|revEv={revEvents}|jams={jams}|detours={detours}|shots={shots}|avgAimErr={avgErr}|maxAimErr={maxErr}|routeB={routeB}|caps={world.capCount}|nm1={nm1}\n") + print("WTO_AI|STAT|t={now}|bots={active}|roles={roles[0]}/{roles[1]}/{roles[2]}/{roles[3]}/{roles[4]}|crowd={crowd.crowdedBotCount}|maxClust={crowd.maxClusterSize}|minAllyD={crowd.minPairDistM}|dispNow={dispNow}|dispEv={crowd.disperseEvents}|ridgeNow={ridgeNow}|ridgeRevEv={ridgeWithdraws}|eng={engNow}|revNow={revNow}|revEv={revEvents}|jams={jams}|paths={paths}|stuckEv={stuckEv}|unreachable={unreachable}|noGoal={noGoal}|shots={shots}|avgAimErr={avgErr}|maxAimErr={maxErr}|routeB={routeB}|caps={world.capCount}\n") wto_log_bot_and_cap_samples(world, bots) diff --git a/game-ai/ground/wto_ai_drive_common.das b/game-ai/ground/wto_ai_drive_common.das index 7206bc1..f0d0b57 100644 --- a/game-ai/ground/wto_ai_drive_common.das +++ b/game-ai/ground/wto_ai_drive_common.das @@ -1,6 +1,7 @@ // Chassis drive actuator: translates `WtoDriveCmd` into closed-loop `VehiclePhysActor` axes // (throttle, steering, brakes, auto-transmission) with space-aware 3-point turns, smooth -// long-distance reverse control, and dead-echo watchdog return to stock movement. +// reverse control, and a dead-echo watchdog. Speed limits for corners and obstacles come from +// the navigation layer through the command; heading error alone slows the vehicle here. options indenting = 2 options no_global_heap = true module wto_ai_drive_common shared @@ -130,9 +131,7 @@ def private wto_compute_cruise_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleS var vLimit = min(cmd.speedMps, spec.vMaxFwd) if absErr > 0.22 let radiusEst = max(4.0, 14.0 / max(0.25, absErr)) - vLimit = min(vLimit, sqrt(WTO_AI_NAV_CORNER_BRAKE_ACCEL * radiusEst)) - if cmd.frontClearM < 12.0 - vLimit = min(vLimit, max(2.2, (cmd.frontClearM - 2.0) * 0.75)) + vLimit = min(vLimit, sqrt(WTO_AI_PF_CORNER_LAT_ACCEL * radiusEst)) let vErr = vLimit - speedMps if firingOnMove let response = vErr / WTO_AI_NAV_MOVING_FIRE_SPEED_RAMP_MPS diff --git a/game-ai/ground/wto_ai_follow_common.das b/game-ai/ground/wto_ai_follow_common.das new file mode 100644 index 0000000..1505fdd --- /dev/null +++ b/game-ai/ground/wto_ai_follow_common.das @@ -0,0 +1,88 @@ +// Pure-pursuit path following on a bot's corridor: where the bot is along it, the lookahead point +// it steers at, and how fast it may go so it slows down before sharp corners and its destination +// instead of braking at the wall. +options indenting = 2 +options no_global_heap = true +module wto_ai_follow_common shared + +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_nav_types_common +require %appGame.wtoai.wto_ai_polyline_common + +[never_inline] +def public wto_drive_cmd_set(var cmd : WtoDriveCmd&; mode : int; targetPos, desiredDir : float3; + speedMps, frontClr, rearClr : float) + cmd.valid = true + cmd.mode = mode + cmd.targetPos = targetPos + cmd.desiredDir = desiredDir + cmd.speedMps = speedMps + cmd.frontClearM = frontClr + cmd.rearClearM = rearClr + +// Moves the bot's place on its corridor forward and records its XZ distance from the corridor. +[never_inline] +def public wto_follow_track(myPos : float3; var rt : WtoRouteState&) + var seg = 0 + var t = 0.0 + rt.offTrackM = wto_poly_track(rt.corridor, rt.corridorLen, rt.segIdx, myPos, seg, t) + rt.segIdx = seg + rt.segT = t + +// Lookahead distance: grows with speed, wheeled vehicles look further (wider turns). +[never_inline] +def public wto_follow_lookahead(spec : WtoVehicleSpec const&; speedMps : float) : float + let lookMin = spec.isTracked ? WTO_AI_PF_TRACKED_LOOK_MIN_M : WTO_AI_PF_WHEELED_LOOK_MIN_M + let lookMax = spec.isTracked ? WTO_AI_PF_TRACKED_LOOK_MAX_M : WTO_AI_PF_WHEELED_LOOK_MAX_M + return clamp(abs(speedMps) * WTO_AI_PF_LOOKAHEAD_SEC, lookMin, max(lookMin, lookMax)) + +[never_inline] +def public wto_follow_target(rt : WtoRouteState const&; lookM : float) : float3 + return wto_poly_walk(rt.corridor, rt.corridorLen, rt.segIdx, rt.segT, lookM) + +// Highest speed at `distToB` metres before corner b (a -> b -> c) that still allows turning it. +[never_inline] +def private wto_follow_corner_cap(a, b, c : float3; distToB, lookM, halfLen : float) : float + let inDir = wto_xz_normalize(b - a, float3(1.0, 0.0, 0.0)) + let outDir = wto_xz_normalize(c - b, inDir) + let turnRad = acos(clamp(dot(inDir, outDir), -1.0, 1.0)) + if turnRad * WTO_RAD_TO_DEG < WTO_AI_PF_CORNER_ANGLE_DEG + return 99.0 + let legs = min(sqrt(wto_xz_dist_sq(a, b)), sqrt(wto_xz_dist_sq(b, c))) + let cut = max(1.0, min(lookM * 0.5, legs * 0.5)) + let radius = max(2.5, cut / max(0.05, tan(turnRad * 0.5))) + let vCorner = sqrt(WTO_AI_PF_CORNER_LAT_ACCEL * radius) + return sqrt(vCorner * vCorner + 2.0 * WTO_AI_PF_BRAKE_DECEL * max(0.0, distToB - halfLen)) + +// Speed allowed by the next two corners and, when the corridor ends at the destination, by it. +[never_inline] +def public wto_follow_speed_cap(rt : WtoRouteState const&; spec : WtoVehicleSpec const&; lookM : float) : float + if rt.corridorLen < 2 + return 99.0 + let s = clamp(rt.segIdx, 0, rt.corridorLen - 2) + let here = lerp(rt.corridor[s], rt.corridor[s + 1], rt.segT) + var dist = sqrt(wto_xz_dist_sq(here, rt.corridor[s + 1])) + var cap = 99.0 + for j in range(2) + let b = s + 1 + j + if b >= rt.corridorLen - 1 + break + cap = min(cap, wto_follow_corner_cap(rt.corridor[b - 1], rt.corridor[b], rt.corridor[b + 1], dist, lookM, spec.halfLen)) + dist += sqrt(wto_xz_dist_sq(rt.corridor[b], rt.corridor[b + 1])) + if rt.truncated || s < rt.corridorLen - 4 + return cap + var remaining = sqrt(wto_xz_dist_sq(here, rt.corridor[s + 1])) + for k in range(s + 1, rt.corridorLen - 1) + remaining += sqrt(wto_xz_dist_sq(rt.corridor[k], rt.corridor[k + 1])) + let arrive = sqrt(2.0 * WTO_AI_PF_BRAKE_DECEL * max(0.0, remaining - WTO_AI_PF_ARRIVE_RADIUS_M)) + return min(cap, max(WTO_AI_PF_ARRIVE_MIN_MPS, arrive)) + +// True when the corridor ends at the destination and the bot is within the arrival radius of it. +[never_inline] +def public wto_follow_arrived(rt : WtoRouteState const&; myPos : float3) : bool + if rt.corridorLen <= 0 || rt.truncated + return false + return wto_xz_dist_sq(myPos, rt.corridor[rt.corridorLen - 1]) <= wto_sq(WTO_AI_PF_ARRIVE_RADIUS_M) diff --git a/game-ai/ground/wto_ai_lanes_build_common.das b/game-ai/ground/wto_ai_lanes_build_common.das new file mode 100644 index 0000000..d96aa88 --- /dev/null +++ b/game-ai/ground/wto_ai_lanes_build_common.das @@ -0,0 +1,236 @@ +// Builds the flank lanes of every team x capture zone and releases their 40% rally points. +// With the battle's navigation pack the paths are queued native searches (one step per call until +// built); without it (fallback) they come from the stock road mesh at once. Center: spawn to the +// zone. Flanks: spawn to a walkable relay beside the center path's middle, then on to the zone; +// a flank longer than flankMaxLengthRatio times the center path is dropped. +options indenting = 2 +options no_global_heap = true +module wto_ai_lanes_build_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_order_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_terrain_common +require %appGame.wtoai.wto_ai_world_common +require %appGame.wtoai.wto_ai_polyline_common +require %appGame.wtoai.wto_ai_navquery_common +require %appGame.wtoai.wto_ai_navmesh_common +require %appGame.wtoai.wto_ai_stockpath_common +require %appGame.wtoai.wto_ai_lanes_common + +[never_inline] +def private wto_lanes_slot(k, leg : int) : int + return WTO_NAVQ_LANE_SLOT0 + k * 5 + leg + +// Center path known: length, rally at rallyProgressFrac and middle of the path. +[never_inline] +def private wto_lanes_set_center(k : int; pts : float3[96]; count : int; var lanes : WtoTeamLanes&) + lanes.centerLen[k] = wto_poly_length(pts, count) + lanes.centerMid[k] = wto_poly_sample(pts, count, 0.5) + lanes.rallyPos[k * 3 + WTO_LANE_CENTER] = wto_poly_sample(pts, count, WTO_AI_CMD_RALLY_PROG_FRAC) + +// No center path: straight-line stand-ins, no flanks. +[never_inline] +def private wto_lanes_set_straight(world : WtoWorldSnap const&; army, capIdx, k : int; var lanes : WtoTeamLanes&) + let spawnPt = world.teamSpawnCenter[army] + let capPt = world.caps[capIdx].center + lanes.centerLen[k] = max(80.0, sqrt(wto_xz_dist_sq(spawnPt, capPt))) + lanes.centerMid[k] = lerp(spawnPt, capPt, 0.5) + lanes.rallyPos[k * 3 + WTO_LANE_CENTER] = lerp(spawnPt, capPt, WTO_AI_CMD_RALLY_PROG_FRAC) + +// Relay of one side beside the center path's middle, on walkable ground; false when unusable. +[never_inline] +def private wto_lanes_relay(world : WtoWorldSnap const&; army, capIdx, k, side : int; + lanes : WtoTeamLanes const&; var relay : float3&) : bool + let spawnPt = world.teamSpawnCenter[army] + let capPt = world.caps[capIdx].center + let toCap = wto_xz_normalize(capPt - spawnPt, float3(1.0, 0.0, 0.0)) + let lat = float3(-toCap.z, 0.0, toCap.x) + let swing = clamp(sqrt(wto_xz_dist_sq(spawnPt, capPt)) * 0.34, 80.0, 260.0) + let sign = side == 0 ? 1.0 : -1.0 + relay = wto_clamp_battle_xz(lerp(spawnPt, capPt, 0.5) + lat * (sign * swing), world.battleCenter, world.battleRadius, 45.0) + if lanes.navState == WTO_NAVMESH_LOADED + var onMesh = relay + if !wto_navq_nearest(WTO_NAVMESH_TIER_STANDARD, WTO_NAVMESH_FILTER_TRACKED, relay, WTO_AI_NAVMESH_GOAL_SNAP_M, onMesh) + return false + relay = onMesh + if !wto_terrain_point_valid(army, relay) + return false + return sqrt(wto_xz_dist_sq(relay, lanes.centerMid[k])) >= WTO_AI_CMD_FLANK_MIN_SEP_M + +// A flank whose two legs are known: keep it when it is not too long. +[never_inline] +def private wto_lanes_accept_flank(k, side : int; leg1 : float3[96]; count1 : int; len2 : float; + relay : float3; var lanes : WtoTeamLanes&) + let fKey = k * 2 + side + lanes.flankValid[fKey] = false + if (wto_poly_length(leg1, count1) + len2) > lanes.centerLen[k] * WTO_AI_CMD_FLANK_MAX_RATIO + return + lanes.flankValid[fKey] = true + lanes.flankRelay[fKey] = relay + lanes.rallyPos[k * 3 + side + 1] = wto_poly_sample(leg1, count1, 0.8) + +// Fallback battles: every path from the stock road mesh at once. +[never_inline] +def private wto_lanes_build_stock(world : WtoWorldSnap const&; army, capIdx, k : int; var lanes : WtoTeamLanes&) + lanes.phase[k] = WTO_LANES_BUILT + var pts : float3[96] + var count = 0 + if !wto_stock_path(world.teamSpawnCenter[army], world.caps[capIdx].center, pts, count) + wto_lanes_set_straight(world, army, capIdx, k, lanes) + return + wto_lanes_set_center(k, pts, count, lanes) + var leg2 : float3[96] + for side in range(2) + var relay = float3(0.0, 0.0, 0.0) + lanes.flankValid[k * 2 + side] = false + if !wto_lanes_relay(world, army, capIdx, k, side, lanes, relay) + continue + var count2 = 0 + if !wto_stock_path(world.teamSpawnCenter[army], relay, pts, count) || !wto_stock_path(relay, world.caps[capIdx].center, leg2, count2) + continue + wto_lanes_accept_flank(k, side, pts, count, wto_poly_length(leg2, count2), pts[count - 1], lanes) + +// Queues both legs of each usable flank (slots k*5+1..4). +[never_inline] +def private wto_lanes_request_legs(world : WtoWorldSnap const&; army, capIdx, k : int; var lanes : WtoTeamLanes&) + for side in range(2) + var relay = float3(0.0, 0.0, 0.0) + lanes.flankValid[k * 2 + side] = false + lanes.ticket[k * 5 + 1 + side * 2] = 0 + lanes.ticket[k * 5 + 2 + side * 2] = 0 + if !wto_lanes_relay(world, army, capIdx, k, side, lanes, relay) + continue + lanes.flankRelay[k * 2 + side] = relay + lanes.ticket[k * 5 + 1 + side * 2] = wto_navq_path_request(wto_lanes_slot(k, 1 + side * 2), WTO_NAVMESH_TIER_STANDARD, + WTO_NAVMESH_FILTER_TRACKED, world.teamSpawnCenter[army], relay) + lanes.ticket[k * 5 + 2 + side * 2] = wto_navq_path_request(wto_lanes_slot(k, 2 + side * 2), WTO_NAVMESH_TIER_STANDARD, + WTO_NAVMESH_FILTER_TRACKED, relay, world.caps[capIdx].center) + lanes.phase[k] = WTO_LANES_LEGS + +// Center path queued: take it once found and queue the flank legs. +[never_inline] +def private wto_lanes_mesh_center(world : WtoWorldSnap const&; army, capIdx, k : int; var lanes : WtoTeamLanes&) + var pts : float3[96] + var count = 0 + var lenM = 0.0 + var truncated = false + let status = wto_navq_path_result(wto_lanes_slot(k, 0), lanes.ticket[k * 5], pts, count, lenM, truncated) + if status == WTO_PATH_PENDING + return + if (status != WTO_PATH_FULL && status != WTO_PATH_PARTIAL) || count < 2 + wto_lanes_set_straight(world, army, capIdx, k, lanes) + lanes.phase[k] = WTO_LANES_BUILT + return + wto_lanes_set_center(k, pts, count, lanes) + wto_lanes_request_legs(world, army, capIdx, k, lanes) + +// Flank legs queued: once none is pending, keep the flanks whose legs both arrived. +[never_inline] +def private wto_lanes_mesh_legs(k : int; var lanes : WtoTeamLanes&) + var leg1 : float3[96] + var leg2 : float3[96] + for side in range(2) + var count1 = 0 + var count2 = 0 + var len1 = 0.0 + var len2 = 0.0 + var trunc1 = false + var trunc2 = false + let t1 = lanes.ticket[k * 5 + 1 + side * 2] + let t2 = lanes.ticket[k * 5 + 2 + side * 2] + if t1 == 0 || t2 == 0 + continue + let s1 = wto_navq_path_result(wto_lanes_slot(k, 1 + side * 2), t1, leg1, count1, len1, trunc1) + let s2 = wto_navq_path_result(wto_lanes_slot(k, 2 + side * 2), t2, leg2, count2, len2, trunc2) + if s1 == WTO_PATH_PENDING || s2 == WTO_PATH_PENDING + return + lanes.ticket[k * 5 + 1 + side * 2] = 0 + lanes.ticket[k * 5 + 2 + side * 2] = 0 + if s1 == WTO_PATH_FULL && s2 == WTO_PATH_FULL && count1 >= 2 + wto_lanes_accept_flank(k, side, leg1, count1, len2, lanes.flankRelay[k * 2 + side], lanes) + lanes.phase[k] = WTO_LANES_BUILT + +// Builds (or advances the building of) the lanes of one team x capture zone. +[never_inline] +def public wto_lanes_ensure_cap(world : WtoWorldSnap const&; army, capIdx : int; var lanes : WtoTeamLanes&) + let k = wto_lanes_cap_key(army, capIdx) + if lanes.phase[k] == WTO_LANES_BUILT || capIdx < 0 || capIdx >= world.capCount || !world.teamSpawnValid[army] + return + if lanes.navState != WTO_NAVMESH_LOADED + if lanes.navState == WTO_NAVMESH_FALLBACK || lanes.navState == WTO_NAVMESH_OFF + wto_lanes_build_stock(world, army, capIdx, k, lanes) + return + if lanes.phase[k] == WTO_LANES_IDLE + lanes.ticket[k * 5] = wto_navq_path_request(wto_lanes_slot(k, 0), WTO_NAVMESH_TIER_STANDARD, WTO_NAVMESH_FILTER_TRACKED, + world.teamSpawnCenter[army], world.caps[capIdx].center) + lanes.phase[k] = WTO_LANES_CENTER + elif lanes.phase[k] == WTO_LANES_CENTER + wto_lanes_mesh_center(world, army, capIdx, k, lanes) + else + wto_lanes_mesh_legs(k, lanes) + +[never_inline] +def private wto_lanes_update_rallies(world : WtoWorldSnap const&; army : int; now : float; + var lanes : WtoTeamLanes&; bots : WtoBotSlot[64]) + let rallyRadSq = wto_sq(WTO_AI_CMD_RALLY_RADIUS_M) + for c in range(world.capCount) + wto_lanes_ensure_cap(world, army, c, lanes) + if lanes.phase[wto_lanes_cap_key(army, c)] != WTO_LANES_BUILT + continue + for lane in range(3) + let sk = wto_lanes_sub_key(army, c, lane) + if lanes.rallyReleased[sk] + continue + let rPos = lanes.rallyPos[sk] + if length_sq(rPos) < 1.0 + lanes.rallyReleased[sk] = true + continue + let rDistToCapSq = wto_xz_dist_sq(rPos, world.caps[c].center) + var assigned = 0 + var arrived = 0 + for i in range(WTO_MAX_BOTS) + assume b = bots[i] + if !b.used || b.army != army || !b.order.valid || b.order.capIndex != c || b.order.laneId != lane || !wto_order_is_offensive(b.order.role) + continue + let uIdx = wto_world_find_unit(world, b.eid) + if uIdx < 0 + continue + assigned++ + let pos = world.units[uIdx].pos + if wto_xz_dist_sq(pos, rPos) <= rallyRadSq || wto_xz_dist_sq(pos, world.caps[c].center) < rDistToCapSq + arrived++ + if assigned <= 1 + lanes.rallyReleased[sk] = true + continue + if arrived > 0 && lanes.rallyStartAt[sk] < 0.0 + lanes.rallyStartAt[sk] = now + let enough = float(arrived) >= float(assigned) * WTO_AI_CMD_RALLY_MIN_FRAC + let timedOut = lanes.rallyStartAt[sk] >= 0.0 && (now - lanes.rallyStartAt[sk]) >= WTO_AI_CMD_RALLY_WAIT_SEC + if enough || timedOut + lanes.rallyReleased[sk] = true + if WTO_AI_DIAG_TELEMETRY + print("WTO_AI|RALLY_GO|t={now}|army={army}|cap={c}|lane={lane}|arrived={arrived}/{assigned}|timeout={timedOut}\n") + +// Once a second: advance lane building, release rallies and send released bots on their way. +[never_inline] +def public wto_lanes_tick_rallies(world : WtoWorldSnap const&; now : float; var lanes : WtoTeamLanes&; + var bots : WtoBotSlot[64]&) + wto_lanes_update_rallies(world, 1, now, lanes, bots) + wto_lanes_update_rallies(world, 2, now, lanes, bots) + for i in range(WTO_MAX_BOTS) + assume b = bots[i] + if !b.used || !b.order.valid || !b.order.rallyHold || b.order.capIndex < 0 + continue + if !lanes.rallyReleased[wto_lanes_sub_key(b.army, b.order.capIndex, b.order.laneId)] + continue + b.order.rallyHold = false + if b.order.role == WTO_CMD_FLANK && b.order.laneId > 0 + let fKey = wto_lanes_cap_key(b.army, b.order.capIndex) * 2 + b.order.laneId - 1 + b.order.routeRelayValid = lanes.flankValid[fKey] + b.order.routeRelayPos = lanes.flankRelay[fKey] + else + b.order.routeRelayValid = false \ No newline at end of file diff --git a/game-ai/ground/wto_ai_lanes_common.das b/game-ai/ground/wto_ai_lanes_common.das index 25e52cf..99815d9 100644 --- a/game-ai/ground/wto_ai_lanes_common.das +++ b/game-ai/ground/wto_ai_lanes_common.das @@ -1,26 +1,32 @@ -// Team-level navmesh flank lanes (center / left / right), 40% rally staging & launch state, -// cap recall timers, and enemy air threat tracking. +// Team-level flank lanes (center / left / right) and their 40% rally staging state, cap recall +// timers, and enemy air threat tracking. Lanes are built in wto_ai_lanes_build_common. options indenting = 2 options no_global_heap = true module wto_ai_lanes_common shared require ecs require math -require pathfinder require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_order_common require %appGame.wtoai.wto_ai_types_common -require %appGame.wtoai.wto_ai_terrain_common require %appGame.wtoai.wto_ai_world_common let public WTO_LANE_CENTER = 0 let public WTO_LANE_LEFT = 1 let public WTO_LANE_RIGHT = 2 +// Lane building per team x capture zone: not started, center path queued, flank legs queued, done. +let public WTO_LANES_IDLE = 0 +let public WTO_LANES_CENTER = 1 +let public WTO_LANES_LEGS = 2 +let public WTO_LANES_BUILT = 3 + [safe_when_uninitialized] struct public WtoTeamLanes - built : bool[16] + navState : int = 0 + phase : int[16] + ticket : int[80] centerLen : float[16] centerMid : float3[16] flankValid : bool[32] @@ -44,7 +50,7 @@ def public wto_lanes_sub_key(army, capIdx, laneId : int) : int [never_inline] def public wto_lanes_reset(var lanes : WtoTeamLanes&) for i in range(16) - lanes.built[i] = false + lanes.phase[i] = WTO_LANES_IDLE lanes.centerLen[i] = 0.0 lanes.centerMid[i] = float3(0.0, 0.0, 0.0) lanes.capSafeSince[i] = -100.0 @@ -56,6 +62,8 @@ def public wto_lanes_reset(var lanes : WtoTeamLanes&) lanes.rallyPos[i] = float3(0.0, 0.0, 0.0) lanes.rallyStartAt[i] = -100.0 lanes.rallyReleased[i] = false + for i in range(80) + lanes.ticket[i] = 0 for a in range(3) lanes.enemyAirActive[a] = false lanes.enemyAirSeenAt[a] = -100.0 @@ -66,92 +74,6 @@ def public wto_lanes_reset_rallies(var lanes : WtoTeamLanes&) lanes.rallyStartAt[i] = -100.0 lanes.rallyReleased[i] = false -[never_inline] -def private wto_nav_project_pt(navIdx : int; var pt : float3&) : bool - if project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(28.0, 64.0, 28.0)) - return true - return project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(150.0, 120.0, 150.0)) - -[never_inline] -def private wto_measure_nav_path(navIdx : int; fromPt, toPt : float3; sampleFrac : float; - var outLen : float&; var outSample : float3&) : bool - var sPt = fromPt - var gPt = toPt - if !wto_nav_project_pt(navIdx, sPt) || !wto_nav_project_pt(navIdx, gPt) - return false - var ok = false - var totalLen = 0.0 - var sample = lerp(sPt, gPt, sampleFrac) - find_path_ex(navIdx, sPt, gPt, float3(32.0, 48.0, 32.0), 9.0, 2.5, null) <| $(path : array#) - let n = length(path) - if n < 2 - return - ok = true - for i in range(1, n) - totalLen += length(path[i] - path[i - 1]) - let targetD = totalLen * clamp(sampleFrac, 0.05, 0.95) - var acc = 0.0 - sample = path[n - 1] - for i in range(1, n) - let seg = length(path[i] - path[i - 1]) - if acc + seg >= targetD && seg > 0.01 - sample = lerp(path[i - 1], path[i], (targetD - acc) / seg) - break - acc += seg - outLen = totalLen - outSample = sample - return ok && totalLen > 1.0 - -[never_inline] -def public wto_lanes_ensure_cap(world : WtoWorldSnap const&; army, capIdx : int; - var lanes : WtoTeamLanes&) - let k = wto_lanes_cap_key(army, capIdx) - if lanes.built[k] || capIdx < 0 || capIdx >= world.capCount || !world.teamSpawnValid[army] - return - let navIdx = pathfinder_is_loaded_ex(1) ? 1 : (pathfinder_is_loaded_ex(0) ? 0 : -1) - if navIdx < 0 - return - lanes.built[k] = true - let spawnPt = world.teamSpawnCenter[army] - let capPt = world.caps[capIdx].center - var cLen = 0.0 - var cRally = lerp(spawnPt, capPt, WTO_AI_CMD_RALLY_PROG_FRAC) - if !wto_measure_nav_path(navIdx, spawnPt, capPt, WTO_AI_CMD_RALLY_PROG_FRAC, cLen, cRally) - cLen = max(80.0, sqrt(wto_xz_dist_sq(spawnPt, capPt))) - var cMid = lerp(spawnPt, capPt, 0.5) - var dummyLen = 0.0 - let _midOk = wto_measure_nav_path(navIdx, spawnPt, capPt, 0.5, dummyLen, cMid) - lanes.centerLen[k] = cLen - lanes.centerMid[k] = cMid - lanes.rallyPos[k * 3 + WTO_LANE_CENTER] = cRally - - let toCap = wto_xz_normalize(capPt - spawnPt, float3(1.0, 0.0, 0.0)) - let lat = float3(-toCap.z, 0.0, toCap.x) - let straightD = sqrt(wto_xz_dist_sq(spawnPt, capPt)) - let swing = clamp(straightD * 0.34, 80.0, 260.0) - for side in range(2) - let sign = side == 0 ? 1.0 : -1.0 - var relay = wto_clamp_battle_xz(lerp(spawnPt, capPt, 0.5) + lat * (sign * swing), world.battleCenter, world.battleRadius, 45.0) - let fKey = k * 2 + side - lanes.flankValid[fKey] = false - if !wto_nav_project_pt(navIdx, relay) || !wto_terrain_point_valid(army, relay) - continue - if sqrt(wto_xz_dist_sq(relay, cMid)) < WTO_AI_CMD_FLANK_MIN_SEP_M - continue - var len1 = 0.0 - var len2 = 0.0 - var rPt = lerp(spawnPt, relay, 0.8) - var dummy = relay - if !wto_measure_nav_path(navIdx, spawnPt, relay, 0.8, len1, rPt) - continue - if !wto_measure_nav_path(navIdx, relay, capPt, 0.5, len2, dummy) - continue - if (len1 + len2) > cLen * WTO_AI_CMD_FLANK_MAX_RATIO - continue - lanes.flankValid[fKey] = true - lanes.flankRelay[fKey] = relay - lanes.rallyPos[k * 3 + side + 1] = rPt - [never_inline] def public wto_lanes_update_team_intel(world : WtoWorldSnap const&; now : float; var lanes : WtoTeamLanes&) @@ -193,42 +115,3 @@ def public wto_lanes_update_recall(world : WtoWorldSnap const&; army : int; now elif lanes.recallActive[k] && (now - lanes.capSafeSince[k]) >= WTO_AI_CMD_RECALL_SAFE_SEC lanes.recallActive[k] = false -[never_inline] -def public wto_lanes_update_rallies(world : WtoWorldSnap const&; army : int; now : float; - var lanes : WtoTeamLanes&; var bots : WtoBotSlot[64]&) - let rallyRadSq = wto_sq(WTO_AI_CMD_RALLY_RADIUS_M) - for c in range(world.capCount) - wto_lanes_ensure_cap(world, army, c, lanes) - for lane in range(3) - let sk = wto_lanes_sub_key(army, c, lane) - if lanes.rallyReleased[sk] - continue - let rPos = lanes.rallyPos[sk] - if length_sq(rPos) < 1.0 - lanes.rallyReleased[sk] = true - continue - let rDistToCapSq = wto_xz_dist_sq(rPos, world.caps[c].center) - var assigned = 0 - var arrived = 0 - for i in range(WTO_MAX_BOTS) - assume b = bots[i] - if !b.used || b.army != army || !b.order.valid || b.order.capIndex != c || b.order.laneId != lane || !wto_order_is_offensive(b.order.role) - continue - let uIdx = wto_world_find_unit(world, b.eid) - if uIdx < 0 - continue - assigned++ - let pos = world.units[uIdx].pos - if wto_xz_dist_sq(pos, rPos) <= rallyRadSq || wto_xz_dist_sq(pos, world.caps[c].center) < rDistToCapSq - arrived++ - if assigned <= 1 - lanes.rallyReleased[sk] = true - continue - if arrived > 0 && lanes.rallyStartAt[sk] < 0.0 - lanes.rallyStartAt[sk] = now - let enough = float(arrived) >= float(assigned) * WTO_AI_CMD_RALLY_MIN_FRAC - let timedOut = lanes.rallyStartAt[sk] >= 0.0 && (now - lanes.rallyStartAt[sk]) >= WTO_AI_CMD_RALLY_WAIT_SEC - if enough || timedOut - lanes.rallyReleased[sk] = true - if WTO_AI_DIAG_TELEMETRY - print("WTO_AI|RALLY_GO|t={now}|army={army}|cap={c}|lane={lane}|arrived={arrived}/{assigned}|timeout={timedOut}\n") diff --git a/game-ai/ground/wto_ai_nav_common.das b/game-ai/ground/wto_ai_nav_common.das index f067fe1..cb614e3 100644 --- a/game-ai/ground/wto_ai_nav_common.das +++ b/game-ai/ground/wto_ai_nav_common.das @@ -1,8 +1,8 @@ -// Bidirectional non-holonomic local planner: -// - Directed 7-arc reverse trajectory planner for ridge withdrawals, tactical peeks, cliff escapes, -// and jam unsticking (enabling sustained 30-50m reverse transfers); -// - Stationary combat hull discipline (zero hull-pivot whip on turreted tanks during ENGAGE_HALT); -// - Forward 9-arc DWA rollout with cliff rejection, TTC ally overtaking, and jam/crowd penalties. +// Navigation layer of one bot per nav tick: turns the tactics goal into a drive command. +// Stationary and hull-angle states hold or pivot in place; tactical withdrawals and unstick +// manoeuvres back up along checked ground; otherwise the bot follows its corridor (route) with a +// lookahead point (follow), slows for corners, narrow passages, traffic and fresh obstacles +// (avoid), and escalates when it stops making progress (unstick). options indenting = 2 options no_global_heap = true module wto_ai_nav_common shared @@ -12,147 +12,21 @@ require math require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_nav_types_common require %appGame.wtoai.wto_ai_terrain_common -require %appGame.wtoai.wto_ai_world_common -require %appGame.wtoai.wto_ai_crowd_common +require %appGame.wtoai.wto_ai_navquery_common +require %appGame.wtoai.wto_ai_navmesh_common require %appGame.wtoai.wto_ai_route_common +require %appGame.wtoai.wto_ai_follow_common +require %appGame.wtoai.wto_ai_avoid_common +require %appGame.wtoai.wto_ai_unstick_common [never_inline] -def private wto_wreck_or_ally_clearance(world : WtoWorldSnap const&; selfEid : EntityId; - pt : float3; tSec, selfRad : float) : float - var pen = 0.0 - for w in range(world.wreckCount) - let r = selfRad + max(world.wrecks[w].halfLen, world.wrecks[w].halfWid) + WTO_AI_TERRAIN_MARGIN_M - let dSq = wto_xz_dist_sq(pt, world.wrecks[w].pos) - if dSq < r * r - return 1.0e6 - elif dSq < wto_sq(r + 3.5) - pen += 18.0 - for i in range(world.unitCount) - assume u = world.units[i] - if !u.isAlive || !u.isGround || u.eid == selfEid - continue - let predPos = u.pos + u.vel * min(tSec, 1.6) - let r = selfRad + max(u.halfLen, u.halfWid) + WTO_AI_TERRAIN_MARGIN_M - let dSq = wto_xz_dist_sq(pt, predPos) - if dSq < r * r - return 1.0e6 - elif dSq < wto_sq(r + 5.0) - pen += 22.0 - return pen - -// Evaluate 7 curved rear trajectories (`16m` behind chassis) toward `reverseGoal`. -[never_inline] -def private wto_eval_reverse_arcs(world : WtoWorldSnap const&; now : float; - myPos, hullFwd, reverseGoal : float3; - var slot : WtoBotSlot&; var outRearDir : float3&) : bool - let rearBase = -wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0)) - let baseYaw = atan2(rearBase.z, rearBase.x) - let wishDir = wto_xz_normalize(reverseGoal - myPos, rearBase) - let selfRad = max(slot.spec.halfWid, 1.65) - var bestScore = -1.0e9 - var found = false - outRearDir = rearBase - for a in range(7) - let steerFrac = float(a - 3) / 3.0 - let arcCurv = steerFrac * 0.042 - var cur = myPos - var blocked = false - var arcPen = abs(steerFrac) * 2.5 - for s in range(1, 5) - let dist = float(s) * 3.8 - let yaw = baseYaw + arcCurv * dist - let stepDir = float3(cos(yaw), 0.0, sin(yaw)) - let nx = cur.x + stepDir.x * 3.8 - let nz = cur.z + stepDir.z * 3.8 - var gy = cur.y - if !wto_terrain_drivable_y(cur, nx, nz, gy) - blocked = true - break - if wto_terrain_hard_ray(cur + float3(0.0, 1.25, 0.0), stepDir, 4.2) < 3.7 - blocked = true - break - let nxt = float3(nx, gy, nz) - let dynPen = wto_wreck_or_ally_clearance(world, slot.eid, nxt, dist / max(1.8, slot.spec.vMaxRev), selfRad) - if dynPen >= 1.0e5 - blocked = true - break - arcPen += dynPen * 0.25 + wto_crowd_point_penalty(world, slot.army, slot.eid, nxt) * 0.2 - cur = nxt - if blocked - continue - let firstYaw = baseYaw + arcCurv * 5.5 - let candDir = float3(cos(firstYaw), 0.0, sin(firstYaw)) - if wto_terrain_has_cliff_ahead(myPos, candDir, 15.0) - continue - let score = dot(candDir, wishDir) * 35.0 - arcPen - wto_world_jam_penalty(world, cur, now) * 0.4 - if score > bestScore - bestScore = score - outRearDir = candDir - found = true - return found - -// Evaluate 9 curved forward trajectories (`22m` ahead) with hard cliff rejection and traffic cost. -[never_inline] -def private wto_eval_forward_arcs(world : WtoWorldSnap const&; now : float; - myPos, hullFwd, wishDir : float3; speedCmd : float; - var slot : WtoBotSlot&; var outFwdDir : float3&) : bool - let fwdBase = wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0)) - let baseYaw = atan2(fwdBase.z, fwdBase.x) - let selfRad = max(slot.spec.halfWid, 1.65) - var bestScore = -1.0e9 - var found = false - outFwdDir = wishDir - for a in range(9) - let steerFrac = float(a - 4) / 4.0 - let arcCurv = steerFrac * 0.038 - let firstYaw = baseYaw + arcCurv * 6.5 - let candDir = float3(cos(firstYaw), 0.0, sin(firstYaw)) - if wto_terrain_has_cliff_ahead(myPos, candDir, WTO_AI_TERRAIN_CREST_LOOKAHEAD_M) - continue - var cur = myPos - var blocked = false - var arcPen = abs(steerFrac) * 2.2 - for s in range(1, 6) - let dist = float(s) * 4.2 - let yaw = baseYaw + arcCurv * dist - let stepDir = float3(cos(yaw), 0.0, sin(yaw)) - let nx = cur.x + stepDir.x * 4.2 - let nz = cur.z + stepDir.z * 4.2 - var gy = cur.y - if !wto_terrain_drivable_y(cur, nx, nz, gy) - blocked = true - break - if wto_terrain_hard_ray(cur + float3(0.0, 1.3, 0.0), stepDir, 4.6) < 4.1 - blocked = true - break - let nxt = float3(nx, gy, nz) - let dynPen = wto_wreck_or_ally_clearance(world, slot.eid, nxt, dist / max(2.5, speedCmd), selfRad) - if dynPen >= 1.0e5 - blocked = true - break - arcPen += dynPen * 0.3 + wto_crowd_point_penalty(world, slot.army, slot.eid, nxt) * 0.35 - cur = nxt - if blocked - continue - let align = dot(candDir, wishDir) * 40.0 + dot(candDir, slot.nav.steerDir) * 4.5 - let score = align - arcPen - wto_world_jam_penalty(world, cur, now) - if score > bestScore - bestScore = score - outFwdDir = candDir - found = true - return found - -[never_inline] -def private wto_set_drive_cmd(var cmd : WtoDriveCmd&; mode : int; targetPos, desiredDir : float3; - speedMps, frontClr, rearClr : float) - cmd.valid = true - cmd.mode = mode - cmd.targetPos = targetPos - cmd.desiredDir = desiredDir - cmd.speedMps = speedMps - cmd.frontClearM = frontClr - cmd.rearClearM = rearClr +def private wto_nav_halt(myPos, hullFwd : float3; var slot : WtoBotSlot&) + slot.nav.stuckCheckAt = -100.0 + slot.nav.stuckOrigin = myPos + wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_HALT, myPos, hullFwd, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) + slot.nav.bumperBlockedSince = -100.0 [never_inline] def private wto_handle_stationary_engage(myPos, hullFwd : float3; var slot : WtoBotSlot&) @@ -161,56 +35,135 @@ def private wto_handle_stationary_engage(myPos, hullFwd : float3; var slot : Wto let toTgt = wto_xz_normalize(slot.perceive.knownPos - myPos, hullFwd) let angDeg = acos(clamp(dot(toTgt, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG if angDeg > slot.spec.yawLimitDeg * 0.78 - wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_PIVOT, myPos + toTgt * 18.0, toTgt, 2.0, slot.nav.frontClearM, slot.nav.rearClearM) + slot.nav.stuckCheckAt = -100.0 + wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_PIVOT, myPos + toTgt * 18.0, toTgt, 2.0, slot.nav.frontClearM, slot.nav.rearClearM) return - // Turreted tanks (and aligned TDs) hold chassis completely still so barrel settles cleanly! - wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_HALT, myPos, hullFwd, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) + // Turreted tanks (and aligned TDs) hold the chassis still so the barrel settles cleanly. + wto_nav_halt(myPos, hullFwd, slot) [never_inline] -def private wto_check_stuck_watchdog(var world : WtoWorldSnap&; now : float; - myPos, wishDir : float3; var slot : WtoBotSlot&) - assume nav = slot.nav - let movingIntent = slot.tactics.desiredSpeedMps > 1.2 && now >= nav.reverseUntil - if !movingIntent - nav.stuckOrigin = myPos - nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC - return - if nav.stuckCheckAt < -50.0 - nav.stuckOrigin = myPos - nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC - return - if now < nav.stuckCheckAt - return - let moved = sqrt(wto_xz_dist_sq(myPos, nav.stuckOrigin)) - nav.stuckOrigin = myPos - nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC - if moved >= WTO_AI_NAV_STUCK_MIN_MOVE_M - return - wto_world_record_jam(world, myPos + wishDir * 6.0, now) - wto_route_request_detour(world, now, myPos, wishDir, slot) - let backIdx = clamp(slot.route.corridorIdx - 2, 0, max(0, slot.route.corridorLen - 1)) - nav.reverseAnchor = slot.route.corridorLen > 0 ? slot.route.corridor[backIdx] : (myPos - wishDir * 22.0) - nav.reverseUntil = now + max(WTO_AI_NAV_UNSTICK_REV_SEC, 3.6) - nav.reverseCount++ +def private wto_nav_hull_angle(myPos, hullFwd : float3; var slot : WtoBotSlot&) + let wishAngle = wto_xz_normalize(slot.tactics.hullAngleDir, hullFwd) + let angErr = acos(clamp(dot(wishAngle, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG + if angErr > 8.0 + slot.nav.stuckCheckAt = -100.0 + wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_PIVOT, myPos + wishAngle * 14.0, wishAngle, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) + else + wto_nav_halt(myPos, hullFwd, slot) +// Ridge withdrawal and backing into cover: reverse straight to the goal when the way is free. [never_inline] -def private wto_try_reverse_drive(world : WtoWorldSnap const&; now : float; - myPos, hullFwd : float3; var slot : WtoBotSlot&) : bool - let stMode = slot.tactics.state - let wantTacRev = stMode == WTO_STATE_RIDGE_WITHDRAW || (stMode == WTO_STATE_RETREAT_COVER && slot.tactics.retreatReverse) - if !wantTacRev && now >= slot.nav.reverseUntil +def private wto_nav_tactical_reverse(navState : int; myPos, hullFwd : float3; var slot : WtoBotSlot&) : bool + let st = slot.tactics.state + if st != WTO_STATE_RIDGE_WITHDRAW && !(st == WTO_STATE_RETREAT_COVER && slot.tactics.retreatReverse) return false - let revGoal = wantTacRev ? slot.tactics.moveGoal : slot.nav.reverseAnchor - var rearDir = -hullFwd - if slot.nav.rearClearM > 2.4 && wto_eval_reverse_arcs(world, now, myPos, hullFwd, revGoal, slot, rearDir) - slot.nav.steerDir = rearDir - wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_REVERSE, myPos + rearDir * 18.0, rearDir, max(2.0, slot.spec.vMaxRev), slot.nav.frontClearM, slot.nav.rearClearM) - return true - slot.nav.reverseUntil = -100.0 - return false + let goal = slot.tactics.moveGoal + let dist = sqrt(wto_xz_dist_sq(myPos, goal)) + if dist < 2.0 || slot.nav.rearClearM < 2.4 + return false + if navState == WTO_NAVMESH_LOADED && slot.route.tier >= 0 + var frac = 0.0 + if wto_navq_raycast(slot.route.tier, slot.route.filter, myPos, goal, frac) == 0 && frac * dist < 3.0 + return false + let dir = wto_xz_normalize(goal - myPos, -hullFwd) + slot.nav.steerDir = dir + slot.nav.stuckCheckAt = -100.0 + wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_REVERSE, goal, dir, max(2.0, slot.spec.vMaxRev), slot.nav.frontClearM, slot.nav.rearClearM) + return true + +// Surface, flags and room to the mesh edge under the bot (battles with a pack only). +[never_inline] +def private wto_nav_probe_mesh(navState : int; myPos : float3; var slot : WtoBotSlot&) + assume nav = slot.nav + nav.onMesh = false + nav.wallDistM = 99.0 + nav.surfaceArea = 0 + nav.chokepoint = false + if navState != WTO_NAVMESH_LOADED || slot.route.tier < 0 + return + var probe = WtoNavProbeOut() + if !wto_navq_probe(slot.route.tier, slot.route.filter, myPos, WTO_AI_PF_NARROW_WALL_M + 1.0, probe) || !probe.onMesh + return + nav.onMesh = true + nav.wallDistM = probe.wallDistM + nav.surfaceArea = probe.area + nav.chokepoint = (probe.flags & WTO_NAVQ_FLAG_CHOKEPOINT) != 0 + +// A sideways step is taken only when the mesh allows the straight line to it. +[never_inline] +def private wto_nav_apply_shift(navState : int; myPos, target, dir : float3; var slot : WtoBotSlot&) : float3 + let shift = slot.nav.avoidShiftM + if abs(shift) < 0.01 + return target + let shifted = target + float3(-dir.z, 0.0, dir.x) * shift + if navState != WTO_NAVMESH_LOADED || slot.route.tier < 0 + return shifted + var frac = 0.0 + if wto_navq_raycast(slot.route.tier, slot.route.filter, myPos, shifted, frac) != 0 + return shifted + slot.nav.avoidShiftM = 0.0 + slot.nav.avoidSpeedCap = min(slot.nav.avoidSpeedCap, 2.0) + return target + +// A fresh obstacle in front for bumperBlockSec: mark it for path searches and plan again. +[never_inline] +def private wto_nav_bumper_block(navState : int; now : float; myPos, dir : float3; clear : float; var slot : WtoBotSlot&) + assume nav = slot.nav + if clear >= WTO_AI_PF_BUMPER_STOP_M + 0.5 + nav.bumperBlockedSince = -100.0 + return + if nav.bumperBlockedSince < -50.0 + nav.bumperBlockedSince = now + return + if now - nav.bumperBlockedSince < WTO_AI_PF_BUMPER_BLOCK_SEC + return + nav.bumperBlockedSince = -100.0 + let spot = myPos + dir * (slot.spec.halfLen + clear + 1.0) + if navState == WTO_NAVMESH_LOADED + wto_navq_add_dynamic(spot, WTO_AI_PF_RUBBLE_RADIUS_M, WTO_AI_PF_RUBBLE_COST_MUL, now + WTO_AI_PF_RUBBLE_TTL_SEC) + slot.route.replanRequested = true + print("WTO_AI|NAV_BLOCKED|eid={uint(slot.eid)}|pos={myPos}|spot={spot}\n") [never_inline] -def public wto_nav_update(var world : WtoWorldSnap&; now : float; +def private wto_nav_speed(navState : int; now : float; myPos, dir : float3; lookM : float; narrow : bool; + var slot : WtoBotSlot&) : float + var speed = min(slot.tactics.desiredSpeedMps, wto_follow_speed_cap(slot.route, slot.spec, lookM)) + if narrow + speed = min(speed, WTO_AI_PF_NARROW_SPEED_MPS) + speed = min(speed, slot.nav.avoidSpeedCap) + let clear = wto_avoid_bumper(myPos, dir, slot.spec) + slot.nav.bumperClearM = clear + if clear < WTO_AI_PF_BUMPER_RAY_M + speed = min(speed, max(0.0, clear - WTO_AI_PF_BUMPER_STOP_M) * 1.2) + wto_nav_bumper_block(navState, now, myPos, dir, clear, slot) + return speed + +[never_inline] +def private wto_nav_follow(var world : WtoWorldSnap&; navState : int; now : float; myPos, hullFwd : float3; + var slot : WtoBotSlot&) + assume rt = slot.route + if rt.corridorLen == 0 || wto_follow_arrived(rt, myPos) + wto_nav_halt(myPos, hullFwd, slot) + return + wto_follow_track(myPos, rt) + let speedNow = abs(slot.drive.lastVFwd) + let lookM = wto_follow_lookahead(slot.spec, speedNow) + let pathTarget = wto_follow_target(rt, lookM) + let pathDir = wto_xz_normalize(pathTarget - myPos, hullFwd) + let narrow = slot.nav.wallDistM < WTO_AI_PF_NARROW_WALL_M || slot.nav.chokepoint + wto_avoid_traffic(world, now, myPos, pathDir, speedNow, narrow, slot) + let target = wto_nav_apply_shift(navState, myPos, pathTarget, pathDir, slot) + let dir = wto_xz_normalize(target - myPos, hullFwd) + let speed = wto_nav_speed(navState, now, myPos, dir, lookM, narrow, slot) + slot.nav.steerDir = dir + let turnDeg = acos(clamp(dot(dir, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG + let mode = turnDeg >= WTO_AI_NAV_PIVOT_ANGLE_DEG ? WTO_DRIVE_PIVOT : WTO_DRIVE_CRUISE + wto_drive_cmd_set(slot.driveCmd, mode, target, dir, speed, slot.nav.frontClearM, slot.nav.rearClearM) + let movingIntent = slot.tactics.desiredSpeedMps > 1.2 && now >= slot.nav.yieldUntil + wto_unstick_watch(world, navState, now, myPos, hullFwd, myPos + dir * 6.0, movingIntent, slot) + +[never_inline] +def public wto_nav_update(var world : WtoWorldSnap&; navState, slotIdx : int; now : float; myPos, rawHullFwd : float3; var slot : WtoBotSlot&) if !WTO_AI_LAYER_NAVIGATION slot.driveCmd.valid = false @@ -219,40 +172,19 @@ def public wto_nav_update(var world : WtoWorldSnap&; now : float; let probeBase = myPos + float3(0.0, 1.25, 0.0) slot.nav.frontClearM = wto_terrain_hard_ray(probeBase, hullFwd, 24.0) slot.nav.rearClearM = wto_terrain_hard_ray(probeBase, -hullFwd, 18.0) - slot.nav.cliffAhead = wto_terrain_has_cliff_ahead(myPos, hullFwd, WTO_AI_TERRAIN_CREST_LOOKAHEAD_M) - - if slot.tactics.state == WTO_STATE_HULL_ANGLE - slot.nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC - let wishAngle = wto_xz_normalize(slot.tactics.hullAngleDir, hullFwd) - let angErr = acos(clamp(dot(wishAngle, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG - if angErr > 8.0 - wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_PIVOT, myPos + wishAngle * 14.0, wishAngle, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) - else - wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_HALT, myPos, hullFwd, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) + let st = slot.tactics.state + if st == WTO_STATE_HULL_ANGLE + wto_nav_hull_angle(myPos, hullFwd, slot) return - if slot.tactics.state == WTO_STATE_SHORT_HALT || slot.tactics.state == WTO_STATE_COVER_RELOAD || slot.tactics.desiredSpeedMps <= 0.05 - slot.nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC + if st == WTO_STATE_SHORT_HALT || st == WTO_STATE_COVER_RELOAD || slot.tactics.desiredSpeedMps <= 0.05 wto_handle_stationary_engage(myPos, hullFwd, slot) return - if wto_try_reverse_drive(world, now, myPos, hullFwd, slot) + if wto_nav_tactical_reverse(navState, myPos, hullFwd, slot) || wto_unstick_reversing(now, myPos, slot) return - - let wp = wto_route_select_waypoint(world, now, myPos, slot.tactics.moveGoal, slot) - let wishDir = wto_xz_normalize(wp - myPos, hullFwd) - wto_check_stuck_watchdog(world, now, myPos, wishDir, slot) - - var bestDir = wishDir - if !wto_eval_forward_arcs(world, now, myPos, hullFwd, wishDir, slot.tactics.desiredSpeedMps, slot, bestDir) - if slot.nav.rearClearM > 3.2 - slot.nav.reverseAnchor = myPos - hullFwd * 26.0 - slot.nav.reverseUntil = now + 4.8 - slot.nav.reverseCount++ - wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_REVERSE, slot.nav.reverseAnchor, -hullFwd, max(2.0, slot.spec.vMaxRev), slot.nav.frontClearM, slot.nav.rearClearM) - return - bestDir = wishDir - - slot.nav.steerDir = bestDir - let turnDeg = acos(clamp(dot(wishDir, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG - let needPivot = turnDeg >= WTO_AI_NAV_PIVOT_ANGLE_DEG || (slot.nav.frontClearM < slot.spec.halfLen + 1.8 && turnDeg > 32.0) - let cmdDir = needPivot ? wishDir : bestDir - wto_set_drive_cmd(slot.driveCmd, needPivot ? WTO_DRIVE_PIVOT : WTO_DRIVE_CRUISE, myPos + cmdDir * 22.0, cmdDir, slot.tactics.desiredSpeedMps, slot.nav.frontClearM, slot.nav.rearClearM) + if navState == WTO_NAVMESH_UNDECIDED + wto_nav_halt(myPos, hullFwd, slot) + return + let goal = wto_route_active_goal(myPos, slot.tactics.moveGoal, slot) + wto_route_update(navState, slotIdx, now, myPos, goal, slot) + wto_nav_probe_mesh(navState, myPos, slot) + wto_nav_follow(world, navState, now, myPos, hullFwd, slot) diff --git a/game-ai/ground/wto_ai_nav_types_common.das b/game-ai/ground/wto_ai_nav_types_common.das new file mode 100644 index 0000000..318f4db --- /dev/null +++ b/game-ai/ground/wto_ai_nav_types_common.das @@ -0,0 +1,65 @@ +// Per-bot path, path-following, avoidance and unstick state (route / follow / avoid / unstick / +// nav modules) and the shared constants of the navigation layer. +options indenting = 2 +options no_global_heap = true +module wto_ai_nav_types_common shared + +// Corners a path may carry; matches WTO_NAV_RT_MAX_CORNERS of the native engine. +let public WTO_NAV_MAX_CORNERS = 96 + +// Where a bot's corridor came from. +let public WTO_ROUTE_SRC_NONE = 0 +let public WTO_ROUTE_SRC_MESH = 1 +let public WTO_ROUTE_SRC_STOCK = 2 +let public WTO_ROUTE_SRC_RECOVER = 3 + +[safe_when_uninitialized] +struct public WtoRouteState + corridor : float3[96] + corridorLen : int = 0 + source : int = 0 + segIdx : int = 0 + segT : float = 0.0 + offTrackM : float = 0.0 + goal : float3 = float3(0.0, 0.0, 0.0) + truncated : bool = false + pending : bool = false + ticket : int = 0 + pendingGoal : float3 = float3(0.0, 0.0, 0.0) + nextReplanAt : float = -100.0 + replanRequested : bool = false + tier : int = -1 + filter : int = 0 + lastStatus : int = -1 + goalUnreachable : bool = false + unreachableGoal : float3 = float3(0.0, 0.0, 0.0) + requests : int = 0 + noGoalCount : int = 0 + +[safe_when_uninitialized] +struct public WtoNavState + steerDir : float3 = float3(1.0, 0.0, 0.0) + frontClearM : float = 30.0 + rearClearM : float = 16.0 + onMesh : bool = false + wallDistM : float = 99.0 + surfaceArea : int = 0 + chokepoint : bool = false + bumperClearM : float = 99.0 + bumperBlockedSince : float = -100.0 + yieldUntil : float = -100.0 + yieldCooldownUntil : float = -100.0 + avoidShiftM : float = 0.0 + avoidSpeedCap : float = 99.0 + stuckOrigin : float3 = float3(0.0, 0.0, 0.0) + stuckCheckAt : float = -100.0 + unstickAnchor : float3 = float3(0.0, 0.0, 0.0) + unstickLevel : int = 0 + unstickAttempts : int = 0 + lastUnstickAt : float = -100.0 + reverseTarget : float3 = float3(0.0, 0.0, 0.0) + reverseUntil : float = -100.0 + reverseCount : int = 0 + unstickEvents : int = 0 + unreachableEvents : int = 0 + ridgeWithdrawEvents : int = 0 diff --git a/game-ai/ground/wto_ai_navmesh_common.das b/game-ai/ground/wto_ai_navmesh_common.das index 670b10f..e14f978 100644 --- a/game-ai/ground/wto_ai_navmesh_common.das +++ b/game-ai/ground/wto_ai_navmesh_common.das @@ -1,7 +1,8 @@ // Baked navigation pack of the battle (native/wto-nav through the "wtoNav" mission action). -// The native side answers synchronously into the request DataBlock; see local_mp_nav.c. -// The pack is loaded once at battle start; whether the battle uses it, keeps the script's own -// navigation or refuses to drive is decided by that load and never changes mid-battle. +// The pack is read in the background while the battle loads (prefetch) and taken at the first +// world tick (load_map); whether the battle uses it, falls back to stock road paths or refuses to +// drive is decided by that load and never changes mid-battle. Queued path searches advance once +// per world tick within the per-frame budget (pump). options indenting = 2 options no_global_heap = true module wto_ai_navmesh_common shared @@ -13,6 +14,7 @@ require DagorSystem require Mission require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_navquery_common let public WTO_NAVMESH_UNDECIDED = 0 let public WTO_NAVMESH_LOADED = 1 @@ -22,11 +24,14 @@ let public WTO_NAVMESH_OFF = 4 let public WTO_NAVMESH_TIER_STANDARD = 1 let public WTO_NAVMESH_FILTER_TRACKED = 0 -let public WTO_NAVMESH_MAX_POINTS = 96 -let public WTO_NAVMESH_PATH_FULL = 0 -let public WTO_NAVMESH_PATH_PARTIAL = 1 -let public WTO_NAVMESH_PATH_FAILED = 2 +[safe_when_uninitialized] +struct public WtoNavmeshBattle + state : int = 0 + selfTestPhase : int = 0 + selfTestTicket : int[3] + lastQueries : int = -1 + lastMeshQueries : int = -1 [never_inline] def private wto_navmesh_add_costs(var blk : DataBlock&) @@ -47,6 +52,19 @@ def private wto_navmesh_add_costs(var blk : DataBlock&) add(blk, "w_shallowWater", "{WTO_AI_NAVMESH_W_SHALLOW_WATER}") add(blk, "w_chokepoint", "{WTO_AI_NAVMESH_W_CHOKEPOINT}") +// Battle loading: start reading this battle's pack on a background thread. +[never_inline] +def public wto_navmesh_prefetch() + if !WTO_AI_NAVMESH_ENABLED + return + using() <| $(var blk : DataBlock) + add(blk, "op", "prefetch") + call_mission_action("wtoNav", blk) + let answer = datablock_getStr(blk, "state", "") + let level = datablock_getStr(blk, "level", "") + let reason = datablock_getStr(blk, "reason", "") + print("WTO_AI|NAVMESH_PREFETCH|state={answer}|level={level}|reason={reason}\n") + // Asks the native engine for this battle's pack once; returns a WTO_NAVMESH_* state. [never_inline] def public wto_navmesh_load() : int @@ -75,83 +93,87 @@ def public wto_navmesh_load() : int return state [never_inline] -def public wto_navmesh_unload() +def private wto_navmesh_unload() using() <| $(var blk : DataBlock) add(blk, "op", "unload_map") call_mission_action("wtoNav", blk) -// Corners of a path on the mesh of `tier`; returns WTO_NAVMESH_PATH_* and fills count/lenM. +// Advances queued path searches within the per-frame budget and expires dynamic costs. [never_inline] -def public wto_navmesh_find_path(tier, costFilter : int; start, goal : float3; - var pts : float3[96]&; var count : int&; var lenM : float&) : int - var status = WTO_NAVMESH_PATH_FAILED - count = 0 - lenM = 0.0 +def private wto_navmesh_pump(now : float) using() <| $(var blk : DataBlock) - add(blk, "op", "find_path") - add(blk, "tier", "{tier}") - add(blk, "filter", "{costFilter}") - add(blk, "max", "{WTO_NAVMESH_MAX_POINTS}") - add(blk, "snap", "{WTO_AI_NAVMESH_SNAP_M}") - add(blk, "sx", "{start.x}") - add(blk, "sy", "{start.y}") - add(blk, "sz", "{start.z}") - add(blk, "gx", "{goal.x}") - add(blk, "gy", "{goal.y}") - add(blk, "gz", "{goal.z}") + add(blk, "op", "pump") + add(blk, "now", "{now}") + add(blk, "budgetUs", "{WTO_AI_NAVMESH_PATH_BUDGET_US}") call_mission_action("wtoNav", blk) - let answer = datablock_getStr(blk, "status", "") - status = answer == "full" ? WTO_NAVMESH_PATH_FULL : answer == "partial" ? WTO_NAVMESH_PATH_PARTIAL : WTO_NAVMESH_PATH_FAILED - if status == WTO_NAVMESH_PATH_FAILED - return - count = clamp(datablock_getInt(blk, "count", 0), 0, WTO_NAVMESH_MAX_POINTS) - lenM = float(datablock_getInt(blk, "lenCm", 0)) * 0.01 - for i in range(count) - let px = datablock_getInt(blk, "p{i}x", 0) - let py = datablock_getInt(blk, "p{i}y", 0) - let pz = datablock_getInt(blk, "p{i}z", 0) - pts[i] = float3(float(px) * 0.01, float(py) * 0.01, float(pz) * 0.01) - return status -// Logs one path per team from its spawn to the first capture zone; proves the round trip. +// One path per team from its spawn to the first capture zone through the queued search. [never_inline] -def public wto_navmesh_self_test(world : WtoWorldSnap const&) : bool - if world.capCount <= 0 || !world.teamSpawnValid[1] || !world.teamSpawnValid[2] - return false +def private wto_navmesh_self_test(world : WtoWorldSnap const&; var nm : WtoNavmeshBattle&) + if nm.selfTestPhase == 0 + if world.capCount <= 0 || !world.teamSpawnValid[1] || !world.teamSpawnValid[2] + return + for army in range(1, 3) + nm.selfTestTicket[army] = wto_navq_path_request(WTO_NAVQ_SELFTEST_SLOT0 + army - 1, WTO_NAVMESH_TIER_STANDARD, + WTO_NAVMESH_FILTER_TRACKED, world.teamSpawnCenter[army], world.caps[0].center) + nm.selfTestPhase = 1 + return + if nm.selfTestPhase != 1 + return var pts : float3[96] + var finished = 0 for army in range(1, 3) var count = 0 var lenM = 0.0 - let status = wto_navmesh_find_path(WTO_NAVMESH_TIER_STANDARD, WTO_NAVMESH_FILTER_TRACKED, - world.teamSpawnCenter[army], world.caps[0].center, pts, count, lenM) + var truncated = false + let status = wto_navq_path_result(WTO_NAVQ_SELFTEST_SLOT0 + army - 1, nm.selfTestTicket[army], pts, count, lenM, truncated) + if status == WTO_PATH_PENDING + continue + finished++ + if nm.selfTestTicket[army] == 0 + continue let last = count > 0 ? pts[count - 1] : float3(0.0, 0.0, 0.0) print("WTO_AI|NAVMESH_SELFTEST|army={army}|status={status}|corners={count}|lenM={lenM}|from={world.teamSpawnCenter[army]}|to={world.caps[0].center}|end={last}\n") - return true + nm.selfTestTicket[army] = 0 + if finished == 2 + nm.selfTestPhase = 2 -// Per world tick: decide the battle's navigation once, then prove a path per team once. +// Per world tick: decide the battle's navigation once, then pump searches and run the self test. [never_inline] -def public wto_navmesh_battle_tick(world : WtoWorldSnap const&; var state : int&; var selfTested : bool&) - if state == WTO_NAVMESH_UNDECIDED - state = wto_navmesh_load() - if state == WTO_NAVMESH_LOADED && !selfTested - selfTested = wto_navmesh_self_test(world) +def public wto_navmesh_battle_tick(world : WtoWorldSnap const&; now : float; var nm : WtoNavmeshBattle&) + if nm.state == WTO_NAVMESH_UNDECIDED + nm.state = wto_navmesh_load() + if nm.state != WTO_NAVMESH_LOADED + return + wto_navmesh_pump(now) + wto_navmesh_self_test(world, nm) // Battle end: release the pack and forget the decision. [never_inline] -def public wto_navmesh_battle_reset(var state : int&; var selfTested : bool&) - if state != WTO_NAVMESH_UNDECIDED && state != WTO_NAVMESH_OFF +def public wto_navmesh_battle_reset(var nm : WtoNavmeshBattle&) + if nm.state != WTO_NAVMESH_UNDECIDED && nm.state != WTO_NAVMESH_OFF wto_navmesh_unload() - state = WTO_NAVMESH_UNDECIDED - selfTested = false + nm = WtoNavmeshBattle() +// Engine statistics, printed only when they changed since the last print. [never_inline] -def public wto_navmesh_log_stats() +def public wto_navmesh_log_stats(var nm : WtoNavmeshBattle&) + if nm.state != WTO_NAVMESH_LOADED + return using() <| $(var blk : DataBlock) add(blk, "op", "get_stats") call_mission_action("wtoNav", blk) - let loaded = datablock_getInt(blk, "loaded", 0) let queries = datablock_getInt(blk, "queries", 0) + let meshQueries = datablock_getInt(blk, "meshQueries", 0) + if queries == nm.lastQueries && meshQueries == nm.lastMeshQueries + return + nm.lastQueries = queries + nm.lastMeshQueries = meshQueries let failures = datablock_getInt(blk, "failures", 0) let avgUs = datablock_getInt(blk, "avgUs", 0) let maxUs = datablock_getInt(blk, "maxUs", 0) - print("WTO_AI|NAVMESH_STATS|loaded={loaded}|queries={queries}|failures={failures}|avgUs={avgUs}|maxUs={maxUs}\n") + let maxFrames = datablock_getInt(blk, "maxFrames", 0) + let pumpMaxUs = datablock_getInt(blk, "pumpMaxUs", 0) + let pending = datablock_getInt(blk, "pending", 0) + let dynCount = datablock_getInt(blk, "dynamic", 0) + print("WTO_AI|NAVMESH_STATS|paths={queries}|failures={failures}|avgUs={avgUs}|maxUs={maxUs}|maxFrames={maxFrames}|pumpMaxUs={pumpMaxUs}|pending={pending}|dynamic={dynCount}|meshQueries={meshQueries}\n") diff --git a/game-ai/ground/wto_ai_navquery_common.das b/game-ai/ground/wto_ai_navquery_common.das new file mode 100644 index 0000000..ffac737 --- /dev/null +++ b/game-ai/ground/wto_ai_navquery_common.das @@ -0,0 +1,173 @@ +// Script side of the native navigation queries ("wtoNav" mission action, local_mp_nav.c): +// queued path searches, mesh probes, mesh raycasts, nearest walkable point and dynamic costs. +// Requests are strings; replies are ints (coordinates in centimetres) and strings. +options indenting = 2 +options no_global_heap = true +module wto_ai_navquery_common shared + +require ecs +require math +require DagorDataBlock +require DagorSystem +require Mission +require %appGame.wtoai.wto_ai_config_common + +let public WTO_PATH_FULL = 0 +let public WTO_PATH_PARTIAL = 1 +let public WTO_PATH_NO_START = 2 +let public WTO_PATH_NO_GOAL = 3 +let public WTO_PATH_FAILED = 4 +let public WTO_PATH_PENDING = 5 +let public WTO_PATH_STALE = 6 + +// Path slots of the native engine: 0..63 bots, 64..143 team lanes, 144..145 battle self test. +let public WTO_NAVQ_LANE_SLOT0 = 64 +let public WTO_NAVQ_SELFTEST_SLOT0 = 144 + +let public WTO_NAVQ_FLAG_CHOKEPOINT = 8 +let public WTO_NAVQ_FLAG_ROAD = 32 + +[safe_when_uninitialized] +struct public WtoNavProbeOut + onMesh : bool = false + nearest : float3 = float3(0.0, 0.0, 0.0) + offsetM : float = 0.0 + wallDistM : float = 99.0 + area : int = 0 + flags : int = 0 + +[never_inline] +def private wto_navq_status(answer : string) : int + if answer == "full" + return WTO_PATH_FULL + if answer == "partial" + return WTO_PATH_PARTIAL + if answer == "no_start" + return WTO_PATH_NO_START + if answer == "no_goal" + return WTO_PATH_NO_GOAL + if answer == "pending" + return WTO_PATH_PENDING + if answer == "stale" + return WTO_PATH_STALE + return WTO_PATH_FAILED + +[never_inline] +def private wto_navq_add_point(var blk : DataBlock&; prefix : string; p : float3) + add(blk, "{prefix}x", "{p.x}") + add(blk, "{prefix}y", "{p.y}") + add(blk, "{prefix}z", "{p.z}") + +[never_inline] +def private wto_navq_get_point(blk : DataBlock const&; kx, ky, kz : string) : float3 + let x = float(datablock_getInt(blk, kx, 0)) * 0.01 + let y = float(datablock_getInt(blk, ky, 0)) * 0.01 + let z = float(datablock_getInt(blk, kz, 0)) * 0.01 + return float3(x, y, z) + +// Queues a path search in native slot `slot`; returns its ticket (0 when refused). +[never_inline] +def public wto_navq_path_request(slot, tier, costFilter : int; start, goal : float3) : int + var ticket = 0 + using() <| $(var blk : DataBlock) + add(blk, "op", "path_request") + add(blk, "slot", "{slot}") + add(blk, "tier", "{tier}") + add(blk, "filter", "{costFilter}") + add(blk, "snap", "{WTO_AI_NAVMESH_SNAP_M}") + add(blk, "goalSnap", "{WTO_AI_NAVMESH_GOAL_SNAP_M}") + wto_navq_add_point(blk, "s", start) + wto_navq_add_point(blk, "g", goal) + call_mission_action("wtoNav", blk) + ticket = datablock_getInt(blk, "ticket", 0) + return ticket + +// Result of a ticket; corners are copied into `pts` only for full and partial paths. +[never_inline] +def public wto_navq_path_result(slot, ticket : int; var pts : float3[96]&; var count : int&; + var lenM : float&; var truncated : bool&) : int + var status = WTO_PATH_FAILED + using() <| $(var blk : DataBlock) + add(blk, "op", "path_result") + add(blk, "slot", "{slot}") + add(blk, "ticket", "{ticket}") + call_mission_action("wtoNav", blk) + status = wto_navq_status(datablock_getStr(blk, "status", "")) + if status != WTO_PATH_FULL && status != WTO_PATH_PARTIAL + return + count = clamp(datablock_getInt(blk, "count", 0), 0, 96) + lenM = float(datablock_getInt(blk, "lenCm", 0)) * 0.01 + truncated = datablock_getInt(blk, "truncated", 0) != 0 + for i in range(count) + pts[i] = wto_navq_get_point(blk, "p{i}x", "p{i}y", "p{i}z") + return status + +// Surface, flags and distance to the mesh edge under `pos`; false when the engine gave no answer. +[never_inline] +def public wto_navq_probe(tier, costFilter : int; pos : float3; wallRadiusM : float; + var probe : WtoNavProbeOut&) : bool + var answered = false + using() <| $(var blk : DataBlock) + add(blk, "op", "probe") + add(blk, "tier", "{tier}") + add(blk, "filter", "{costFilter}") + add(blk, "snap", "{WTO_AI_NAVMESH_SNAP_M}") + add(blk, "wallR", "{wallRadiusM}") + wto_navq_add_point(blk, "p", pos) + call_mission_action("wtoNav", blk) + let onMesh = datablock_getInt(blk, "onMesh", -1) + answered = onMesh >= 0 + probe.onMesh = onMesh == 1 + if !probe.onMesh + return + probe.offsetM = float(datablock_getInt(blk, "offCm", 0)) * 0.01 + probe.wallDistM = float(datablock_getInt(blk, "wallCm", 0)) * 0.01 + probe.area = datablock_getInt(blk, "area", 0) + probe.flags = datablock_getInt(blk, "flags", 0) + probe.nearest = wto_navq_get_point(blk, "nx", "ny", "nz") + return answered + +// 1 when the mesh lets a vehicle go straight from start to goal, 0 when an edge blocks it +// (`hitFrac` of the way), -1 when start is off the mesh or the engine gave no answer. +[never_inline] +def public wto_navq_raycast(tier, costFilter : int; start, goal : float3; var hitFrac : float&) : int + var clear = -1 + hitFrac = 0.0 + using() <| $(var blk : DataBlock) + add(blk, "op", "raycast") + add(blk, "tier", "{tier}") + add(blk, "filter", "{costFilter}") + add(blk, "snap", "{WTO_AI_NAVMESH_SNAP_M}") + wto_navq_add_point(blk, "s", start) + wto_navq_add_point(blk, "g", goal) + call_mission_action("wtoNav", blk) + clear = datablock_getInt(blk, "clear", -1) + hitFrac = float(datablock_getInt(blk, "hitPm", 0)) * 0.001 + return clear + +// Nearest walkable point within `radiusM` horizontally (any height). +[never_inline] +def public wto_navq_nearest(tier, costFilter : int; pos : float3; radiusM : float; var outPt : float3&) : bool + var found = false + using() <| $(var blk : DataBlock) + add(blk, "op", "nearest") + add(blk, "tier", "{tier}") + add(blk, "filter", "{costFilter}") + add(blk, "radius", "{radiusM}") + wto_navq_add_point(blk, "p", pos) + call_mission_action("wtoNav", blk) + found = datablock_getInt(blk, "found", 0) == 1 + if found + outPt = wto_navq_get_point(blk, "x", "y", "z") + return found + +// Makes later path searches avoid a circle (wreck, jam, rubble) until script time `untilAt`. +[never_inline] +def public wto_navq_add_dynamic(pos : float3; radiusM, costMul, untilAt : float) + using() <| $(var blk : DataBlock) + add(blk, "op", "dynamic") + wto_navq_add_point(blk, "p", pos) + add(blk, "radius", "{radiusM}") + add(blk, "mul", "{costMul}") + add(blk, "until", "{untilAt}") + call_mission_action("wtoNav", blk) diff --git a/game-ai/ground/wto_ai_polyline_common.das b/game-ai/ground/wto_ai_polyline_common.das new file mode 100644 index 0000000..e0e4428 --- /dev/null +++ b/game-ai/ground/wto_ai_polyline_common.das @@ -0,0 +1,97 @@ +// XZ geometry on path corner lists (float3[96] plus a count): length, sampling, tracking a +// position along the path and walking forward or back from it. +options indenting = 2 +options no_global_heap = true +module wto_ai_polyline_common shared + +require math +require %appGame.wtoai.wto_ai_math_common + +// Closest point of segment a-b to p in the XZ plane: `t` in 0..1, returns the squared distance. +[never_inline] +def public wto_poly_seg_closest(a, b, p : float3; var t : float&) : float + let abx = b.x - a.x + let abz = b.z - a.z + let lenSq = abx * abx + abz * abz + t = lenSq > 1.0e-6 ? clamp(((p.x - a.x) * abx + (p.z - a.z) * abz) / lenSq, 0.0, 1.0) : 0.0 + let cx = a.x + abx * t + let cz = a.z + abz * t + return wto_sq(p.x - cx) + wto_sq(p.z - cz) + +[never_inline] +def public wto_poly_length(pts : float3[96]; count : int) : float + var total = 0.0 + for i in range(1, count) + total += sqrt(wto_xz_dist_sq(pts[i - 1], pts[i])) + return total + +// Point `frac` (0..1) of the way along the path. +[never_inline] +def public wto_poly_sample(pts : float3[96]; count : int; frac : float) : float3 + if count <= 0 + return float3(0.0, 0.0, 0.0) + let target = wto_poly_length(pts, count) * clamp(frac, 0.0, 1.0) + var acc = 0.0 + for i in range(1, count) + let seg = sqrt(wto_xz_dist_sq(pts[i - 1], pts[i])) + if acc + seg >= target && seg > 0.01 + return lerp(pts[i - 1], pts[i], (target - acc) / seg) + acc += seg + return pts[count - 1] + +// Segment closest to `pos` among the few after `fromSeg` (never behind it); returns the XZ distance. +[never_inline] +def public wto_poly_track(pts : float3[96]; count : int; fromSeg : int; pos : float3; + var seg : int&; var t : float&) : float + seg = clamp(fromSeg, 0, max(0, count - 2)) + t = 0.0 + if count < 2 + return count == 1 ? sqrt(wto_xz_dist_sq(pos, pts[0])) : 0.0 + var bestSq = 1.0e12 + let last = min(count - 2, seg + 6) + for k in range(seg, last + 1) + var tk = 0.0 + let dSq = wto_poly_seg_closest(pts[k], pts[k + 1], pos, tk) + if dSq <= bestSq + bestSq = dSq + seg = k + t = tk + return sqrt(bestSq) + +// Point `dist` metres further along the path than (seg, t); the last corner when past the end. +[never_inline] +def public wto_poly_walk(pts : float3[96]; count : int; seg : int; t, dist : float) : float3 + if count <= 0 + return float3(0.0, 0.0, 0.0) + if count == 1 + return pts[0] + let s0 = clamp(seg, 0, count - 2) + var cur = lerp(pts[s0], pts[s0 + 1], t) + var left = dist + for k in range(s0 + 1, count) + let segLen = sqrt(wto_xz_dist_sq(cur, pts[k])) + if segLen >= left && segLen > 1.0e-3 + return lerp(cur, pts[k], left / segLen) + left -= segLen + cur = pts[k] + return pts[count - 1] + +// Point `dist` metres back along the path from (seg, t); the first corner when past the start. +[never_inline] +def public wto_poly_walk_back(pts : float3[96]; count : int; seg : int; t, dist : float) : float3 + if count <= 0 + return float3(0.0, 0.0, 0.0) + if count == 1 + return pts[0] + let s0 = clamp(seg, 0, count - 2) + var cur = lerp(pts[s0], pts[s0 + 1], t) + var left = dist + var k = s0 + while k >= 0 + let segLen = sqrt(wto_xz_dist_sq(cur, pts[k])) + if segLen >= left && segLen > 1.0e-3 + return lerp(cur, pts[k], left / segLen) + left -= segLen + cur = pts[k] + k-- + return pts[0] diff --git a/game-ai/ground/wto_ai_route_common.das b/game-ai/ground/wto_ai_route_common.das index 086eef2..9185276 100644 --- a/game-ai/ground/wto_ai_route_common.das +++ b/game-ai/ground/wto_ai_route_common.das @@ -1,169 +1,160 @@ -// Corridor route planner: wide-projected `nm1` NavMesh pathfinding (fixing off-road hill caps), -// 5-wing lateral approach relays, crest-safe cross-country shortcuts, and corridor-independent -// jam/cluster bypass waypoints. +// Corridor of every bot: which mesh tier and cost filter fit the vehicle, when to plan again +// (goal moved, off the corridor, timer, obstacle reported) and where the path comes from — queued +// native searches on the battle's pack, or the stock road mesh when the battle fell back. options indenting = 2 options no_global_heap = true module wto_ai_route_common shared require ecs require math -require pathfinder require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_types_common -require %appGame.wtoai.wto_ai_terrain_common -require %appGame.wtoai.wto_ai_world_common -require %appGame.wtoai.wto_ai_crowd_common +require %appGame.wtoai.wto_ai_nav_types_common +require %appGame.wtoai.wto_ai_polyline_common +require %appGame.wtoai.wto_ai_navquery_common +require %appGame.wtoai.wto_ai_navmesh_common +require %appGame.wtoai.wto_ai_stockpath_common + +// Mesh tier by vehicle width as baked: narrow up to 2.9 m, standard up to 3.6 m, wide above. +// spec.halfWid carries the 0.18 m collision margin of wto_specs_load, removed here. +[never_inline] +def public wto_route_tier(spec : WtoVehicleSpec const&) : int + let width = max(0.0, spec.halfWid - 0.18) * 2.0 + if width <= 2.9 + return 0 + if width <= 3.6 + return 1 + return 2 [never_inline] -def private wto_project_nav_wide(navIdx : int; var pt : float3&) : bool - if project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(28.0, 64.0, 28.0)) - return true - return project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(165.0, 130.0, 165.0)) +def public wto_route_filter(spec : WtoVehicleSpec const&) : int + return spec.isTracked ? 0 : 1 +// Destination of this tick: the order's relay (flank or rally) while marching toward it. [never_inline] -def private wto_replan_corridor(now : float; myPos, goal : float3; var rt : WtoRouteState&) - rt.nextReplanAt = now + 2.8 - rt.corridorGoal = goal - rt.corridorLen = 0 - rt.corridorIdx = 0 - let navIdx = pathfinder_is_loaded_ex(1) ? 1 : (pathfinder_is_loaded_ex(0) ? 0 : -1) - if navIdx < 0 - rt.lastStartOk = false - rt.lastGoalOk = false - return - var sPt = myPos - var gPt = goal - rt.lastStartOk = wto_project_nav_wide(navIdx, sPt) - rt.lastGoalOk = wto_project_nav_wide(navIdx, gPt) - if !rt.lastStartOk || !rt.lastGoalOk - return - let maxKeep = WTO_MAX_PATH_PTS - 1 - find_path_ex(navIdx, sPt, gPt, float3(32.0, 48.0, 32.0), 9.0, 2.5, null) <| $(path : array#) - let total = length(path) - if total <= 0 - return - rt.corridor[0] = path[0] - rt.corridorLen = 1 - let minStepSq = total > maxKeep ? wto_sq(max(12.0, float(total) * 9.0 / float(maxKeep))) : 0.0 - for i in range(1, total) - if rt.corridorLen >= maxKeep - break - let prev = rt.corridor[rt.corridorLen - 1] - var isCorner = false - if i + 1 < total - let d0 = wto_xz_normalize(path[i] - prev, float3(1.0, 0.0, 0.0)) - let d1 = wto_xz_normalize(path[i + 1] - path[i], d0) - isCorner = dot(d0, d1) < 0.86 - if i == total - 1 || isCorner || wto_xz_dist_sq(prev, path[i]) >= minStepSq - rt.corridor[rt.corridorLen] = path[i] - rt.corridorLen++ - if rt.corridorLen < maxKeep && wto_xz_dist_sq(rt.corridor[rt.corridorLen - 1], path[total - 1]) > 9.0 - rt.corridor[rt.corridorLen] = path[total - 1] - rt.corridorLen++ - if rt.corridorLen > 0 && rt.corridorLen < WTO_MAX_PATH_PTS && wto_xz_dist_sq(rt.corridor[rt.corridorLen - 1], goal) > 64.0 - rt.corridor[rt.corridorLen] = goal - rt.corridorLen++ - -// Validate a crest-safe cross-country shortcut (<= 145m) with zero cliff drop-offs or jams. -[never_inline] -def private wto_try_shortcut(world : WtoWorldSnap const&; now : float; myPos, target : float3; - var slot : WtoBotSlot&) - assume rt = slot.route - rt.shortcutValid = false - rt.nextShortcutAt = now + 1.1 - let dist = sqrt(wto_xz_dist_sq(myPos, target)) - if dist < 22.0 || dist > 145.0 - return - let dir = wto_xz_normalize(target - myPos, float3(1.0, 0.0, 0.0)) - if wto_terrain_has_cliff_ahead(myPos, dir, min(dist, WTO_AI_TERRAIN_CREST_LOOKAHEAD_M + 8.0)) - return - let steps = clamp(int(dist / 7.5), 2, 20) - var prev = myPos - for s in range(1, steps + 1) - let d = (dist * float(s)) / float(steps) - let tx = myPos.x + dir.x * d - let tz = myPos.z + dir.z * d - var gy = prev.y - if !wto_terrain_drivable_y(prev, tx, tz, gy) - return - let samplePt = float3(tx, gy, tz) - if wto_world_jam_penalty(world, samplePt, now) > 4.0 || wto_crowd_point_penalty(world, slot.army, slot.eid, samplePt) > 18.0 - return - if wto_terrain_hard_ray(prev + float3(0.0, 1.3, 0.0), dir, 8.0) < 7.5 - return - prev = samplePt - rt.shortcutPos = target - rt.shortcutValid = true - -// Generate a lateral bypass waypoint around an obstacle/jam, even when no NavMesh corridor exists. -[never_inline] -def public wto_route_request_detour(world : WtoWorldSnap const&; now : float; - myPos, blockedDir : float3; var slot : WtoBotSlot&) - assume rt = slot.route - let fwd = wto_xz_normalize(blockedDir, float3(1.0, 0.0, 0.0)) - let lat = float3(-fwd.z, 0.0, fwd.x) - let pref = ((uint(slot.eid) + uint(rt.detourCount)) & 1u) == 0u ? 1.0 : -1.0 - var bestScore = -1.0e9 - var found = false - var bestPt = myPos - for k in range(4) - let side = (k % 2 == 0 ? pref : -pref) * (k < 2 ? 38.0 : 56.0) - let fwdStep = k < 2 ? 22.0 : 12.0 - var cand = wto_clamp_battle_xz(myPos + fwd * fwdStep + lat * side, world.battleCenter, world.battleRadius, 35.0) - if !wto_terrain_point_valid(slot.army, cand) - continue - let candDir = wto_xz_normalize(cand - myPos, lat) - if wto_terrain_has_cliff_ahead(myPos, candDir, 18.0) - continue - if wto_terrain_hard_ray(myPos + float3(0.0, 1.3, 0.0), candDir, 16.0) < 10.0 - continue - let score = -wto_world_jam_penalty(world, cand, now) - wto_crowd_point_penalty(world, slot.army, slot.eid, cand) - if score > bestScore - bestScore = score - bestPt = cand - found = true - if found - rt.detourPos = bestPt - rt.detourValid = true - rt.detourUntil = now + 11.0 - rt.detourCount++ - -[never_inline] -def public wto_route_select_waypoint(world : WtoWorldSnap const&; now : float; - myPos, finalGoal : float3; var slot : WtoBotSlot&) : float3 - assume rt = slot.route - if rt.detourValid - if now < rt.detourUntil && wto_xz_dist_sq(myPos, rt.detourPos) > 100.0 - return rt.detourPos - rt.detourValid = false - - if !rt.wingInit - rt.wingInit = true - rt.laneOffsetM = float(int((uint(slot.eid) / 5u) % 5u) - 2) * 4.0 +def public wto_route_active_goal(myPos, finalGoal : float3; slot : WtoBotSlot const&) : float3 let st = slot.tactics.state - let useRelay = (st == WTO_STATE_MARCH || st == WTO_STATE_PREAIM || st == WTO_STATE_RELOAD_ADVANCE) && slot.order.routeRelayValid - var activeGoal = finalGoal - if useRelay - let relay = slot.order.routeRelayPos - let distMeToRelaySq = wto_xz_dist_sq(myPos, relay) - let distMeToGoalSq = wto_xz_dist_sq(myPos, finalGoal) - let distRelayToGoalSq = wto_xz_dist_sq(relay, finalGoal) - if slot.order.rallyHold || (distMeToRelaySq > 1444.0 && distMeToGoalSq > distRelayToGoalSq) - activeGoal = relay + let marching = st == WTO_STATE_MARCH || st == WTO_STATE_PREAIM || st == WTO_STATE_RELOAD_ADVANCE + if !marching || !slot.order.routeRelayValid + return finalGoal + let relay = slot.order.routeRelayPos + let meToRelaySq = wto_xz_dist_sq(myPos, relay) + if slot.order.rallyHold || (meToRelaySq > 1444.0 && wto_xz_dist_sq(myPos, finalGoal) > wto_xz_dist_sq(relay, finalGoal)) + return relay + return finalGoal - if now >= rt.nextShortcutAt - wto_try_shortcut(world, now, myPos, activeGoal, slot) - if rt.shortcutValid && wto_xz_dist_sq(rt.shortcutPos, activeGoal) <= 144.0 - return activeGoal +[never_inline] +def private wto_route_accept(var rt : WtoRouteState&; count : int; goal : float3; truncated : bool; source : int) + rt.corridorLen = count + rt.segIdx = 0 + rt.segT = 0.0 + rt.offTrackM = 0.0 + rt.goal = goal + rt.truncated = truncated + rt.source = source + rt.goalUnreachable = false - if now >= rt.nextReplanAt || wto_xz_dist_sq(rt.corridorGoal, activeGoal) > 400.0 - wto_replan_corridor(now, myPos, activeGoal, rt) - while rt.corridorIdx < rt.corridorLen - 1 && wto_xz_dist_sq(myPos, rt.corridor[rt.corridorIdx]) <= 256.0 - rt.corridorIdx++ - if rt.corridorLen > 0 && rt.corridorIdx < rt.corridorLen - let wp = rt.corridor[rt.corridorIdx] - let toWp = wto_xz_normalize(wp - myPos, float3(1.0, 0.0, 0.0)) - let lat = float3(-toWp.z, 0.0, toWp.x) - return wp + lat * clamp(rt.laneOffsetM, -6.0, 6.0) - return activeGoal +// Straight two-point corridor (stock fallback without a road path, or back onto the mesh). +[never_inline] +def private wto_route_straight(var rt : WtoRouteState&; myPos, goal : float3; source : int) + rt.corridor[0] = myPos + rt.corridor[1] = goal + wto_route_accept(rt, 2, goal, source == WTO_ROUTE_SRC_RECOVER, source) + +[never_inline] +def private wto_route_request(navState, slotIdx : int; now : float; myPos, goal : float3; var slot : WtoBotSlot&) + assume rt = slot.route + rt.tier = wto_route_tier(slot.spec) + rt.filter = wto_route_filter(slot.spec) + rt.nextReplanAt = now + WTO_AI_PF_REPLAN_SEC + rt.replanRequested = false + rt.requests++ + if navState == WTO_NAVMESH_LOADED + rt.ticket = wto_navq_path_request(slotIdx, rt.tier, rt.filter, myPos, goal) + rt.pending = rt.ticket > 0 + rt.pendingGoal = goal + return + var count = 0 + if wto_stock_path(myPos, goal, rt.corridor, count) + wto_route_accept(rt, count, goal, false, WTO_ROUTE_SRC_STOCK) + else + wto_route_straight(rt, myPos, goal, WTO_ROUTE_SRC_STOCK) + +// The bot stands off the mesh: head for the nearest walkable point, then plan again from there. +[never_inline] +def private wto_route_recover(now : float; myPos : float3; var rt : WtoRouteState&) + var onMesh = myPos + rt.nextReplanAt = now + 1.0 + if wto_navq_nearest(rt.tier, rt.filter, myPos, WTO_AI_NAVMESH_GOAL_SNAP_M, onMesh) + wto_route_straight(rt, myPos, onMesh, WTO_ROUTE_SRC_RECOVER) + else + rt.corridorLen = 0 + +[never_inline] +def private wto_route_poll(slotIdx : int; now : float; myPos : float3; var slot : WtoBotSlot&) + assume rt = slot.route + var count = 0 + var lenM = 0.0 + var truncated = false + let status = wto_navq_path_result(slotIdx, rt.ticket, rt.corridor, count, lenM, truncated) + if status == WTO_PATH_PENDING + return + rt.pending = false + rt.lastStatus = status + if (status == WTO_PATH_FULL || status == WTO_PATH_PARTIAL) && count >= 1 + wto_route_accept(rt, count, rt.pendingGoal, truncated, WTO_ROUTE_SRC_MESH) + elif status == WTO_PATH_NO_START + wto_route_recover(now, myPos, rt) + elif status == WTO_PATH_NO_GOAL + rt.corridorLen = 0 + rt.goalUnreachable = true + rt.unreachableGoal = rt.pendingGoal + rt.noGoalCount++ + print("WTO_AI|ROUTE_NO_GOAL|eid={uint(slot.eid)}|tier={rt.tier}|pos={myPos}|goal={rt.pendingGoal}\n") + else + rt.nextReplanAt = now + 1.0 + +[never_inline] +def private wto_route_needs_plan(now : float; goal : float3; slot : WtoBotSlot const&) : bool + assume rt = slot.route + let moveSq = wto_sq(WTO_AI_PF_REPLAN_GOAL_MOVE_M) + if rt.goalUnreachable && wto_xz_dist_sq(rt.unreachableGoal, goal) <= moveSq + return now >= rt.nextReplanAt + return (rt.corridorLen == 0 || rt.replanRequested || now >= rt.nextReplanAt || + wto_xz_dist_sq(rt.goal, goal) > moveSq || rt.offTrackM > WTO_AI_PF_OFF_TRACK_REPLAN_M || + rt.tier != wto_route_tier(slot.spec) || rt.filter != wto_route_filter(slot.spec)) + +// Per nav tick: collect a finished search, then plan again when the corridor no longer fits. +[never_inline] +def public wto_route_update(navState, slotIdx : int; now : float; myPos, goal : float3; var slot : WtoBotSlot&) + assume rt = slot.route + if rt.pending + wto_route_poll(slotIdx, now, myPos, slot) + if rt.pending && wto_xz_dist_sq(rt.pendingGoal, goal) <= wto_sq(WTO_AI_PF_REPLAN_GOAL_MOVE_M) + return + if wto_route_needs_plan(now, goal, slot) + wto_route_request(navState, slotIdx, now, myPos, goal, slot) + +// Bots whose corridor ahead passes near a new obstacle (wreck, rubble) plan again next tick. +[never_inline] +def public wto_route_note_obstacle(pos : float3; radiusM : float; var bots : WtoBotSlot[64]&) + let reachSq = wto_sq(radiusM + 4.0) + for i in range(WTO_MAX_BOTS) + assume rt = bots[i].route + if !bots[i].used || rt.corridorLen < 2 + continue + let last = min(rt.corridorLen - 2, rt.segIdx + 8) + for k in range(rt.segIdx, last + 1) + var t = 0.0 + if wto_poly_seg_closest(rt.corridor[k], rt.corridor[k + 1], pos, t) <= reachSq + rt.replanRequested = true + break + +// A vehicle died at `pos`: later path searches route around its wreck, nearby bots plan again. +[never_inline] +def public wto_route_report_wreck(navState : int; now : float; pos : float3; var bots : WtoBotSlot[64]&) + if navState != WTO_NAVMESH_LOADED + return + wto_navq_add_dynamic(pos, WTO_AI_PF_WRECK_RADIUS_M, WTO_AI_PF_WRECK_COST_MUL, now + WTO_AI_PF_WRECK_TTL_SEC) + wto_route_note_obstacle(pos, WTO_AI_PF_WRECK_RADIUS_M, bots) \ No newline at end of file diff --git a/game-ai/ground/wto_ai_runtime.das b/game-ai/ground/wto_ai_runtime.das index 22f0cc4..c4912f6 100644 --- a/game-ai/ground/wto_ai_runtime.das +++ b/game-ai/ground/wto_ai_runtime.das @@ -24,13 +24,16 @@ require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_order_common require %appGame.wtoai.wto_ai_combat_types_common require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_nav_types_common require %appGame.wtoai.wto_ai_specs_common require %appGame.wtoai.wto_ai_world_common require %appGame.wtoai.wto_ai_crowd_common require %appGame.wtoai.wto_ai_lanes_common +require %appGame.wtoai.wto_ai_lanes_build_common require %appGame.wtoai.wto_ai_commander_common require %appGame.wtoai.wto_ai_perceive_common require %appGame.wtoai.wto_ai_tactics_common +require %appGame.wtoai.wto_ai_route_common require %appGame.wtoai.wto_ai_nav_common require %appGame.wtoai.wto_ai_navmesh_common require %appGame.wtoai.wto_ai_drive_common @@ -48,8 +51,7 @@ var private g_cmd_dirty : bool = true var private g_last_zone_ver : int = -1 var private g_fire_budget : int = 0 var private g_next_diag_at : float = 0.0 -var private g_navmesh_state : int = 0 -var private g_navmesh_tested : bool = false +var private @safe_when_uninitialized g_navmesh : WtoNavmeshBattle def private wto_any_layer_active() : bool return WTO_AI_ENABLED && (WTO_AI_LAYER_MACRO || WTO_AI_LAYER_TACTICS || WTO_AI_LAYER_NAVIGATION || WTO_AI_LAYER_FIRE_CONTROL) @@ -69,7 +71,7 @@ def private wto_reset_runtime() g_cmd_dirty = true g_last_zone_ver = -1 g_next_diag_at = 0.0 - wto_navmesh_battle_reset(g_navmesh_state, g_navmesh_tested) + wto_navmesh_battle_reset(g_navmesh) for i in range(WTO_MAX_BOTS) if g_bots[i].drive.routeBOwned wto_drive_request_control(g_bots[i].eid, 0) @@ -84,6 +86,20 @@ def private wto_find_slot(eid : EntityId) : int return i return -1 +[never_inline] +def private wto_forget_unit(eid : EntityId) + let idx = wto_find_slot(eid) + if idx >= 0 + if g_bots[idx].drive.routeBOwned + wto_drive_request_control(eid, 0) + g_bots[idx] = WtoBotSlot() + g_cmd_dirty = true + for i in range(WTO_MAX_BOTS) + if g_bots[i].used && g_bots[i].tactics.engageTargetEid == eid + g_bots[i].tactics.engageShotsNoEffect = 0 + g_bots[i].tactics.engageNoShotHalts = 0 + g_bots[i].tactics.engageTotalHaltSec = 0.0 + [never_inline] def private wto_acquire_slot(eid : EntityId; army : int; now : float) : int let cap = min(WTO_MAX_BOTS, WTO_AI_MAX_TRACKED_BOTS) @@ -124,6 +140,12 @@ def wto_ai_mission_reset_es(evt : Event) wto_reset_runtime() wto_drive_announce_script_ready() +// Battle loading: read the navigation pack in the background before the first world tick. +[es(tag=server, on_event=EventEcsMissionLoaded)] +def wto_ai_mission_loaded_es(evt : Event) + if wto_any_layer_active() && WTO_AI_LAYER_NAVIGATION + wto_navmesh_prefetch() + [es(tag=server)] def wto_ai_zone_captured_es(evt : EventZoneCaptured) if !wto_any_layer_active() @@ -136,32 +158,14 @@ def wto_ai_zone_captured_es(evt : EventZoneCaptured) def wto_ai_unit_dead_es(evt : Event; eid : EntityId; unit__ref : UnitRef) let u = unit__ref.unit if u != null && as_gm(u) != null && (int(u.army) == 1 || int(u.army) == 2) - wto_world_record_death(g_world, eid, int(u.army), u.pos, float(get_app().usefulTotalTime)) - let idx = wto_find_slot(eid) - if idx >= 0 - if g_bots[idx].drive.routeBOwned - wto_drive_request_control(eid, 0) - g_bots[idx] = WtoBotSlot() - g_cmd_dirty = true - for i in range(WTO_MAX_BOTS) - if g_bots[i].used && g_bots[i].tactics.engageTargetEid == eid - g_bots[i].tactics.engageShotsNoEffect = 0 - g_bots[i].tactics.engageNoShotHalts = 0 - g_bots[i].tactics.engageTotalHaltSec = 0.0 + let now = float(get_app().usefulTotalTime) + wto_world_record_death(g_world, eid, int(u.army), u.pos, now) + wto_route_report_wreck(g_navmesh.state, now, u.pos, g_bots) + wto_forget_unit(eid) [es(tag=server, on_disappear, on_event=EventUnitRespawn)] def wto_ai_unit_cleanup_es(evt : Event; eid : EntityId) - let idx = wto_find_slot(eid) - if idx >= 0 - if g_bots[idx].drive.routeBOwned - wto_drive_request_control(eid, 0) - g_bots[idx] = WtoBotSlot() - g_cmd_dirty = true - for i in range(WTO_MAX_BOTS) - if g_bots[i].used && g_bots[i].tactics.engageTargetEid == eid - g_bots[i].tactics.engageShotsNoEffect = 0 - g_bots[i].tactics.engageNoShotHalts = 0 - g_bots[i].tactics.engageTotalHaltSec = 0.0 + wto_forget_unit(eid) [es(tag=server)] def wto_ai_unit_damage_es(evt : EventUnitDamage; eid : EntityId; unit__ref : UnitRef) @@ -212,7 +216,8 @@ def wto_ai_world_tick_es(act : UpdateStageInfoAct) print("WTO_AI|RUNTIME_READY\n") wto_world_refresh(now, g_world) if WTO_AI_LAYER_NAVIGATION - wto_navmesh_battle_tick(g_world, g_navmesh_state, g_navmesh_tested) + wto_navmesh_battle_tick(g_world, now, g_navmesh) + g_lanes.navState = g_navmesh.state wto_crowd_update_all(g_world, g_bots, g_crowd) let zoneChanged = g_world.zoneVersion != g_last_zone_ver if zoneChanged @@ -226,25 +231,11 @@ def wto_ai_world_tick_es(act : UpdateStageInfoAct) wto_commander_update_all(g_world, now, zoneChanged, g_lanes, g_bots) elif WTO_AI_LAYER_MACRO && now >= g_next_rally_at g_next_rally_at = now + 1.0 - wto_lanes_update_rallies(g_world, 1, now, g_lanes, g_bots) - wto_lanes_update_rallies(g_world, 2, now, g_lanes, g_bots) - for i in range(WTO_MAX_BOTS) - assume b = g_bots[i] - if b.used && b.order.valid && b.order.rallyHold && b.order.capIndex >= 0 - let sk = wto_lanes_sub_key(b.army, b.order.capIndex, b.order.laneId) - if g_lanes.rallyReleased[sk] - b.order.rallyHold = false - if b.order.role == WTO_CMD_FLANK && b.order.laneId > 0 - let ck = wto_lanes_cap_key(b.army, b.order.capIndex) - b.order.routeRelayValid = g_lanes.flankValid[ck * 2 + b.order.laneId - 1] - b.order.routeRelayPos = g_lanes.flankRelay[ck * 2 + b.order.laneId - 1] - else - b.order.routeRelayValid = false + wto_lanes_tick_rallies(g_world, now, g_lanes, g_bots) if WTO_AI_DIAG_TELEMETRY && now >= g_next_diag_at g_next_diag_at = now + WTO_AI_DIAG_INTERVAL_SEC wto_diag_log_telemetry(g_world, now, g_bots, g_crowd) - if g_navmesh_state == WTO_NAVMESH_LOADED - wto_navmesh_log_stats() + wto_navmesh_log_stats(g_navmesh) [es(tag=server, no_order)] def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&; @@ -273,15 +264,15 @@ def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : wto_perceive_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], slot) wto_tactics_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], unit.isBurn, repair_system_remaining_repair_time, slot, g_crowd) // A failed pack with navEngine.allowFallback off leaves every bot standing for the battle. - if now >= slot.nextNavAt && g_navmesh_state != WTO_NAVMESH_FAILED + if now >= slot.nextNavAt && g_navmesh.state != WTO_NAVMESH_FAILED slot.nextNavAt = now + WTO_AI_NAV_TICK_SEC - wto_nav_update(g_world, now, unit.pos, unit.unitTm[0], slot) + wto_nav_update(g_world, g_navmesh.state, idx, now, unit.pos, unit.unitTm[0], slot) wto_fire_update(g_world, unit, now, act.dt, slot, g_fire_budget) [es(tag=server, after=wto_ai_pipeline_es)] def wto_ai_phys_tick_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&; unit__missionName : string; var vehicle_net_phys : VehiclePhysActor&) - if !wto_any_layer_active() || !WTO_AI_LAYER_NAVIGATION || WTO_AI_NAV_DRIVE_MODE != "vehicle_phys" || g_navmesh_state == WTO_NAVMESH_FAILED + if !wto_any_layer_active() || !WTO_AI_LAYER_NAVIGATION || WTO_AI_NAV_DRIVE_MODE != "vehicle_phys" || g_navmesh.state == WTO_NAVMESH_FAILED return var unit = unit__ref.unit if unit == null || !unit.isAlive || unit.isDelayed || unit.isHumanPlayer || vehicle_net_phys.physEdit == null diff --git a/game-ai/ground/wto_ai_stockpath_common.das b/game-ai/ground/wto_ai_stockpath_common.das new file mode 100644 index 0000000..146805c --- /dev/null +++ b/game-ai/ground/wto_ai_stockpath_common.das @@ -0,0 +1,53 @@ +// Path source for battles without a baked navigation pack (navEngine fallback): the level's stock +// road navmesh, thinned to direction changes. Used only when the battle decided on the fallback. +options indenting = 2 +options no_global_heap = true +module wto_ai_stockpath_common shared + +require ecs +require math +require pathfinder +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common + +[never_inline] +def private wto_stock_project(navIdx : int; var pt : float3&) : bool + if project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(WTO_AI_NAVMESH_SNAP_M, 64.0, WTO_AI_NAVMESH_SNAP_M)) + return true + return project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(WTO_AI_NAVMESH_GOAL_SNAP_M, 130.0, WTO_AI_NAVMESH_GOAL_SNAP_M)) + +// Stock road path from start to goal as at most 96 corners; false when the stock mesh has none. +[never_inline] +def public wto_stock_path(start, goal : float3; var pts : float3[96]&; var count : int&) : bool + count = 0 + let navIdx = pathfinder_is_loaded_ex(1) ? 1 : (pathfinder_is_loaded_ex(0) ? 0 : -1) + if navIdx < 0 + return false + var sPt = start + var gPt = goal + if !wto_stock_project(navIdx, sPt) || !wto_stock_project(navIdx, gPt) + return false + let maxKeep = 95 + find_path_ex(navIdx, sPt, gPt, float3(32.0, 48.0, 32.0), 9.0, 2.5, null) <| $(path : array#) + let total = length(path) + if total <= 0 + return + pts[0] = path[0] + count = 1 + let minStepSq = total > maxKeep ? wto_sq(max(12.0, float(total) * 9.0 / float(maxKeep))) : 0.0 + for i in range(1, total) + if count >= maxKeep + break + let prev = pts[count - 1] + var isCorner = false + if i + 1 < total + let d0 = wto_xz_normalize(path[i] - prev, float3(1.0, 0.0, 0.0)) + let d1 = wto_xz_normalize(path[i + 1] - path[i], d0) + isCorner = dot(d0, d1) < 0.86 + if i == total - 1 || isCorner || wto_xz_dist_sq(prev, path[i]) >= minStepSq + pts[count] = path[i] + count++ + if count < maxKeep && wto_xz_dist_sq(pts[count - 1], path[total - 1]) > 9.0 + pts[count] = path[total - 1] + count++ + return count >= 2 diff --git a/game-ai/ground/wto_ai_tactics_actions_common.das b/game-ai/ground/wto_ai_tactics_actions_common.das index 39f772f..14c4f52 100644 --- a/game-ai/ground/wto_ai_tactics_actions_common.das +++ b/game-ai/ground/wto_ai_tactics_actions_common.das @@ -12,6 +12,7 @@ require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_order_common require %appGame.wtoai.wto_ai_combat_types_common require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_nav_types_common require %appGame.wtoai.wto_ai_terrain_common require %appGame.wtoai.wto_ai_cover_common diff --git a/game-ai/ground/wto_ai_tactics_common.das b/game-ai/ground/wto_ai_tactics_common.das index 29faf95..6e684c0 100644 --- a/game-ai/ground/wto_ai_tactics_common.das +++ b/game-ai/ground/wto_ai_tactics_common.das @@ -13,6 +13,7 @@ require %appGame.wtoai.wto_ai_order_common require %appGame.wtoai.wto_ai_combat_types_common require %appGame.wtoai.wto_ai_fire_speed_common require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_nav_types_common require %appGame.wtoai.wto_ai_terrain_common require %appGame.wtoai.wto_ai_crowd_common require %appGame.wtoai.wto_ai_cover_common diff --git a/game-ai/ground/wto_ai_types_common.das b/game-ai/ground/wto_ai_types_common.das index 89e117d..d388ff8 100644 --- a/game-ai/ground/wto_ai_types_common.das +++ b/game-ai/ground/wto_ai_types_common.das @@ -6,12 +6,12 @@ module wto_ai_types_common shared require ecs require %appGame.wtoai.wto_ai_order_common require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_nav_types_common let public WTO_MAX_BOTS = 64 let public WTO_MAX_UNITS = 96 let public WTO_MAX_WRECKS = 64 let public WTO_MAX_CAPS = 8 -let public WTO_MAX_PATH_PTS = 32 let public WTO_MAX_DEATHS = 32 let public WTO_MAX_JAMS = 24 let public WTO_MAX_RADIO = 24 @@ -200,42 +200,6 @@ struct public WtoTacticsState disperseGoal : float3 = float3(0.0, 0.0, 0.0) disperseUntil : float = -100.0 -[safe_when_uninitialized] -struct public WtoRouteState - corridor : float3[32] - corridorLen : int = 0 - corridorIdx : int = 0 - corridorGoal : float3 = float3(0.0, 0.0, 0.0) - nextReplanAt : float = -100.0 - nextShortcutAt : float = -100.0 - wingInit : bool = false - wingSign : int = 0 - laneOffsetM : float = 0.0 - wingCapIdx : int = -2 - wingRelayPos : float3 = float3(0.0, 0.0, 0.0) - wingRelayValid : bool = false - shortcutPos : float3 = float3(0.0, 0.0, 0.0) - shortcutValid : bool = false - detourPos : float3 = float3(0.0, 0.0, 0.0) - detourValid : bool = false - detourUntil : float = -100.0 - detourCount : int = 0 - lastStartOk : bool = false - lastGoalOk : bool = false - -[safe_when_uninitialized] -struct public WtoNavState - steerDir : float3 = float3(1.0, 0.0, 0.0) - frontClearM : float = 30.0 - rearClearM : float = 16.0 - cliffAhead : bool = false - stuckOrigin : float3 = float3(0.0, 0.0, 0.0) - stuckCheckAt : float = -100.0 - reverseAnchor : float3 = float3(0.0, 0.0, 0.0) - reverseUntil : float = -100.0 - reverseCount : int = 0 - ridgeWithdrawEvents : int = 0 - [safe_when_uninitialized] struct public WtoDriveCmd valid : bool = false diff --git a/game-ai/ground/wto_ai_unstick_common.das b/game-ai/ground/wto_ai_unstick_common.das new file mode 100644 index 0000000..b9c4249 --- /dev/null +++ b/game-ai/ground/wto_ai_unstick_common.das @@ -0,0 +1,115 @@ +// Deterministic three-level unstick. A bot that wants to move but makes no progress within +// stuckWindowSec backs up along the corridor it came by (level 1). Stuck again soon after, it also +// marks the spot ahead as a jam that path searches avoid and plans again (level 2). After +// unstickMaxAttempts without real progress it logs the place, marks it harder and gives its order +// back to the commander (level 3). +options indenting = 2 +options no_global_heap = true +module wto_ai_unstick_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_nav_types_common +require %appGame.wtoai.wto_ai_world_common +require %appGame.wtoai.wto_ai_polyline_common +require %appGame.wtoai.wto_ai_navquery_common +require %appGame.wtoai.wto_ai_navmesh_common +require %appGame.wtoai.wto_ai_follow_common + +// Where to back up to: unstickReverseM back along the corridor (or straight back), cut short +// where the mesh ends; false when there is no room behind. +[never_inline] +def private wto_unstick_reverse_target(navState : int; myPos, hullFwd : float3; slot : WtoBotSlot const&; + var target : float3&) : bool + if slot.nav.rearClearM < 2.5 + return false + assume rt = slot.route + let straightBack = myPos - hullFwd * WTO_AI_PF_UNSTICK_REV_M + target = rt.corridorLen >= 2 ? wto_poly_walk_back(rt.corridor, rt.corridorLen, rt.segIdx, rt.segT, WTO_AI_PF_UNSTICK_REV_M) : straightBack + if wto_xz_dist_sq(myPos, target) < 4.0 + target = straightBack + if navState != WTO_NAVMESH_LOADED || rt.tier < 0 + return true + var frac = 0.0 + if wto_navq_raycast(rt.tier, rt.filter, myPos, target, frac) != 0 + return true + if frac * sqrt(wto_xz_dist_sq(myPos, target)) < 2.0 + return false + target = lerp(myPos, target, frac * 0.9) + return true + +[never_inline] +def private wto_unstick_start_reverse(navState : int; now : float; myPos, hullFwd : float3; var slot : WtoBotSlot&) + var target = myPos + if !wto_unstick_reverse_target(navState, myPos, hullFwd, slot, target) + return + slot.nav.reverseTarget = target + slot.nav.reverseUntil = now + WTO_AI_PF_UNSTICK_REV_SEC + slot.nav.reverseCount++ + +[never_inline] +def private wto_unstick_mark(var world : WtoWorldSnap&; navState : int; now : float; pos : float3; radiusM, costMul : float) + wto_world_record_jam(world, pos, now) + if navState == WTO_NAVMESH_LOADED + wto_navq_add_dynamic(pos, radiusM, costMul, now + WTO_AI_PF_JAM_TTL_SEC) + +[never_inline] +def private wto_unstick_give_up(var world : WtoWorldSnap&; navState : int; now : float; myPos, ahead : float3; + var slot : WtoBotSlot&) + print("WTO_AI|NAV_UNREACHABLE|eid={uint(slot.eid)}|tier={slot.route.tier}|pos={myPos}|goal={slot.route.goal}|attempts={slot.nav.unstickAttempts}\n") + wto_unstick_mark(world, navState, now, ahead, WTO_AI_PF_JAM_RADIUS_M * 1.5, WTO_AI_PF_JAM_COST_MUL * 2.0) + slot.order.expiresAt = now + slot.nav.unreachableEvents++ + slot.nav.unstickAttempts = 0 + slot.nav.unstickLevel = 0 + +// Backing up after being stuck; true while the manoeuvre runs (the drive command is set). +[never_inline] +def public wto_unstick_reversing(now : float; myPos : float3; var slot : WtoBotSlot&) : bool + assume nav = slot.nav + if now >= nav.reverseUntil + return false + if wto_xz_dist_sq(myPos, nav.reverseTarget) < 1.0 || nav.rearClearM < 2.1 + nav.reverseUntil = -100.0 + nav.stuckCheckAt = -100.0 + return false + let dir = wto_xz_normalize(nav.reverseTarget - myPos, -nav.steerDir) + nav.steerDir = dir + wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_REVERSE, nav.reverseTarget, dir, max(2.0, slot.spec.vMaxRev), nav.frontClearM, nav.rearClearM) + return true + +// Per nav tick while following: detects no progress and escalates through the three levels. +[never_inline] +def public wto_unstick_watch(var world : WtoWorldSnap&; navState : int; now : float; myPos, hullFwd, ahead : float3; + movingIntent : bool; var slot : WtoBotSlot&) + assume nav = slot.nav + if !movingIntent || nav.stuckCheckAt < -50.0 + nav.stuckOrigin = myPos + nav.stuckCheckAt = now + WTO_AI_PF_STUCK_WINDOW_SEC + return + if now < nav.stuckCheckAt + return + let moved = sqrt(wto_xz_dist_sq(myPos, nav.stuckOrigin)) + nav.stuckOrigin = myPos + nav.stuckCheckAt = now + WTO_AI_PF_STUCK_WINDOW_SEC + if moved >= WTO_AI_PF_STUCK_MIN_PROGRESS_M + if wto_xz_dist_sq(myPos, nav.unstickAnchor) > 144.0 + nav.unstickAttempts = 0 + nav.unstickLevel = 0 + return + nav.unstickAttempts++ + nav.unstickEvents++ + nav.unstickLevel = (now - nav.lastUnstickAt) <= WTO_AI_PF_UNSTICK_REPEAT_SEC ? min(nav.unstickLevel + 1, 2) : 1 + nav.lastUnstickAt = now + nav.unstickAnchor = myPos + print("WTO_AI|NAV_STUCK|eid={uint(slot.eid)}|level={nav.unstickLevel}|attempt={nav.unstickAttempts}|pos={myPos}\n") + if nav.unstickAttempts >= WTO_AI_PF_UNSTICK_MAX_ATTEMPTS + wto_unstick_give_up(world, navState, now, myPos, ahead, slot) + slot.route.replanRequested = true + elif nav.unstickLevel >= 2 + wto_unstick_mark(world, navState, now, ahead, WTO_AI_PF_JAM_RADIUS_M, WTO_AI_PF_JAM_COST_MUL) + slot.route.replanRequested = true + wto_unstick_start_reverse(navState, now, myPos, hullFwd, slot) diff --git a/native/wto-nav/wto_nav_internal.h b/native/wto-nav/wto_nav_internal.h new file mode 100644 index 0000000..0cdae48 --- /dev/null +++ b/native/wto-nav/wto_nav_internal.h @@ -0,0 +1,81 @@ +/* + * State shared by the navigation engine's translation units (wto_nav_runtime.cpp: packs and + * loading; wto_nav_paths.cpp: queued sliced path searches; wto_nav_queries.cpp: point queries and + * dynamic costs). Everything below is guarded by g_lock unless noted. + */ +#pragma once + +#include "wto_nav_runtime.h" +#include "wto_nav_format.h" + +#include "DetourCommon.h" +#include "DetourNavMesh.h" +#include "DetourNavMeshQuery.h" + +#include + +#include + +#ifndef DT_VIRTUAL_QUERYFILTER +#error "Detour must be built with DT_VIRTUAL_QUERYFILTER for the chokepoint and dynamic cost filter" +#endif + +namespace wtonav { + +constexpr int kPathSearchNodes = 32768; /* Node pool of the sliced path search, per tier */ +constexpr int kPointSearchNodes = 2048; /* Node pool of point queries (wall distance) */ +constexpr int kMaxPathPolys = 4096; + +/* A circle that multiplies the cost of every edge whose midpoint lies inside it. */ +struct DynamicCost { + float pos[3]; + float radius; + float mul; + float until; +}; + +extern DynamicCost g_dynamic[WTO_NAV_RT_MAX_DYNAMIC]; +extern uint32_t g_dynamic_count; + +/* Area costs per WtoPolyArea, times the chokepoint multiplier and live dynamic costs. */ +class QueryFilter : public dtQueryFilter { +public: + float chokepointMul = 1.0f; + + float getCost(const float *pa, const float *pb, + const dtPolyRef, const dtMeshTile *, const dtPoly *, + const dtPolyRef, const dtMeshTile *, const dtPoly *curPoly, + const dtPolyRef, const dtMeshTile *, const dtPoly *) const override; +}; + +struct Pack { + float heightSpan = 0.0f; /* Vertical extent of the mesh bounds */ + dtNavMesh *meshes[WTO_NAV_TIER_COUNT] = {}; + dtNavMeshQuery *pathQueries[WTO_NAV_TIER_COUNT] = {}; /* Owned by the sliced path search */ + dtNavMeshQuery *pointQueries[WTO_NAV_TIER_COUNT] = {}; /* Snapping, raycasts, wall distance */ + std::vector covers; + std::vector tactical; +}; + +extern SRWLOCK g_lock; +extern Pack *g_pack; +extern QueryFilter g_filters[WTO_NAV_RT_FILTER_COUNT]; +extern WtoNavStats g_stats; + +double now_micros(); + +/* + * Nearest polygon within `snap` metres; mission points (spawn and capture zone centres) carry + * heights that are not on the ground, so a miss is retried over the mesh's whole height range, + * still within `snap` horizontally. + */ +bool snap_to_mesh(const dtNavMeshQuery *query, const dtQueryFilter &filter, float snap, float height_span, + const float point[3], dtPolyRef *ref, float nearest[3]); + +/* Called with g_lock held whenever the loaded pack changes. */ +void paths_reset_locked(); +void dynamic_reset_locked(); +void dynamic_expire_locked(float now); +uint32_t paths_pending_locked(); + +} // namespace wtonav diff --git a/native/wto-nav/wto_nav_paths.cpp b/native/wto-nav/wto_nav_paths.cpp new file mode 100644 index 0000000..4c76d3a --- /dev/null +++ b/native/wto-nav/wto_nav_paths.cpp @@ -0,0 +1,246 @@ +/* + * Queued path searches (wto_nav_runtime.h): every slot holds at most one request. Requests are + * searched one at a time, oldest first, with Detour's sliced search; wto_nav_pump advances the + * search in small iteration chunks until its per-frame time budget is spent, so one long path + * across a 4 km map spreads over several frames instead of stalling one. + */ +#include "wto_nav_internal.h" + +#include + +namespace wtonav { +namespace { + +constexpr int kIterChunk = 64; /* Detour node expansions between budget checks */ + +enum class JobState : uint8_t { Empty, Queued, Running, Done }; + +struct PathJob { + uint32_t ticket; + JobState state; + uint32_t tier; + uint32_t filter; + dtPolyRef startRef; + dtPolyRef goalRef; + float startPt[3]; + float goalPt[3]; + double searchMicros; + uint32_t frames; + uint32_t lastPump; + WtoNavPathResult result; + float corners[WTO_NAV_RT_MAX_CORNERS * 3]; +}; + +PathJob g_jobs[WTO_NAV_RT_PATH_SLOTS]; +uint32_t g_next_ticket = 1; +uint32_t g_pump_serial; +int g_active = -1; /* Slot whose search owns its tier's path query */ +dtPolyRef g_poly_path[kMaxPathPolys]; + +void finish(PathJob &job, WtoNavPathStatus status) +{ + job.state = JobState::Done; + job.result.status = status; + if (g_pack == nullptr) + return; + g_stats.queries++; + if (status != WTO_NAV_PATH_FULL) + g_stats.failures++; + g_stats.totalMicros += job.searchMicros; + if (job.searchMicros > g_stats.maxMicros) + g_stats.maxMicros = job.searchMicros; + if (job.frames > g_stats.maxFrames) + g_stats.maxFrames = job.frames; +} + +/* Snaps start and goal; on success the job is queued, otherwise it is finished. */ +void prepare(PathJob &job, const WtoNavPathRequest &req) +{ + if (g_pack == nullptr || req.tier >= WTO_NAV_TIER_COUNT || req.filter >= WTO_NAV_RT_FILTER_COUNT || !(req.snapM > 0.0f)) { + finish(job, WTO_NAV_PATH_FAILED); + return; + } + const dtNavMeshQuery *query = g_pack->pointQueries[req.tier]; + const QueryFilter &filter = g_filters[req.filter]; + if (!snap_to_mesh(query, filter, req.snapM, g_pack->heightSpan, req.start, &job.startRef, job.startPt)) { + finish(job, WTO_NAV_PATH_NO_START); + return; + } + if (!snap_to_mesh(query, filter, req.snapM, g_pack->heightSpan, req.goal, &job.goalRef, job.goalPt)) { + if (!(req.goalSnapM > req.snapM) || + !snap_to_mesh(query, filter, req.goalSnapM, g_pack->heightSpan, req.goal, &job.goalRef, job.goalPt)) { + finish(job, WTO_NAV_PATH_NO_GOAL); + return; + } + job.result.goalMoved = 1; + } + job.state = JobState::Queued; +} + +int next_queued() +{ + int best = -1; + for (int i = 0; i < WTO_NAV_RT_PATH_SLOTS; i++) { + if (g_jobs[i].state == JobState::Queued && (best < 0 || g_jobs[i].ticket < g_jobs[best].ticket)) + best = i; + } + return best; +} + +/* Turns a finished polygon corridor into straight-path corners. */ +void finalize(PathJob &job, dtNavMeshQuery *query) +{ + int count = 0; + dtStatus status = query->finalizeSlicedFindPath(g_poly_path, &count, kMaxPathPolys); + if (dtStatusFailed(status) || count == 0) { + finish(job, WTO_NAV_PATH_FAILED); + return; + } + const bool partial = dtStatusDetail(status, DT_PARTIAL_RESULT) || g_poly_path[count - 1] != job.goalRef; + float goal[3]; + dtVcopy(goal, job.goalPt); + if (partial && dtStatusFailed(query->closestPointOnPoly(g_poly_path[count - 1], job.goalPt, goal, nullptr))) { + finish(job, WTO_NAV_PATH_FAILED); + return; + } + int corners = 0; + status = query->findStraightPath(job.startPt, goal, g_poly_path, count, job.corners, nullptr, nullptr, + &corners, WTO_NAV_RT_MAX_CORNERS, 0); + if (dtStatusFailed(status) || corners == 0) { + finish(job, WTO_NAV_PATH_FAILED); + return; + } + float length = 0.0f; + for (int i = 1; i < corners; i++) + length += dtVdist(job.corners + (i - 1) * 3, job.corners + i * 3); + job.result.count = corners; + job.result.lengthM = length; + job.result.truncated = dtStatusDetail(status, DT_BUFFER_TOO_SMALL) ? 1 : 0; + finish(job, partial ? WTO_NAV_PATH_PARTIAL : WTO_NAV_PATH_FULL); +} + +/* Starts the oldest queued search; false when nothing is left to search. */ +bool start_next() +{ + for (;;) { + const int slot = next_queued(); + if (slot < 0) + return false; + PathJob &job = g_jobs[slot]; + dtNavMeshQuery *query = g_pack->pathQueries[job.tier]; + if (dtStatusFailed(query->initSlicedFindPath(job.startRef, job.goalRef, job.startPt, job.goalPt, + &g_filters[job.filter], 0))) { + finish(job, WTO_NAV_PATH_FAILED); + continue; + } + job.state = JobState::Running; + g_active = slot; + return true; + } +} + +} // namespace + +void paths_reset_locked() +{ + memset(g_jobs, 0, sizeof(g_jobs)); + g_active = -1; +} + +uint32_t paths_pending_locked() +{ + uint32_t pending = 0; + for (const PathJob &job : g_jobs) + pending += job.state == JobState::Queued || job.state == JobState::Running; + return pending; +} + +} // namespace wtonav + +using namespace wtonav; + +extern "C" uint32_t wto_nav_path_request(uint32_t slot, const WtoNavPathRequest *request) +{ + if (slot >= WTO_NAV_RT_PATH_SLOTS || request == nullptr) + return 0; + AcquireSRWLockExclusive(&g_lock); + PathJob &job = g_jobs[slot]; + if (g_active == (int)slot) + g_active = -1; /* The next initSlicedFindPath discards the abandoned search */ + memset(&job, 0, sizeof(job)); + if (g_next_ticket == 0) + g_next_ticket = 1; + job.ticket = g_next_ticket++; + job.tier = request->tier; + job.filter = request->filter; + prepare(job, *request); + const uint32_t ticket = job.ticket; + ReleaseSRWLockExclusive(&g_lock); + return ticket; +} + +extern "C" void wto_nav_path_result(uint32_t slot, uint32_t ticket, float *points, int max_points, WtoNavPathResult *result) +{ + memset(result, 0, sizeof(*result)); + result->status = WTO_NAV_PATH_STALE; + if (slot >= WTO_NAV_RT_PATH_SLOTS || ticket == 0) + return; + AcquireSRWLockShared(&g_lock); + const PathJob &job = g_jobs[slot]; + if (job.ticket == ticket) { + if (job.state == JobState::Queued || job.state == JobState::Running) { + result->status = WTO_NAV_PATH_PENDING; + } else if (job.state == JobState::Done) { + *result = job.result; + if (result->count > max_points) + result->count = max_points < 0 ? 0 : max_points; + if (points != nullptr && result->count > 0) + memcpy(points, job.corners, sizeof(float) * 3 * (size_t)result->count); + } + } + ReleaseSRWLockShared(&g_lock); +} + +extern "C" void wto_nav_pump(double budget_us, float now) +{ + AcquireSRWLockExclusive(&g_lock); + const double began = now_micros(); + dynamic_expire_locked(now); + g_pump_serial++; + if (g_pack == nullptr) { + for (PathJob &job : g_jobs) { + if (job.state == JobState::Queued || job.state == JobState::Running) + finish(job, WTO_NAV_PATH_FAILED); + } + g_active = -1; + ReleaseSRWLockExclusive(&g_lock); + return; + } + for (;;) { + if (g_active < 0 && !start_next()) + break; + PathJob &job = g_jobs[g_active]; + dtNavMeshQuery *query = g_pack->pathQueries[job.tier]; + if (job.lastPump != g_pump_serial) { + job.lastPump = g_pump_serial; + job.frames++; + } + const double chunk_began = now_micros(); + int done = 0; + const dtStatus status = query->updateSlicedFindPath(kIterChunk, &done); + job.searchMicros += now_micros() - chunk_began; + if (dtStatusFailed(status)) { + finish(job, WTO_NAV_PATH_FAILED); + g_active = -1; + } else if (!dtStatusInProgress(status)) { + finalize(job, query); + g_active = -1; + } + if (now_micros() - began >= budget_us) + break; + } + const double spent = now_micros() - began; + if (spent > g_stats.pumpMaxMicros) + g_stats.pumpMaxMicros = spent; + ReleaseSRWLockExclusive(&g_lock); +} diff --git a/native/wto-nav/wto_nav_queries.cpp b/native/wto-nav/wto_nav_queries.cpp new file mode 100644 index 0000000..9518ff4 --- /dev/null +++ b/native/wto-nav/wto_nav_queries.cpp @@ -0,0 +1,164 @@ +/* + * Point queries on the loaded pack (wto_nav_runtime.h) for the ground AI's path follower: what + * lies under a vehicle (surface, flags, distance to the mesh edge), whether the mesh lets it go + * straight somewhere, the nearest walkable point, and dynamic cost circles (wrecks, jams, rubble) + * that later path searches route around. + */ +#include "wto_nav_internal.h" + +#include +#include + +namespace wtonav { + +DynamicCost g_dynamic[WTO_NAV_RT_MAX_DYNAMIC]; +uint32_t g_dynamic_count; + +void dynamic_reset_locked() +{ + g_dynamic_count = 0; +} + +void dynamic_expire_locked(float now) +{ + uint32_t kept = 0; + for (uint32_t i = 0; i < g_dynamic_count; i++) { + if (g_dynamic[i].until >= now) + g_dynamic[kept++] = g_dynamic[i]; + } + g_dynamic_count = kept; +} + +namespace { + +bool valid_query(uint32_t tier, uint32_t filter) +{ + return g_pack != nullptr && tier < WTO_NAV_TIER_COUNT && filter < WTO_NAV_RT_FILTER_COUNT; +} + +/* An existing circle overlapping most of the new one, or -1. */ +int find_dynamic(const float pos[3], float radius) +{ + for (uint32_t i = 0; i < g_dynamic_count; i++) { + const float dx = g_dynamic[i].pos[0] - pos[0], dz = g_dynamic[i].pos[2] - pos[2]; + const float reach = (g_dynamic[i].radius > radius ? g_dynamic[i].radius : radius) * 0.5f; + if (dx * dx + dz * dz <= reach * reach) + return (int)i; + } + return -1; +} + +int soonest_dynamic() +{ + int best = 0; + for (uint32_t i = 1; i < g_dynamic_count; i++) { + if (g_dynamic[i].until < g_dynamic[best].until) + best = (int)i; + } + return best; +} + +} // namespace +} // namespace wtonav + +using namespace wtonav; + +extern "C" int wto_nav_probe(uint32_t tier, uint32_t filter, const float pos[3], float snap_m, float wall_radius_m, WtoNavProbe *probe) +{ + memset(probe, 0, sizeof(*probe)); + AcquireSRWLockExclusive(&g_lock); /* findDistanceToWall uses the query's node pool */ + if (!valid_query(tier, filter) || !(snap_m > 0.0f)) { + ReleaseSRWLockExclusive(&g_lock); + return 0; + } + g_stats.meshQueries++; + dtNavMeshQuery *query = g_pack->pointQueries[tier]; + const QueryFilter &qf = g_filters[filter]; + dtPolyRef ref = 0; + if (snap_to_mesh(query, qf, snap_m, g_pack->heightSpan, pos, &ref, probe->nearest)) { + const dtMeshTile *tile = nullptr; + const dtPoly *poly = nullptr; + probe->onMesh = 1; + probe->offsetM = dtVdist2D(pos, probe->nearest); + if (dtStatusSucceed(g_pack->meshes[tier]->getTileAndPolyByRef(ref, &tile, &poly))) { + probe->area = poly->getArea(); + probe->flags = poly->flags; + } + float hit_pos[3], hit_normal[3]; + float dist = wall_radius_m; + if (wall_radius_m > 0.0f && + dtStatusFailed(query->findDistanceToWall(ref, probe->nearest, wall_radius_m, &qf, &dist, hit_pos, hit_normal))) + dist = wall_radius_m; + probe->wallDistM = dist; + } + ReleaseSRWLockExclusive(&g_lock); + return 1; +} + +extern "C" int wto_nav_raycast(uint32_t tier, uint32_t filter, float snap_m, const float start[3], const float goal[3], + float *hit_frac, float hit[3]) +{ + *hit_frac = 0.0f; + dtVcopy(hit, start); + AcquireSRWLockShared(&g_lock); + if (!valid_query(tier, filter) || !(snap_m > 0.0f)) { + ReleaseSRWLockShared(&g_lock); + return -1; + } + InterlockedIncrement((volatile LONG *)&g_stats.meshQueries); + const dtNavMeshQuery *query = g_pack->pointQueries[tier]; + const QueryFilter &qf = g_filters[filter]; + dtPolyRef ref = 0; + float from[3]; + int clear = -1; + if (snap_to_mesh(query, qf, snap_m, g_pack->heightSpan, start, &ref, from)) { + float t = 0.0f, normal[3]; + dtPolyRef visited[64]; + int visited_count = 0; + if (dtStatusSucceed(query->raycast(ref, from, goal, &qf, &t, normal, visited, &visited_count, 64))) { + clear = t == FLT_MAX ? 1 : 0; + *hit_frac = t == FLT_MAX ? 1.0f : t; + dtVlerp(hit, from, goal, *hit_frac); + } + } + ReleaseSRWLockShared(&g_lock); + return clear; +} + +extern "C" int wto_nav_nearest(uint32_t tier, uint32_t filter, float radius_m, const float pos[3], float out[3]) +{ + int found = 0; + AcquireSRWLockShared(&g_lock); + if (valid_query(tier, filter) && radius_m > 0.0f) { + InterlockedIncrement((volatile LONG *)&g_stats.meshQueries); + dtPolyRef ref = 0; + found = snap_to_mesh(g_pack->pointQueries[tier], g_filters[filter], radius_m, g_pack->heightSpan, pos, &ref, out); + } + ReleaseSRWLockShared(&g_lock); + return found; +} + +extern "C" uint32_t wto_nav_add_dynamic(const float pos[3], float radius_m, float cost_mul, float until) +{ + if (!(radius_m > 0.0f) || !(cost_mul > 0.0f)) + return 0; + AcquireSRWLockExclusive(&g_lock); + int at = find_dynamic(pos, radius_m); + if (at >= 0) { + DynamicCost &d = g_dynamic[at]; + dtVcopy(d.pos, pos); + d.radius = d.radius > radius_m ? d.radius : radius_m; + d.mul = d.mul > cost_mul ? d.mul : cost_mul; + d.until = d.until > until ? d.until : until; + } else { + at = g_dynamic_count < WTO_NAV_RT_MAX_DYNAMIC ? (int)g_dynamic_count++ : soonest_dynamic(); + DynamicCost &d = g_dynamic[at]; + dtVcopy(d.pos, pos); + d.radius = radius_m; + d.mul = cost_mul; + d.until = until; + } + const uint32_t count = g_dynamic_count; + ReleaseSRWLockExclusive(&g_lock); + return count; +} diff --git a/native/wto-nav/wto_nav_runtime.cpp b/native/wto-nav/wto_nav_runtime.cpp index 43b5871..72c5f61 100644 --- a/native/wto-nav/wto_nav_runtime.cpp +++ b/native/wto-nav/wto_nav_runtime.cpp @@ -1,69 +1,49 @@ /* * In-game navigation engine (wto_nav_runtime.h): loads one `.wtonav` pack written by - * tools/navgen/bake into upstream Detour meshes and answers path queries for the ground AI. + * tools/navgen/bake into upstream Detour meshes, optionally on a background thread while the + * battle is still loading. Path searches live in wto_nav_paths.cpp, point queries and dynamic + * costs in wto_nav_queries.cpp. */ -#include "wto_nav_runtime.h" -#include "wto_nav_format.h" +#include "wto_nav_internal.h" #include "DetourAlloc.h" -#include "DetourCommon.h" -#include "DetourNavMesh.h" -#include "DetourNavMeshQuery.h" - -#include #include #include -#include +#include -#ifndef DT_VIRTUAL_QUERYFILTER -#error "Detour must be built with DT_VIRTUAL_QUERYFILTER for the chokepoint cost filter" -#endif +namespace wtonav { + +SRWLOCK g_lock = SRWLOCK_INIT; +Pack *g_pack; +QueryFilter g_filters[WTO_NAV_RT_FILTER_COUNT]; +WtoNavStats g_stats; namespace { -constexpr int kMaxSearchNodes = 32768; -constexpr int kMaxPathPolys = 4096; constexpr size_t kMaxPackBytes = 512u * 1024u * 1024u; constexpr size_t kMaxEverBytes = 64u * 1024u; constexpr int kMaxLevelBlocks = 4096; -/* Area costs per WtoPolyArea, times a multiplier on chokepoint polygons. */ -class WtoQueryFilter : public dtQueryFilter { -public: - float chokepointMul = 1.0f; - - float getCost(const float *pa, const float *pb, - const dtPolyRef, const dtMeshTile *, const dtPoly *, - const dtPolyRef, const dtMeshTile *, const dtPoly *curPoly, - const dtPolyRef, const dtMeshTile *, const dtPoly *) const override - { - float cost = dtVdist(pa, pb) * getAreaCost(curPoly->getArea()); - if (curPoly->flags & WTO_FLAG_CHOKEPOINT) - cost *= chokepointMul; - return cost; - } -}; - -struct Pack { - float heightSpan = 0.0f; /* Vertical extent of the mesh bounds */ - dtNavMesh *meshes[WTO_NAV_TIER_COUNT] = {}; - dtNavMeshQuery *queries[WTO_NAV_TIER_COUNT] = {}; - std::vector covers; - std::vector tactical; -}; - -SRWLOCK g_lock = SRWLOCK_INIT; -Pack *g_pack; -WtoQueryFilter g_filters[WTO_NAV_RT_FILTER_COUNT]; bool g_filters_ready; -WtoNavStats g_stats; + +/* A pack read on a background thread, waiting for wto_nav_load. Guarded by g_stage_lock. */ +struct Staged { + std::wstring packPath; + std::wstring levelPath; + HANDLE thread = nullptr; + Pack *pack = nullptr; + WtoNavLoadInfo info = {}; +}; + +SRWLOCK g_stage_lock = SRWLOCK_INIT; +Staged *g_staged; void init_filters_locked() { if (g_filters_ready) return; - for (WtoQueryFilter &filter : g_filters) { + for (QueryFilter &filter : g_filters) { filter.setIncludeFlags(WTO_FLAG_WALK); filter.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED); } @@ -75,7 +55,8 @@ void free_pack(Pack *pack) if (pack == nullptr) return; for (uint32_t t = 0; t < WTO_NAV_TIER_COUNT; t++) { - dtFreeNavMeshQuery(pack->queries[t]); + dtFreeNavMeshQuery(pack->pathQueries[t]); + dtFreeNavMeshQuery(pack->pointQueries[t]); dtFreeNavMesh(pack->meshes[t]); } delete pack; @@ -109,6 +90,15 @@ bool fits(const std::vector &data, uint64_t offset, uint64_t size) return offset <= data.size() && size <= data.size() - offset; } +bool init_queries(Pack *pack, uint32_t tier) +{ + pack->pathQueries[tier] = dtAllocNavMeshQuery(); + pack->pointQueries[tier] = dtAllocNavMeshQuery(); + return pack->pathQueries[tier] != nullptr && pack->pointQueries[tier] != nullptr && + dtStatusSucceed(pack->pathQueries[tier]->init(pack->meshes[tier], kPathSearchNodes)) && + dtStatusSucceed(pack->pointQueries[tier]->init(pack->meshes[tier], kPointSearchNodes)); +} + bool load_tier(const std::vector &data, const WtoNavHeader &hdr, uint32_t tier, Pack *pack, uint32_t *polys, char *detail, size_t detail_size) { uint64_t at = hdr.tierOffsets[tier]; @@ -156,8 +146,7 @@ bool load_tier(const std::vector &data, const WtoNavHeader &hdr, uint32 } *polys += (uint32_t)((const dtMeshHeader *)tile)->polyCount; } - pack->queries[tier] = dtAllocNavMeshQuery(); - if (pack->queries[tier] == nullptr || dtStatusFailed(pack->queries[tier]->init(pack->meshes[tier], kMaxSearchNodes))) { + if (!init_queries(pack, tier)) { snprintf(detail, detail_size, "tier %u query init failed", tier); return false; } @@ -204,11 +193,96 @@ Pack *parse_pack(const std::vector &data, WtoNavLoadInfo *info) return pack; } -/* - * Nearest polygon within `snap` metres; mission points (spawn and capture zone centres) carry - * heights that are not on the ground, so a miss is retried over the mesh's whole height range, - * still within `snap` horizontally. - */ +/* Reads and parses a pack plus the level fingerprint; runs on any thread, touches no globals. */ +Pack *read_pack(const wchar_t *pack_path, const wchar_t *level_path, WtoNavLoadInfo *info) +{ + const double began = now_micros(); + std::vector data; + Pack *pack = nullptr; + + memset(info, 0, sizeof(*info)); + if (level_path != nullptr && level_path[0] != L'\0') + info->fingerprintKnown = wto_nav_read_level_fingerprint(level_path, info->levelSha1); + if (read_file(pack_path, data, info)) { + pack = parse_pack(data, info); + info->result = pack != nullptr ? WTO_NAV_LOAD_OK : WTO_NAV_LOAD_CORRUPT; + } + if (pack != nullptr && info->fingerprintKnown) + info->fingerprintMatch = memcmp(info->packSha1, info->levelSha1, sizeof(info->packSha1)) == 0; + info->readMs = (now_micros() - began) / 1000.0; + return pack; +} + +DWORD WINAPI prefetch_main(void *arg) +{ + Staged *staged = (Staged *)arg; + staged->pack = read_pack(staged->packPath.c_str(), staged->levelPath.c_str(), &staged->info); + return 0; +} + +/* Waits for the background read of `staged` and frees what it produced. */ +void discard_staged(Staged *staged) +{ + if (staged == nullptr) + return; + if (staged->thread != nullptr) { + WaitForSingleObject(staged->thread, INFINITE); + CloseHandle(staged->thread); + } + free_pack(staged->pack); + delete staged; +} + +/* Takes the staged pack if it is `pack_path`; the caller then owns (and joins) it. */ +Staged *take_staged(const wchar_t *pack_path) +{ + AcquireSRWLockExclusive(&g_stage_lock); + Staged *staged = g_staged; + if (staged != nullptr && staged->packPath == pack_path) + g_staged = nullptr; + else + staged = nullptr; + ReleaseSRWLockExclusive(&g_stage_lock); + return staged; +} + +void replace_pack(Pack *pack) +{ + AcquireSRWLockExclusive(&g_lock); + init_filters_locked(); + free_pack(g_pack); + g_pack = pack; + paths_reset_locked(); + dynamic_reset_locked(); + memset(&g_stats, 0, sizeof(g_stats)); + g_stats.loaded = pack != nullptr; + ReleaseSRWLockExclusive(&g_lock); +} + +} // namespace + +float QueryFilter::getCost(const float *pa, const float *pb, + const dtPolyRef, const dtMeshTile *, const dtPoly *, + const dtPolyRef, const dtMeshTile *, const dtPoly *curPoly, + const dtPolyRef, const dtMeshTile *, const dtPoly *) const +{ + float cost = dtVdist(pa, pb) * getAreaCost(curPoly->getArea()); + if (curPoly->flags & WTO_FLAG_CHOKEPOINT) + cost *= chokepointMul; + if (g_dynamic_count != 0) { + const float mx = (pa[0] + pb[0]) * 0.5f, mz = (pa[2] + pb[2]) * 0.5f; + float mul = 1.0f; + for (uint32_t i = 0; i < g_dynamic_count; i++) { + const DynamicCost &d = g_dynamic[i]; + const float dx = mx - d.pos[0], dz = mz - d.pos[2]; + if (dx * dx + dz * dz < d.radius * d.radius && d.mul > mul) + mul = d.mul; + } + cost *= mul; + } + return cost; +} + bool snap_to_mesh(const dtNavMeshQuery *query, const dtQueryFilter &filter, float snap, float height_span, const float point[3], dtPolyRef *ref, float nearest[3]) { @@ -229,45 +303,9 @@ double now_micros() return (double)counter.QuadPart * 1e6 / (double)frequency.QuadPart; } -WtoNavPathStatus find_path_locked(uint32_t tier, uint32_t filter_index, float snap_radius_m, - const float start[3], const float goal[3], - float *points, int max_points, int *count, float *length_m) -{ - if (g_pack == nullptr || tier >= WTO_NAV_TIER_COUNT || filter_index >= WTO_NAV_RT_FILTER_COUNT || - points == nullptr || max_points < 2 || !(snap_radius_m > 0.0f)) - return WTO_NAV_PATH_FAILED; - dtNavMeshQuery *query = g_pack->queries[tier]; - const WtoQueryFilter &filter = g_filters[filter_index]; - dtPolyRef start_ref = 0, goal_ref = 0; - float start_pt[3], goal_pt[3]; +} // namespace wtonav - if (!snap_to_mesh(query, filter, snap_radius_m, g_pack->heightSpan, start, &start_ref, start_pt)) - return WTO_NAV_PATH_NO_START; - if (!snap_to_mesh(query, filter, snap_radius_m, g_pack->heightSpan, goal, &goal_ref, goal_pt)) - return WTO_NAV_PATH_NO_GOAL; - - static dtPolyRef path[kMaxPathPolys]; - int path_count = 0; - dtStatus status = query->findPath(start_ref, goal_ref, start_pt, goal_pt, &filter, path, &path_count, kMaxPathPolys); - if (dtStatusFailed(status) || path_count == 0) - return WTO_NAV_PATH_FAILED; - bool partial = dtStatusDetail(status, DT_PARTIAL_RESULT) || path[path_count - 1] != goal_ref; - if (partial && dtStatusFailed(query->closestPointOnPoly(path[path_count - 1], goal, goal_pt, nullptr))) - return WTO_NAV_PATH_FAILED; - - int corners = 0; - status = query->findStraightPath(start_pt, goal_pt, path, path_count, points, nullptr, nullptr, &corners, max_points, 0); - if (dtStatusFailed(status) || corners == 0) - return WTO_NAV_PATH_FAILED; - float length = 0.0f; - for (int i = 1; i < corners; i++) - length += dtVdist(points + (i - 1) * 3, points + i * 3); - *count = corners; - *length_m = length; - return partial ? WTO_NAV_PATH_PARTIAL : WTO_NAV_PATH_FULL; -} - -} // namespace +using namespace wtonav; extern "C" int wto_nav_read_level_fingerprint(const wchar_t *level_path, uint8_t sha1[20]) { @@ -314,39 +352,54 @@ extern "C" int wto_nav_read_level_fingerprint(const wchar_t *level_path, uint8_t return found; } -extern "C" void wto_nav_load(const wchar_t *pack_path, const uint8_t *level_sha1, WtoNavLoadInfo *info) +extern "C" void wto_nav_prefetch(const wchar_t *pack_path, const wchar_t *level_path) { - std::vector data; - Pack *pack = nullptr; - - memset(info, 0, sizeof(*info)); - if (level_sha1 != nullptr) { - info->fingerprintKnown = 1; - memcpy(info->levelSha1, level_sha1, sizeof(info->levelSha1)); + if (pack_path == nullptr || pack_path[0] == L'\0') + return; + AcquireSRWLockExclusive(&g_stage_lock); + if (g_staged != nullptr && g_staged->packPath == pack_path) { + ReleaseSRWLockExclusive(&g_stage_lock); + return; } - if (read_file(pack_path, data, info)) { - pack = parse_pack(data, info); - info->result = pack != nullptr ? WTO_NAV_LOAD_OK : WTO_NAV_LOAD_CORRUPT; + Staged *previous = g_staged; + Staged *staged = new Staged(); + staged->packPath = pack_path; + staged->levelPath = level_path != nullptr ? level_path : L""; + staged->thread = CreateThread(nullptr, 0, prefetch_main, staged, 0, nullptr); + if (staged->thread == nullptr) { + delete staged; + staged = nullptr; } - if (pack != nullptr && level_sha1 != nullptr) - info->fingerprintMatch = memcmp(info->packSha1, level_sha1, sizeof(info->packSha1)) == 0; + g_staged = staged; + ReleaseSRWLockExclusive(&g_stage_lock); + discard_staged(previous); +} - AcquireSRWLockExclusive(&g_lock); - init_filters_locked(); - free_pack(g_pack); - g_pack = pack; - memset(&g_stats, 0, sizeof(g_stats)); - g_stats.loaded = pack != nullptr; - ReleaseSRWLockExclusive(&g_lock); +extern "C" void wto_nav_load(const wchar_t *pack_path, const wchar_t *level_path, WtoNavLoadInfo *info) +{ + const double began = now_micros(); + Staged *staged = take_staged(pack_path); + Pack *pack; + + if (staged != nullptr) { + WaitForSingleObject(staged->thread, INFINITE); + CloseHandle(staged->thread); + staged->thread = nullptr; + pack = staged->pack; + staged->pack = nullptr; + *info = staged->info; + info->prefetched = 1; + discard_staged(staged); + } else { + pack = read_pack(pack_path, level_path, info); + } + info->waitMs = (now_micros() - began) / 1000.0; + replace_pack(pack); } extern "C" void wto_nav_unload(void) { - AcquireSRWLockExclusive(&g_lock); - free_pack(g_pack); - g_pack = nullptr; - g_stats.loaded = 0; - ReleaseSRWLockExclusive(&g_lock); + replace_pack(nullptr); } extern "C" int wto_nav_is_loaded(void) @@ -369,31 +422,11 @@ extern "C" void wto_nav_set_costs(uint32_t filter, const WtoNavCosts *costs) ReleaseSRWLockExclusive(&g_lock); } -extern "C" WtoNavPathStatus wto_nav_find_path(uint32_t tier, uint32_t filter, float snap_radius_m, - const float start[3], const float goal[3], - float *points, int max_points, int *count, float *length_m) -{ - *count = 0; - *length_m = 0.0f; - AcquireSRWLockExclusive(&g_lock); - const double began = now_micros(); - const WtoNavPathStatus status = find_path_locked(tier, filter, snap_radius_m, start, goal, points, max_points, count, length_m); - const double spent = now_micros() - began; - if (g_pack != nullptr) { - g_stats.queries++; - g_stats.totalMicros += spent; - if (spent > g_stats.maxMicros) - g_stats.maxMicros = spent; - if (status != WTO_NAV_PATH_FULL) - g_stats.failures++; - } - ReleaseSRWLockExclusive(&g_lock); - return status; -} - extern "C" void wto_nav_get_stats(WtoNavStats *stats) { - AcquireSRWLockShared(&g_lock); + AcquireSRWLockExclusive(&g_lock); + g_stats.pending = paths_pending_locked(); + g_stats.dynamic = g_dynamic_count; *stats = g_stats; - ReleaseSRWLockShared(&g_lock); + ReleaseSRWLockExclusive(&g_lock); } diff --git a/native/wto-nav/wto_nav_runtime.h b/native/wto-nav/wto_nav_runtime.h index a278edc..e29c64a 100644 --- a/native/wto-nav/wto_nav_runtime.h +++ b/native/wto-nav/wto_nav_runtime.h @@ -1,7 +1,7 @@ /* * In-game navigation engine: one baked `.wtonav` pack (tools/navgen) held for the battle in * progress, queried through upstream Detour. The C side (wto-net local_mp_nav.c) owns the - * daScript request protocol; this interface only knows packs, levels and paths. + * daScript request protocol; this interface only knows packs, levels, paths and mesh queries. * * Every function is safe to call from any thread; queries are serialized internally. */ @@ -13,8 +13,11 @@ extern "C" { #endif -#define WTO_NAV_RT_AREA_COUNT 12 /* WtoPolyArea values 0..11 */ -#define WTO_NAV_RT_FILTER_COUNT 2 /* 0 tracked, 1 wheeled */ +#define WTO_NAV_RT_AREA_COUNT 12 /* WtoPolyArea values 0..11 */ +#define WTO_NAV_RT_FILTER_COUNT 2 /* 0 tracked, 1 wheeled */ +#define WTO_NAV_RT_PATH_SLOTS 160 /* Independent path searches the script may keep in flight */ +#define WTO_NAV_RT_MAX_CORNERS 96 /* Straight-path corners returned per path */ +#define WTO_NAV_RT_MAX_DYNAMIC 64 /* Live dynamic cost circles (wrecks, jams, rubble) */ /* Detour traversal costs for one vehicle class, indexed by WtoPolyArea. */ typedef struct WtoNavCosts { @@ -33,11 +36,14 @@ typedef struct WtoNavLoadInfo { WtoNavLoadResult result; int fingerprintKnown; /* 1 when the level file's eVER SHA-1 was read */ int fingerprintMatch; /* 1 when it equals the pack's; meaningful only when known */ + int prefetched; /* 1 when the pack was read in the background beforehand */ uint8_t packSha1[20]; uint8_t levelSha1[20]; uint32_t tiers; uint32_t covers; uint32_t polys[3]; + double readMs; /* Time spent reading and parsing, wherever it happened */ + double waitMs; /* Time the caller of wto_nav_load was held up */ char detail[96]; /* Why loading failed, for the log */ } WtoNavLoadInfo; @@ -45,26 +51,68 @@ typedef enum WtoNavPathStatus { WTO_NAV_PATH_FULL = 0, WTO_NAV_PATH_PARTIAL, /* Ends at the reachable polygon closest to the goal */ WTO_NAV_PATH_NO_START, /* Start not within the snap radius of the mesh */ - WTO_NAV_PATH_NO_GOAL, + WTO_NAV_PATH_NO_GOAL, /* Goal not within the goal snap radius of the mesh */ WTO_NAV_PATH_FAILED, /* No pack loaded, bad tier or Detour failure */ + WTO_NAV_PATH_PENDING, /* Queued or being searched; ask again after the next pump */ + WTO_NAV_PATH_STALE, /* The slot holds another (newer) request, or none */ } WtoNavPathStatus; +typedef struct WtoNavPathRequest { + uint32_t tier; /* 0 narrow, 1 standard, 2 wide */ + uint32_t filter; /* 0 tracked, 1 wheeled */ + float snapM; /* Start (and first goal) snap radius */ + float goalSnapM; /* Wider horizontal goal snap when the goal misses snapM */ + float start[3]; + float goal[3]; +} WtoNavPathRequest; + +typedef struct WtoNavPathResult { + WtoNavPathStatus status; + int count; /* Corners written, the first being the snapped start */ + int truncated; /* 1 when the path has more corners than were returned */ + int goalMoved; /* 1 when the goal was snapped with goalSnapM */ + float lengthM; /* Length of the returned corners */ +} WtoNavPathResult; + +/* What the mesh says about one point of the tier's mesh. */ +typedef struct WtoNavProbe { + int onMesh; /* 1 when a polygon lies within the snap radius */ + float nearest[3]; /* Closest point on that polygon */ + float offsetM; /* Horizontal distance from the asked point to `nearest` */ + float wallDistM; /* Distance to the mesh edge, capped at the search radius */ + uint32_t area; /* WtoPolyArea of the polygon */ + uint32_t flags; /* WtoPolyFlag bits of the polygon */ +} WtoNavProbe; + typedef struct WtoNavStats { int loaded; - uint32_t queries; - uint32_t failures; - double totalMicros; - double maxMicros; + uint32_t queries; /* Finished path searches */ + uint32_t failures; /* Of which not FULL */ + double totalMicros; /* Search time of finished paths, summed over their frames */ + double maxMicros; /* Longest search time of a single path */ + uint32_t maxFrames; /* Most pump frames a single path took */ + double pumpMaxMicros; /* Longest single pump */ + uint32_t pending; /* Paths waiting or being searched now */ + uint32_t dynamic; /* Live dynamic cost circles */ + uint32_t meshQueries; /* Probe, raycast and nearest calls */ } WtoNavStats; /* Reads the eVER SHA-1 of a Dagor level file (levels/.bin) without loading the level. */ int wto_nav_read_level_fingerprint(const wchar_t *level_path, uint8_t sha1[20]); /* - * Loads `pack_path`, replacing any loaded pack. `level_sha1` is the fingerprint of the level the - * game runs (NULL when unknown); a mismatch is reported but never refuses the pack. + * Starts reading `pack_path` (and the fingerprint of `level_path`) on a background thread so a + * later wto_nav_load of the same pack only takes the result. Nothing happens when that pack is + * already being read or waiting; a different one replaces it. */ -void wto_nav_load(const wchar_t *pack_path, const uint8_t *level_sha1, WtoNavLoadInfo *info); +void wto_nav_prefetch(const wchar_t *pack_path, const wchar_t *level_path); + +/* + * Makes `pack_path` the loaded pack, replacing any other: from the background read when it is + * the same file (waiting for it to finish), otherwise read here. A fingerprint mismatch is + * reported but never refuses the pack. Clears paths in flight and dynamic costs. + */ +void wto_nav_load(const wchar_t *pack_path, const wchar_t *level_path, WtoNavLoadInfo *info); void wto_nav_unload(void); int wto_nav_is_loaded(void); @@ -72,12 +120,38 @@ int wto_nav_is_loaded(void); void wto_nav_set_costs(uint32_t filter, const WtoNavCosts *costs); /* - * Straight-line corners from `start` to `goal` on the mesh of `tier` (0 narrow, 1 standard, - * 2 wide). `points` receives up to `max_points` xyz triples; the first is the snapped start. + * Queues a path search in `slot`, replacing whatever the slot held. Start and goal are snapped + * at once; a miss is final and reported through the ticket's result. Returns the ticket that + * wto_nav_path_result must quote (0 when the slot or request is invalid). */ -WtoNavPathStatus wto_nav_find_path(uint32_t tier, uint32_t filter, float snap_radius_m, - const float start[3], const float goal[3], - float *points, int max_points, int *count, float *length_m); +uint32_t wto_nav_path_request(uint32_t slot, const WtoNavPathRequest *request); + +/* Result of `ticket` in `slot`; `points` receives up to `max_points` xyz triples. */ +void wto_nav_path_result(uint32_t slot, uint32_t ticket, float *points, int max_points, WtoNavPathResult *result); + +/* + * Advances queued searches for at most `budget_us` microseconds (one call per game frame) and + * expires dynamic costs whose end time is before `now` (script time, seconds). + */ +void wto_nav_pump(double budget_us, float now); + +int wto_nav_probe(uint32_t tier, uint32_t filter, const float pos[3], float snap_m, float wall_radius_m, WtoNavProbe *probe); + +/* + * Walks the mesh surface from `start` toward `goal`. Returns 1 when nothing blocks the way, + * 0 when a mesh edge does (`hit_frac` and `hit` tell where), -1 when `start` is off the mesh. + */ +int wto_nav_raycast(uint32_t tier, uint32_t filter, float snap_m, const float start[3], const float goal[3], + float *hit_frac, float hit[3]); + +/* Closest point of the tier's mesh within `radius_m` (horizontally, any height); 1 if found. */ +int wto_nav_nearest(uint32_t tier, uint32_t filter, float radius_m, const float pos[3], float out[3]); + +/* + * Adds a circle that multiplies path costs by `cost_mul` until script time `until`; a circle + * close to an existing one updates it. Returns the number of live circles. + */ +uint32_t wto_nav_add_dynamic(const float pos[3], float radius_m, float cost_mul, float until); void wto_nav_get_stats(WtoNavStats *stats); diff --git a/native/wto-net/build.ps1 b/native/wto-net/build.ps1 index c786288..79c979d 100644 --- a/native/wto-net/build.ps1 +++ b/native/wto-net/build.ps1 @@ -32,7 +32,7 @@ $sources = Quote @( "$src\dll_main.c", "$src\hook_config.c", "$src\redirect_rules.c", "$src\resolver_hooks.c", "$src\connection_hooks.c", "$src\local_mp_core.c", "$src\local_mp_values.c", "$src\local_mp_players.c", "$src\local_mp_loadout.c", "$src\local_mp_actions.c", "$src\local_mp_awards.c", "$src\local_mp_kills.c", "$src\local_mp_events.c", "$src\local_mp_scores.c", "$src\local_mp_nuke.c", "$src\local_mp_support.c", "$src\local_mp_damage_notifications.c", "$src\local_mp_air_events.c", "$src\local_mp_ground_ai.c", "$src\local_mp_nav.c", "$src\local_mp_zones.c", - "$nav\wto_nav_runtime.cpp", + "$nav\wto_nav_runtime.cpp", "$nav\wto_nav_paths.cpp", "$nav\wto_nav_queries.cpp", "$mh\src\hook.c", "$mh\src\buffer.c", "$mh\src\trampoline.c", "$mh\src\hde\hde64.c" ) $detourSources = Quote (Get-ChildItem "$dt\Source\*.cpp").FullName diff --git a/native/wto-net/src/local_mp_nav.c b/native/wto-net/src/local_mp_nav.c index 3377b54..6c391d1 100644 --- a/native/wto-net/src/local_mp_nav.c +++ b/native/wto-net/src/local_mp_nav.c @@ -3,22 +3,33 @@ * battle's navigation pack (native/wto-nav). The script fills a DataBlock with the request, this * module answers synchronously by writing into the same block: * - * op=load_map allowFallback="0|1", tracked/wheeled costs t_, w_ - * -> state=loaded|fallback|failed, fingerprint=match|mismatch|unknown, level, - * reason, tiers, covers - * op=unload_map -> ok - * op=find_path tier, filter (0 tracked, 1 wheeled), max, snap, sx..sz, gx..gz - * -> status=full|partial|no_start|no_goal|failed, count, lenCm, - * px/py/pz in centimetres (ints) - * op=get_stats -> loaded, queries, failures, avgUs, maxUs + * op=prefetch -> state=started|skipped, level, reason (battle still loading) + * op=load_map allowFallback="0|1", tracked/wheeled costs t_, w_ + * -> state=loaded|fallback|failed, fingerprint=match|mismatch|unknown, level, + * reason, tiers, covers + * op=unload_map -> ok + * op=pump now (script seconds), budgetUs -> pending + * op=path_request slot, tier, filter (0 tracked, 1 wheeled), snap, goalSnap, sx..sz, gx..gz + * -> ticket + * op=path_result slot, ticket -> status=pending|full|partial|no_start|no_goal|failed|stale, + * count, lenCm, truncated, goalMoved, px/py/pz + * op=probe tier, filter, snap, wallR, px..pz -> onMesh, offCm, wallCm, area, flags, + * nx/ny/nz + * op=raycast tier, filter, snap, sx..sz, gx..gz -> clear=1|0|-1, hitPm, hx/hy/hz + * op=nearest tier, filter, radius, px..pz -> found, x/y/z + * op=dynamic px..pz, radius, mul, until (script seconds) -> count + * op=get_stats -> loaded, queries, failures, avgUs, maxUs, maxFrames, pumpMaxUs, pending, + * dynamic, meshQueries * - * Request values are strings: the script only uses the DataBlock string add it already relies on. - * Replies are ints and strings written with the setters local_mp_awards resolves. + * Coordinates in replies are centimetres (ints). Request values are strings: the script only uses + * the DataBlock string add it already relies on. Replies are ints and strings written with the + * setters local_mp_awards resolves. * * The level comes from the mission settings (customBots wtoLevel, written by the local server), - * the pack folder from wto_ws.cfg (nav.dir). Whether the battle uses the pack, falls back to the - * script's own navigation or refuses to drive is decided by the first load_map of the battle and - * kept until unload_map or the end of the session; it never changes in the middle of a battle. + * the pack folder from wto_ws.cfg (nav.dir). The script asks for a prefetch while the battle + * loads, so the pack is read on a background thread. Whether the battle uses the pack, falls back + * to stock road paths or refuses to drive is decided by the first load_map of the battle and kept + * until unload_map or the end of the session; it never changes in the middle of a battle. */ #include "hook_config.h" #include "local_mp_internal.h" @@ -30,7 +41,6 @@ #include #include -#define NAV_MAX_POINTS 96 #define NAV_LEVEL_MAX 64 typedef void (__fastcall *BlkSetStrFn)(void *blk, const char *name, const char *value); @@ -107,6 +117,17 @@ static long get_long(const void *blk, const char *name, long def) return *end == '\0' ? value : def; } +/* x, y, z */ +static void get_vec(const void *blk, char prefix, float out[3]) +{ + char key[3] = { prefix, 'x', '\0' }; + out[0] = get_real(blk, key, 0.0f); + key[1] = 'y'; + out[1] = get_real(blk, key, 0.0f); + key[1] = 'z'; + out[2] = get_real(blk, key, 0.0f); +} + static int32_t to_cm(float metres) { const float cm = metres * 100.0f; @@ -117,6 +138,13 @@ static int32_t to_cm(float metres) return (int32_t)(cm >= 0.0f ? cm + 0.5f : cm - 0.5f); } +static void set_vec_cm(void *blk, const char *x, const char *y, const char *z, const float v[3]) +{ + set_int(blk, x, to_cm(v[0])); + set_int(blk, y, to_cm(v[1])); + set_int(blk, z, to_cm(v[2])); +} + static void hex20(const uint8_t *sha1, char out[41]) { static const char digits[] = "0123456789abcdef"; @@ -172,6 +200,32 @@ static int level_file_path(const char *level, wchar_t *out, size_t out_count) return _snwprintf_s(out, out_count, _TRUNCATE, L"%s\\levels\\%S.bin", exe, level) > 0; } +/* + * Pack and level paths of the battle in the mission settings; on failure `reason` says why. + * `level_path` is left empty when the level file cannot be located (fingerprint unknown). + */ +static int battle_paths(char level[NAV_LEVEL_MAX], wchar_t pack[MAX_PATH], wchar_t level_path[MAX_PATH], + char *reason, size_t reason_size) +{ + const wchar_t *dir = config_nav_dir(); + if (!battle_level(level)) { + level[0] = '\0'; + snprintf(reason, reason_size, "battle level unknown (customBots wtoLevel)"); + return 0; + } + if (dir[0] == L'\0') { + snprintf(reason, reason_size, "no pack folder (wto_ws.cfg nav.dir)"); + return 0; + } + if (_snwprintf_s(pack, MAX_PATH, _TRUNCATE, L"%s\\%S.wtonav", dir, level) <= 0) { + snprintf(reason, reason_size, "pack path too long"); + return 0; + } + if (!level_file_path(level, level_path, MAX_PATH)) + level_path[0] = L'\0'; + return 1; +} + static void read_costs(const void *blk, const char *prefix, WtoNavCosts *costs) { char key[48]; @@ -191,49 +245,43 @@ static void read_costs(const void *blk, const char *prefix, WtoNavCosts *costs) costs->chokepointMul = 1.0f; } +static void log_loaded(const WtoNavLoadInfo *info) +{ + char expected[41], actual[41]; + hex20(info->packSha1, expected); + hex20(info->levelSha1, actual); + if (info->fingerprintKnown && !info->fingerprintMatch) + log_line("WTO_NAV|FINGERPRINT_MISMATCH|level=%s|expected=%s|actual=%s", g_battle.level, expected, actual); + log_line("WTO_NAV|LOADED|level=%s|fingerprint=%s|tiers=%u|covers=%u|polys=%u/%u/%u|prefetched=%d|readMs=%.0f|waitMs=%.1f", + g_battle.level, g_battle.fingerprint, info->tiers, info->covers, + info->polys[0], info->polys[1], info->polys[2], info->prefetched, info->readMs, info->waitMs); +} + static void decide_locked(const void *blk, int allow_fallback) { wchar_t pack[MAX_PATH], level_path[MAX_PATH]; - const wchar_t *dir = config_nav_dir(); - uint8_t level_sha1[20]; - int have_level_sha1 = 0; WtoNavLoadInfo info; - double began = (double)GetTickCount64(); WtoNavCosts costs; memset(&info, 0, sizeof(info)); - if (!battle_level(g_battle.level)) { - snprintf(g_battle.reason, sizeof(g_battle.reason), "battle level unknown (customBots wtoLevel)"); - } else if (dir[0] == L'\0') { - snprintf(g_battle.reason, sizeof(g_battle.reason), "no pack folder (wto_ws.cfg nav.dir)"); - } else if (_snwprintf_s(pack, MAX_PATH, _TRUNCATE, L"%s\\%S.wtonav", dir, g_battle.level) <= 0) { - snprintf(g_battle.reason, sizeof(g_battle.reason), "pack path too long"); - } else { - have_level_sha1 = level_file_path(g_battle.level, level_path, MAX_PATH) && - wto_nav_read_level_fingerprint(level_path, level_sha1); + info.result = WTO_NAV_LOAD_MISSING; + if (battle_paths(g_battle.level, pack, level_path, g_battle.reason, sizeof(g_battle.reason))) { read_costs(blk, "t", &costs); wto_nav_set_costs(0, &costs); read_costs(blk, "w", &costs); wto_nav_set_costs(1, &costs); - wto_nav_load(pack, have_level_sha1 ? level_sha1 : NULL, &info); + wto_nav_load(pack, level_path[0] ? level_path : NULL, &info); if (info.result != WTO_NAV_LOAD_OK) snprintf(g_battle.reason, sizeof(g_battle.reason), "%s", info.detail); } if (info.result == WTO_NAV_LOAD_OK && g_battle.reason[0] == '\0') { - char expected[41], actual[41]; g_battle.decision = NAV_LOADED; g_battle.tiers = info.tiers; g_battle.covers = info.covers; snprintf(g_battle.fingerprint, sizeof(g_battle.fingerprint), "%s", !info.fingerprintKnown ? "unknown" : info.fingerprintMatch ? "match" : "mismatch"); - hex20(info.packSha1, expected); - hex20(info.levelSha1, actual); - if (info.fingerprintKnown && !info.fingerprintMatch) - log_line("WTO_NAV|FINGERPRINT_MISMATCH|level=%s|expected=%s|actual=%s", g_battle.level, expected, actual); - log_line("WTO_NAV|LOADED|level=%s|fingerprint=%s|tiers=%u|covers=%u|polys=%u/%u/%u|ms=%.0f", - g_battle.level, g_battle.fingerprint, info.tiers, info.covers, - info.polys[0], info.polys[1], info.polys[2], (double)GetTickCount64() - began); + log_loaded(&info); return; } snprintf(g_battle.fingerprint, sizeof(g_battle.fingerprint), "unknown"); @@ -244,6 +292,27 @@ static void decide_locked(const void *blk, int allow_fallback) log_line("WTO_NAV|LOAD_FAILED_NO_FALLBACK|level=%s|reason=%s", g_battle.level, g_battle.reason); } +static void prefetch(void *blk) +{ + wchar_t pack[MAX_PATH], level_path[MAX_PATH]; + char level[NAV_LEVEL_MAX], reason[96] = ""; + int started = 0; + + AcquireSRWLockExclusive(&g_battle_lock); + if (g_battle.decision != NAV_UNDECIDED) { + snprintf(reason, sizeof(reason), "battle already decided"); + level[0] = '\0'; + } else if (battle_paths(level, pack, level_path, reason, sizeof(reason))) { + wto_nav_prefetch(pack, level_path); + started = 1; + log_line("WTO_NAV|PREFETCH|level=%s", level); + } + ReleaseSRWLockExclusive(&g_battle_lock); + set_str(blk, "state", started ? "started" : "skipped"); + set_str(blk, "level", level); + set_str(blk, "reason", reason); +} + static void load_map(void *blk) { static const char *const STATES[] = { "", "loaded", "fallback", "failed" }; @@ -268,45 +337,108 @@ static void unload_locked(const char *why) if (wto_nav_is_loaded()) { WtoNavStats stats; wto_nav_get_stats(&stats); - log_line("WTO_NAV|UNLOADED|level=%s|why=%s|queries=%u|failures=%u|avgUs=%.0f|maxUs=%.0f", + log_line("WTO_NAV|UNLOADED|level=%s|why=%s|paths=%u|failures=%u|avgUs=%.0f|maxUs=%.0f|maxFrames=%u|pumpMaxUs=%.0f|meshQueries=%u", g_battle.level, why, stats.queries, stats.failures, - stats.queries ? stats.totalMicros / stats.queries : 0.0, stats.maxMicros); + stats.queries ? stats.totalMicros / stats.queries : 0.0, stats.maxMicros, + stats.maxFrames, stats.pumpMaxMicros, stats.meshQueries); wto_nav_unload(); } memset(&g_battle, 0, sizeof(g_battle)); } -static void find_path(void *blk) +static void path_request(void *blk) { - static const char *const STATUS[] = { "full", "partial", "no_start", "no_goal", "failed" }; - float points[NAV_MAX_POINTS * 3]; - const float start[3] = { get_real(blk, "sx", 0.0f), get_real(blk, "sy", 0.0f), get_real(blk, "sz", 0.0f) }; - const float goal[3] = { get_real(blk, "gx", 0.0f), get_real(blk, "gy", 0.0f), get_real(blk, "gz", 0.0f) }; - const long tier = get_long(blk, "tier", -1), filter = get_long(blk, "filter", 0); - long max = get_long(blk, "max", NAV_MAX_POINTS); - int count = 0, i; - float length = 0.0f; - char key[16]; - WtoNavPathStatus status; + WtoNavPathRequest req; + const long slot = get_long(blk, "slot", -1), tier = get_long(blk, "tier", -1), filter = get_long(blk, "filter", 0); + uint32_t ticket = 0; - if (max < 2 || max > NAV_MAX_POINTS) - max = NAV_MAX_POINTS; - status = (tier < 0 || filter < 0) ? WTO_NAV_PATH_FAILED - : wto_nav_find_path((uint32_t)tier, (uint32_t)filter, get_real(blk, "snap", 0.0f), - start, goal, points, (int)max, &count, &length); - set_str(blk, "status", STATUS[status]); - set_int(blk, "count", count); - set_int(blk, "lenCm", to_cm(length)); - for (i = 0; i < count; i++) { + memset(&req, 0, sizeof(req)); + req.tier = (uint32_t)tier; + req.filter = (uint32_t)filter; + req.snapM = get_real(blk, "snap", 0.0f); + req.goalSnapM = get_real(blk, "goalSnap", 0.0f); + get_vec(blk, 's', req.start); + get_vec(blk, 'g', req.goal); + if (slot >= 0 && tier >= 0 && filter >= 0) + ticket = wto_nav_path_request((uint32_t)slot, &req); + set_int(blk, "ticket", (int32_t)ticket); +} + +static void path_result(void *blk) +{ + static const char *const STATUS[] = { "full", "partial", "no_start", "no_goal", "failed", "pending", "stale" }; + float points[WTO_NAV_RT_MAX_CORNERS * 3]; + const long slot = get_long(blk, "slot", -1), ticket = get_long(blk, "ticket", 0); + WtoNavPathResult result; + char key[16]; + int i; + + wto_nav_path_result(slot < 0 ? UINT32_MAX : (uint32_t)slot, ticket <= 0 ? 0u : (uint32_t)ticket, + points, WTO_NAV_RT_MAX_CORNERS, &result); + set_str(blk, "status", STATUS[result.status]); + set_int(blk, "count", result.count); + set_int(blk, "lenCm", to_cm(result.lengthM)); + set_int(blk, "truncated", result.truncated); + set_int(blk, "goalMoved", result.goalMoved); + for (i = 0; i < result.count; i++) { + char ky[16], kz[16]; snprintf(key, sizeof(key), "p%dx", i); - set_int(blk, key, to_cm(points[i * 3])); - snprintf(key, sizeof(key), "p%dy", i); - set_int(blk, key, to_cm(points[i * 3 + 1])); - snprintf(key, sizeof(key), "p%dz", i); - set_int(blk, key, to_cm(points[i * 3 + 2])); + snprintf(ky, sizeof(ky), "p%dy", i); + snprintf(kz, sizeof(kz), "p%dz", i); + set_vec_cm(blk, key, ky, kz, points + i * 3); } } +static void probe(void *blk) +{ + WtoNavProbe info; + float pos[3]; + get_vec(blk, 'p', pos); + if (!wto_nav_probe((uint32_t)get_long(blk, "tier", 0), (uint32_t)get_long(blk, "filter", 0), pos, + get_real(blk, "snap", 0.0f), get_real(blk, "wallR", 0.0f), &info)) + info.onMesh = -1; + set_int(blk, "onMesh", info.onMesh); + if (info.onMesh != 1) + return; + set_int(blk, "offCm", to_cm(info.offsetM)); + set_int(blk, "wallCm", to_cm(info.wallDistM)); + set_int(blk, "area", (int32_t)info.area); + set_int(blk, "flags", (int32_t)info.flags); + set_vec_cm(blk, "nx", "ny", "nz", info.nearest); +} + +static void raycast(void *blk) +{ + float start[3], goal[3], hit[3], frac = 0.0f; + int clear; + get_vec(blk, 's', start); + get_vec(blk, 'g', goal); + clear = wto_nav_raycast((uint32_t)get_long(blk, "tier", 0), (uint32_t)get_long(blk, "filter", 0), + get_real(blk, "snap", 0.0f), start, goal, &frac, hit); + set_int(blk, "clear", clear); + set_int(blk, "hitPm", (int32_t)(frac * 1000.0f + 0.5f)); + set_vec_cm(blk, "hx", "hy", "hz", hit); +} + +static void nearest(void *blk) +{ + float pos[3], out[3] = { 0.0f, 0.0f, 0.0f }; + int found; + get_vec(blk, 'p', pos); + found = wto_nav_nearest((uint32_t)get_long(blk, "tier", 0), (uint32_t)get_long(blk, "filter", 0), + get_real(blk, "radius", 0.0f), pos, out); + set_int(blk, "found", found); + set_vec_cm(blk, "x", "y", "z", out); +} + +static void add_dynamic(void *blk) +{ + float pos[3]; + get_vec(blk, 'p', pos); + set_int(blk, "count", (int32_t)wto_nav_add_dynamic(pos, get_real(blk, "radius", 0.0f), get_real(blk, "mul", 1.0f), + get_real(blk, "until", 0.0f))); +} + static void get_stats(void *blk) { WtoNavStats stats; @@ -316,6 +448,19 @@ static void get_stats(void *blk) set_int(blk, "failures", (int32_t)stats.failures); set_int(blk, "avgUs", stats.queries ? (int32_t)(stats.totalMicros / stats.queries) : 0); set_int(blk, "maxUs", (int32_t)stats.maxMicros); + set_int(blk, "maxFrames", (int32_t)stats.maxFrames); + set_int(blk, "pumpMaxUs", (int32_t)stats.pumpMaxMicros); + set_int(blk, "pending", (int32_t)stats.pending); + set_int(blk, "dynamic", (int32_t)stats.dynamic); + set_int(blk, "meshQueries", (int32_t)stats.meshQueries); +} + +static void pump(void *blk) +{ + WtoNavStats stats; + wto_nav_pump((double)get_real(blk, "budgetUs", 500.0f), get_real(blk, "now", 0.0f)); + wto_nav_get_stats(&stats); + set_int(blk, "pending", (int32_t)stats.pending); } void local_mp_nav_request(void *blk) @@ -327,8 +472,22 @@ void local_mp_nav_request(void *blk) op = g_lmp_datablock_get_str(blk, "op", ""); if (op == NULL) return; - if (strcmp(op, "find_path") == 0) { - find_path(blk); + if (strcmp(op, "probe") == 0) { + probe(blk); + } else if (strcmp(op, "path_result") == 0) { + path_result(blk); + } else if (strcmp(op, "path_request") == 0) { + path_request(blk); + } else if (strcmp(op, "raycast") == 0) { + raycast(blk); + } else if (strcmp(op, "pump") == 0) { + pump(blk); + } else if (strcmp(op, "nearest") == 0) { + nearest(blk); + } else if (strcmp(op, "dynamic") == 0) { + add_dynamic(blk); + } else if (strcmp(op, "prefetch") == 0) { + prefetch(blk); } else if (strcmp(op, "load_map") == 0) { load_map(blk); } else if (strcmp(op, "unload_map") == 0) { diff --git a/packages/patcher/src/ground-ai/ground-ai-config.ts b/packages/patcher/src/ground-ai/ground-ai-config.ts index 72c188c..a4f2500 100644 --- a/packages/patcher/src/ground-ai/ground-ai-config.ts +++ b/packages/patcher/src/ground-ai/ground-ai-config.ts @@ -35,6 +35,46 @@ export interface GroundAiNavCosts { readonly chokepoint: number; } +/** Path following, local avoidance and unstick of the ground AI (navigation plan section 8). */ +export interface GroundAiPathFollow { + readonly replanIntervalSec: number; + readonly replanGoalMoveM: number; + readonly offCorridorReplanM: number; + readonly lookaheadTimeSec: number; + readonly trackedLookaheadMinM: number; + readonly trackedLookaheadMaxM: number; + readonly wheeledLookaheadMinM: number; + readonly wheeledLookaheadMaxM: number; + readonly cornerAngleDeg: number; + readonly cornerLateralAccelMps2: number; + readonly cornerBrakeDecelMps2: number; + readonly arriveRadiusM: number; + readonly arriveMinSpeedMps: number; + readonly narrowWallMarginM: number; + readonly narrowSpeedMps: number; + readonly bumperRayM: number; + readonly bumperStopM: number; + readonly bumperBlockSec: number; + readonly trafficTtcSec: number; + readonly avoidShiftM: number; + readonly yieldWaitMaxSec: number; + readonly stuckWindowSec: number; + readonly stuckMinProgressM: number; + readonly unstickReverseM: number; + readonly unstickReverseSec: number; + readonly unstickRepeatSec: number; + readonly unstickMaxAttempts: number; + readonly jamRadiusM: number; + readonly jamCostMul: number; + readonly jamTtlSec: number; + readonly rubbleRadiusM: number; + readonly rubbleCostMul: number; + readonly rubbleTtlSec: number; + readonly wreckRadiusM: number; + readonly wreckCostMul: number; + readonly wreckTtlSec: number; +} + export const GROUND_AI_NAV_COST_KEYS = [ 'road', 'bridge', 'ground', 'rough', 'forest', 'crushable', 'shallowWater', 'chokepoint', ] as const satisfies readonly (keyof GroundAiNavCosts)[]; @@ -106,12 +146,8 @@ export interface GroundAiConfig { readonly steerSign: 1 | -1; readonly deadEchoSec: number; readonly controlTimeoutSec: number; - readonly cornerBrakeAccel: number; readonly movingFireSpeedRampMps: number; readonly pivotAngleDeg: number; - readonly stuckWindowSec: number; - readonly stuckMinMoveM: number; - readonly unstickReverseSec: number; readonly tacticalReverseDistM: number; readonly tacticalReverseMaxSec: number; }; @@ -120,9 +156,21 @@ export interface GroundAiConfig { readonly enabled: boolean; readonly allowFallback: boolean; readonly snapRadiusM: number; + /** Farther goal snap when a goal misses snapRadiusM (positions picked off the mesh). */ + readonly goalSnapRadiusM: number; + /** Time queued path searches may take per game frame. */ + readonly pathBudgetMsPerFrame: number; }; readonly navCostsTracked: GroundAiNavCosts; readonly navCostsWheeled: GroundAiNavCosts; + readonly pathFollow: GroundAiPathFollow; + /** + * Bake-time values the runtime must agree with (the rest of navBake is read by tools/navgen): + * riExtra objects up to this stock hp are crushable, so the bumper rays drive through them. + */ + readonly navBake: { + readonly crushableMaxRiExtraHp: number; + }; readonly perception: { readonly foliageTransparency: number; readonly nearSpotRangeM: number; @@ -298,19 +346,19 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['WTO_AI_NAV_STEER_SIGN', 'float', c.navigation.steerSign], ['WTO_AI_NAV_DEAD_ECHO_SEC', 'float', c.navigation.deadEchoSec], ['WTO_AI_NAV_CONTROL_TIMEOUT_SEC', 'float', c.navigation.controlTimeoutSec], - ['WTO_AI_NAV_CORNER_BRAKE_ACCEL', 'float', c.navigation.cornerBrakeAccel], ['WTO_AI_NAV_MOVING_FIRE_SPEED_RAMP_MPS', 'float', c.navigation.movingFireSpeedRampMps], ['WTO_AI_NAV_PIVOT_ANGLE_DEG', 'float', c.navigation.pivotAngleDeg], - ['WTO_AI_NAV_STUCK_WINDOW_SEC', 'float', c.navigation.stuckWindowSec], - ['WTO_AI_NAV_STUCK_MIN_MOVE_M', 'float', c.navigation.stuckMinMoveM], - ['WTO_AI_NAV_UNSTICK_REV_SEC', 'float', c.navigation.unstickReverseSec], ['WTO_AI_NAV_TAC_REV_DIST_M', 'float', c.navigation.tacticalReverseDistM], ['WTO_AI_NAV_TAC_REV_MAX_SEC', 'float', c.navigation.tacticalReverseMaxSec], ['WTO_AI_NAVMESH_ENABLED', 'bool', c.navEngine.enabled], ['WTO_AI_NAVMESH_ALLOW_FALLBACK', 'bool', c.navEngine.allowFallback], ['WTO_AI_NAVMESH_SNAP_M', 'float', c.navEngine.snapRadiusM], + ['WTO_AI_NAVMESH_GOAL_SNAP_M', 'float', c.navEngine.goalSnapRadiusM], + ['WTO_AI_NAVMESH_PATH_BUDGET_US', 'float', c.navEngine.pathBudgetMsPerFrame * 1000], ...navCostEntries('T', c.navCostsTracked), ...navCostEntries('W', c.navCostsWheeled), + ...pathFollowEntries(c.pathFollow), + ['WTO_AI_NAVBAKE_CRUSH_MAX_HP', 'float', c.navBake.crushableMaxRiExtraHp], ['WTO_AI_PERC_FOLIAGE_TRANS', 'float', c.perception.foliageTransparency], ['WTO_AI_PERC_NEAR_SPOT_M', 'float', c.perception.nearSpotRangeM], ['WTO_AI_PERC_FIRING_SPOT_M', 'float', c.perception.firingSpotRangeM], @@ -387,6 +435,48 @@ function navCostEntries(prefix: 'T' | 'W', costs: GroundAiNavCosts): readonly Da ]); } +/** WTO_AI_PF_* constants of the path following, avoidance and unstick modules. */ +function pathFollowEntries(p: GroundAiPathFollow): readonly DasEntry[] { + return [ + ['WTO_AI_PF_REPLAN_SEC', 'float', p.replanIntervalSec], + ['WTO_AI_PF_REPLAN_GOAL_MOVE_M', 'float', p.replanGoalMoveM], + ['WTO_AI_PF_OFF_TRACK_REPLAN_M', 'float', p.offCorridorReplanM], + ['WTO_AI_PF_LOOKAHEAD_SEC', 'float', p.lookaheadTimeSec], + ['WTO_AI_PF_TRACKED_LOOK_MIN_M', 'float', p.trackedLookaheadMinM], + ['WTO_AI_PF_TRACKED_LOOK_MAX_M', 'float', p.trackedLookaheadMaxM], + ['WTO_AI_PF_WHEELED_LOOK_MIN_M', 'float', p.wheeledLookaheadMinM], + ['WTO_AI_PF_WHEELED_LOOK_MAX_M', 'float', p.wheeledLookaheadMaxM], + ['WTO_AI_PF_CORNER_ANGLE_DEG', 'float', p.cornerAngleDeg], + ['WTO_AI_PF_CORNER_LAT_ACCEL', 'float', p.cornerLateralAccelMps2], + ['WTO_AI_PF_BRAKE_DECEL', 'float', p.cornerBrakeDecelMps2], + ['WTO_AI_PF_ARRIVE_RADIUS_M', 'float', p.arriveRadiusM], + ['WTO_AI_PF_ARRIVE_MIN_MPS', 'float', p.arriveMinSpeedMps], + ['WTO_AI_PF_NARROW_WALL_M', 'float', p.narrowWallMarginM], + ['WTO_AI_PF_NARROW_SPEED_MPS', 'float', p.narrowSpeedMps], + ['WTO_AI_PF_BUMPER_RAY_M', 'float', p.bumperRayM], + ['WTO_AI_PF_BUMPER_STOP_M', 'float', p.bumperStopM], + ['WTO_AI_PF_BUMPER_BLOCK_SEC', 'float', p.bumperBlockSec], + ['WTO_AI_PF_TRAFFIC_TTC_SEC', 'float', p.trafficTtcSec], + ['WTO_AI_PF_AVOID_SHIFT_M', 'float', p.avoidShiftM], + ['WTO_AI_PF_YIELD_WAIT_SEC', 'float', p.yieldWaitMaxSec], + ['WTO_AI_PF_STUCK_WINDOW_SEC', 'float', p.stuckWindowSec], + ['WTO_AI_PF_STUCK_MIN_PROGRESS_M', 'float', p.stuckMinProgressM], + ['WTO_AI_PF_UNSTICK_REV_M', 'float', p.unstickReverseM], + ['WTO_AI_PF_UNSTICK_REV_SEC', 'float', p.unstickReverseSec], + ['WTO_AI_PF_UNSTICK_REPEAT_SEC', 'float', p.unstickRepeatSec], + ['WTO_AI_PF_UNSTICK_MAX_ATTEMPTS', 'int', p.unstickMaxAttempts], + ['WTO_AI_PF_JAM_RADIUS_M', 'float', p.jamRadiusM], + ['WTO_AI_PF_JAM_COST_MUL', 'float', p.jamCostMul], + ['WTO_AI_PF_JAM_TTL_SEC', 'float', p.jamTtlSec], + ['WTO_AI_PF_RUBBLE_RADIUS_M', 'float', p.rubbleRadiusM], + ['WTO_AI_PF_RUBBLE_COST_MUL', 'float', p.rubbleCostMul], + ['WTO_AI_PF_RUBBLE_TTL_SEC', 'float', p.rubbleTtlSec], + ['WTO_AI_PF_WRECK_RADIUS_M', 'float', p.wreckRadiusM], + ['WTO_AI_PF_WRECK_COST_MUL', 'float', p.wreckCostMul], + ['WTO_AI_PF_WRECK_TTL_SEC', 'float', p.wreckTtlSec], + ]; +} + function formatDasLiteral(name: string, kind: 'bool' | 'int' | 'float' | 'string', value: boolean | number | string): string { if (kind === 'bool') { if (typeof value !== 'boolean') throw new Error(`ground AI config ${name} must be boolean`); diff --git a/packages/patcher/src/index.ts b/packages/patcher/src/index.ts index f820fb3..3296136 100644 --- a/packages/patcher/src/index.ts +++ b/packages/patcher/src/index.ts @@ -77,6 +77,7 @@ export { type GroundAiLoadoutConfig, type GroundAiMode, type GroundAiNavCosts, + type GroundAiPathFollow, } from './ground-ai/ground-ai-config.ts'; export { rebuildGuiPack, type AppliedGuiPatch, type GuiPackResult } from './gui-pack.ts'; export { loadGuiPatches, type GuiScriptEdit, type GuiScriptPatch, type GuiScriptVariant } from './gui-patch-definition.ts'; From 413bd55c546821e94a181dbf57d228412b6aa296 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sat, 5 Dec 2026 21:39:07 +0800 Subject: [PATCH 08/19] fix(ground-ai): spread team routes, pass vehicles and keep off deep water First in-game run of the path follower on Berlin and Poland showed whole teams queueing on one road, bots ramming stopped teammates and wrecks, bots clipping building corners, bots sliding into the Poland river and the same bot getting stuck at the same spot dozens of times. Native engine (native/wto-nav): - Team traffic: a bot's finished path counts for its team for trafficHoldSec; the team's later searches pay trafficCostPerPath more per counted path through a polygon (up to trafficCostMaxMul), so teammates spread over parallel routes. A slot's previous path stops counting when it asks for a new one. - Path corners are moved up to cornerOffsetM away from the edge they turn around, when the mesh allows both legs; off-mesh link endpoints stay put. - path_request takes the team; load_map takes the new settings; get_stats reports live traffic paths and moved corners. Bake (tools/navgen): - Water deeper than navBake.maxFordDepthM (0.9 m, was a fixed 0.6 m) is a wall before erosion, so walkable ground keeps the tier radius from it, plus deepWaterMarginM on banks lower than deepWaterBankHeightM above the water line. Quays and ramps above it keep only the radius. The preview marks deep water from the terrain. Ground AI scripts: - The lookahead point is pulled back along the path until the mesh allows the straight line to it, so corners are no longer cut through buildings. - New traffic module replaces the fixed sideways step: hull length and width along the heading; stopped vehicles, wrecks and parked players are passed on the side with room, or the bot stops short and after blockWaitSec marks the spot and plans again; moving traffic ahead is followed; oncoming traffic is passed in the open and in narrow passages the bigger vehicle goes first. Wrecks carry their heading. - A hull pressed against a vehicle or wreck backs off after contactReverseSec instead of the full stuck window. - Jams and confirmed obstacles cost far more, and a given-up place is all but closed (giveUpRadiusM, giveUpCostMul), so replanning leaves instead of returning to it. Tuning: navEngine trafficCostPerPath, trafficCostMaxMul, trafficHoldSec, cornerOffsetM; pathFollow stationarySpeedMps, passMarginM, passSpeedMps, blockWaitSec, blockTtlSec, contactGapM, contactReverseSec, giveUpRadiusM, giveUpCostMul; avoidShiftM removed; jamCostMul 4 -> 12, rubbleCostMul 8 -> 25; navBake maxFordDepthM, deepWaterMarginM, deepWaterBankHeightM (bake only). Launcher fields and en/zh-CN labels updated (978/978 keys). Checked: root and launcher typecheck, MSVC build with no warnings in project code, check-patches for 2.61.0.58 and 2.61.0.60, rebake of avg_berlin, avg_poland and avg_hurtgen (all spawn-to-zone pairs still connected on every tier), offline run on the new avg_poland pack (eight same-team paths spread over different roads, traffic released after the hold time, corners moved, pump within budget), isolated game copy build. daScript compilation and in-battle behaviour still need the in-game run. --- .../src/renderer/src/i18n/locales/en.json | 18 +- .../src/renderer/src/i18n/locales/zh-CN.json | 18 +- .../src/pages/tuning/bot-tuning-fields.ts | 14 +- apps/launcher/src/shared/schemas/tuning.ts | 14 +- apps/server/src/tuning/ground-ai-tuning.ts | 14 +- apps/server/tuning/ground-ai.jsonc | 43 +++- game-ai/ground/wto_ai_avoid_common.das | 102 +------- game-ai/ground/wto_ai_lanes_build_common.das | 6 +- game-ai/ground/wto_ai_nav_common.das | 45 ++-- game-ai/ground/wto_ai_nav_types_common.das | 9 +- game-ai/ground/wto_ai_navmesh_common.das | 15 +- game-ai/ground/wto_ai_navquery_common.das | 6 +- game-ai/ground/wto_ai_route_common.das | 2 +- game-ai/ground/wto_ai_traffic_common.das | 239 ++++++++++++++++++ game-ai/ground/wto_ai_types_common.das | 1 + game-ai/ground/wto_ai_unstick_common.das | 13 +- game-ai/ground/wto_ai_world_common.das | 1 + native/wto-nav/wto_nav_internal.h | 18 +- native/wto-nav/wto_nav_paths.cpp | 160 +++++++++++- native/wto-nav/wto_nav_runtime.cpp | 62 ++++- native/wto-nav/wto_nav_runtime.h | 19 ++ native/wto-net/src/local_mp_nav.c | 28 +- .../patcher/src/ground-ai/ground-ai-config.ts | 30 ++- tools/navgen/bake/bake.cpp | 98 ++++++- tools/navgen/mission-bounds.mts | 3 + 25 files changed, 817 insertions(+), 161 deletions(-) create mode 100644 game-ai/ground/wto_ai_traffic_common.das diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 7642034..34e5f6a 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -534,7 +534,7 @@ "fireControl": "Range bands, speed gates, barrel settle and ballistic safety", "navigation": "Drive backend, pivot turns and tactical reverse", "navEngine": "Baked map navigation packs, their fallback, and path costs per surface for tracked and wheeled vehicles", - "pathFollow": "Replanning, lookahead steering, corner and arrival braking, narrow passages, bumper rays, traffic yielding, three-level unstick and temporary path costs", + "pathFollow": "Replanning, lookahead steering, corner and arrival braking, narrow passages, bumper rays, passing stopped vehicles and wrecks, giving way, three-level unstick and temporary path costs", "crowd": "Personal space and ally cluster dispersal", "terrain": "Climb/drop slope limits, water depth and ridge peek caps", "runtime": "Script update intervals and telemetry logging" @@ -682,7 +682,11 @@ "allowFallback": "Fall back to the old pathing for the battle when a pack is missing or broken", "snapRadiusM": "Max distance from a path's start or goal to the mesh", "goalSnapRadiusM": "Max distance a path goal may be moved onto the mesh", - "pathBudgetMsPerFrame": "Path search time per frame" + "pathBudgetMsPerFrame": "Path search time per frame", + "trafficCostPerPath": "Team traffic · extra path cost per teammate route", + "trafficCostMaxMul": "Team traffic · max path cost multiplier", + "trafficHoldSec": "Team traffic · how long a planned route counts", + "cornerOffsetM": "Distance path corners keep from the walls they turn around" }, "navCostsTracked": { "road": "Tracked · road cost", @@ -724,8 +728,14 @@ "bumperStopM": "Stop distance before an obstacle hit by the front rays", "bumperBlockSec": "Time blocked before an obstacle is reported", "trafficTtcSec": "Vehicle collision look-ahead time", - "avoidShiftM": "Sideways step around vehicles and wrecks", "yieldWaitMaxSec": "Max wait while giving way in narrow passages", + "stationarySpeedMps": "Speed below which a vehicle counts as an obstacle", + "passMarginM": "Gap kept between hulls when passing", + "passSpeedMps": "Speed cap while passing an obstacle", + "blockWaitSec": "Wait before a blocked passage is marked and replanned", + "blockTtlSec": "Blocked passage cost duration", + "contactGapM": "Gap to an obstacle that counts as contact", + "contactReverseSec": "Time in contact before backing off", "stuckWindowSec": "Stuck detection window", "stuckMinProgressM": "Min progress within the stuck window", "unstickReverseM": "Unstick reverse distance", @@ -735,6 +745,8 @@ "jamRadiusM": "Jam cost radius", "jamCostMul": "Jam path cost multiplier", "jamTtlSec": "Jam cost duration", + "giveUpRadiusM": "Given-up place cost radius", + "giveUpCostMul": "Given-up place path cost multiplier", "rubbleRadiusM": "Fresh obstacle cost radius", "rubbleCostMul": "Fresh obstacle path cost multiplier", "rubbleTtlSec": "Fresh obstacle cost duration", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index 94ee57a..2f0f6d2 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -534,7 +534,7 @@ "fireControl": "距离分档、车速门槛、稳定等待与弹道防误伤", "navigation": "驱动方式、原地转向与战术倒车", "navEngine": "离线地图导航包的启用与降级,以及履带 / 轮式车在各类地表上的寻路代价", - "pathFollow": "重新寻路、前瞻跟路、弯道与到达前减速、窄路限速、车头射线、会车让路、三级脱困与临时寻路代价", + "pathFollow": "重新寻路、前瞻跟路、弯道与到达前减速、窄路限速、车头射线、绕过停车和残骸、会车让路、三级脱困与临时寻路代价", "crowd": "友军安全间距与扎堆疏散", "terrain": "爬坡 / 下坡角度、涉水深度与探头限制", "runtime": "脚本刷新间隔与调试遥测日志" @@ -682,7 +682,11 @@ "allowFallback": "缺少或损坏时整局退回旧寻路", "snapRadiusM": "起终点吸附到导航网格的最大距离", "goalSnapRadiusM": "目标点吸附到导航网格的最远距离", - "pathBudgetMsPerFrame": "每帧寻路计算时间上限" + "pathBudgetMsPerFrame": "每帧寻路计算时间上限", + "trafficCostPerPath": "同队分流 · 每条队友路线增加的寻路代价", + "trafficCostMaxMul": "同队分流 · 寻路代价最高倍率", + "trafficHoldSec": "同队分流 · 规划出的路线计入多久", + "cornerOffsetM": "路线拐点离所绕墙角的距离" }, "navCostsTracked": { "road": "履带车 · 道路代价", @@ -724,8 +728,14 @@ "bumperStopM": "车头射线碰到障碍时的停车距离", "bumperBlockSec": "被挡多久后上报障碍", "trafficTtcSec": "车辆碰撞预判时间", - "avoidShiftM": "绕开车辆和残骸的横移距离", "yieldWaitMaxSec": "窄路让路最长等待时间", + "stationarySpeedMps": "车速低于多少算作障碍物", + "passMarginM": "绕行时与对方车体保持的间距", + "passSpeedMps": "绕行障碍时的限速", + "blockWaitSec": "无路可绕时等待多久后标记并重新寻路", + "blockTtlSec": "被堵路段代价持续时间", + "contactGapM": "离障碍多近算作顶上", + "contactReverseSec": "顶上多久后倒车", "stuckWindowSec": "卡住检测窗口时长", "stuckMinProgressM": "检测窗口内的最小前进距离", "unstickReverseM": "脱困倒车距离", @@ -735,6 +745,8 @@ "jamRadiusM": "堵车点代价半径", "jamCostMul": "堵车点寻路代价倍率", "jamTtlSec": "堵车点代价持续时间", + "giveUpRadiusM": "放弃地点代价半径", + "giveUpCostMul": "放弃地点寻路代价倍率", "rubbleRadiusM": "新障碍代价半径", "rubbleCostMul": "新障碍寻路代价倍率", "rubbleTtlSec": "新障碍代价持续时间", diff --git a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts index f94425d..b9325f5 100644 --- a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts +++ b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts @@ -278,6 +278,10 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ num('navEngine', 'snapRadiusM', 2, 40, 'm'), num('navEngine', 'goalSnapRadiusM', 5, 150, 'm'), num('navEngine', 'pathBudgetMsPerFrame', 0.05, 5, 'ms'), + num('navEngine', 'trafficCostPerPath', 0, 3), + num('navEngine', 'trafficCostMaxMul', 1, 10), + num('navEngine', 'trafficHoldSec', 0, 120, 's'), + num('navEngine', 'cornerOffsetM', 0, 5, 'm'), ...NAV_COST_FIELDS.map((field) => num('navCostsTracked', field, 0.1, 20)), ...NAV_COST_FIELDS.map((field) => num('navCostsWheeled', field, 0.1, 20)), ], @@ -306,8 +310,14 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ num('pathFollow', 'bumperStopM', 0.3, 6, 'm'), num('pathFollow', 'bumperBlockSec', 0.2, 5, 's'), num('pathFollow', 'trafficTtcSec', 0.5, 8, 's'), - num('pathFollow', 'avoidShiftM', 0.5, 10, 'm'), num('pathFollow', 'yieldWaitMaxSec', 0.5, 15, 's'), + num('pathFollow', 'stationarySpeedMps', 0.2, 4, 'm/s'), + num('pathFollow', 'passMarginM', 0.2, 4, 'm'), + num('pathFollow', 'passSpeedMps', 1, 12, 'm/s'), + num('pathFollow', 'blockWaitSec', 0.5, 15, 's'), + num('pathFollow', 'blockTtlSec', 3, 120, 's'), + num('pathFollow', 'contactGapM', 0.2, 3, 'm'), + num('pathFollow', 'contactReverseSec', 0.3, 5, 's'), num('pathFollow', 'stuckWindowSec', 1, 15, 's'), num('pathFollow', 'stuckMinProgressM', 0.2, 10, 'm'), num('pathFollow', 'unstickReverseM', 2, 25, 'm'), @@ -317,6 +327,8 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ num('pathFollow', 'jamRadiusM', 2, 50, 'm'), num('pathFollow', 'jamCostMul', 1, 50), num('pathFollow', 'jamTtlSec', 5, 600, 's'), + num('pathFollow', 'giveUpRadiusM', 3, 50, 'm'), + num('pathFollow', 'giveUpCostMul', 1, 200), num('pathFollow', 'rubbleRadiusM', 1, 40, 'm'), num('pathFollow', 'rubbleCostMul', 1, 50), num('pathFollow', 'rubbleTtlSec', 5, 600, 's'), diff --git a/apps/launcher/src/shared/schemas/tuning.ts b/apps/launcher/src/shared/schemas/tuning.ts index be651db..94b4217 100644 --- a/apps/launcher/src/shared/schemas/tuning.ts +++ b/apps/launcher/src/shared/schemas/tuning.ts @@ -102,6 +102,10 @@ const GroundAiNavEngineSchema = z.object({ snapRadiusM: z.number().min(2).max(40), goalSnapRadiusM: z.number().min(5).max(150), pathBudgetMsPerFrame: z.number().min(0.05).max(5), + trafficCostPerPath: z.number().min(0).max(3), + trafficCostMaxMul: z.number().min(1).max(10), + trafficHoldSec: z.number().min(0).max(120), + cornerOffsetM: z.number().min(0).max(5), }); const navCost = z.number().min(0.1).max(20); @@ -136,8 +140,14 @@ const GroundAiPathFollowSchema = z.object({ bumperStopM: z.number().min(0.3).max(6), bumperBlockSec: z.number().min(0.2).max(5), trafficTtcSec: z.number().min(0.5).max(8), - avoidShiftM: z.number().min(0.5).max(10), yieldWaitMaxSec: z.number().min(0.5).max(15), + stationarySpeedMps: z.number().min(0.2).max(4), + passMarginM: z.number().min(0.2).max(4), + passSpeedMps: z.number().min(1).max(12), + blockWaitSec: z.number().min(0.5).max(15), + blockTtlSec: z.number().min(3).max(120), + contactGapM: z.number().min(0.2).max(3), + contactReverseSec: z.number().min(0.3).max(5), stuckWindowSec: z.number().min(1).max(15), stuckMinProgressM: z.number().min(0.2).max(10), unstickReverseM: z.number().min(2).max(25), @@ -147,6 +157,8 @@ const GroundAiPathFollowSchema = z.object({ jamRadiusM: z.number().min(2).max(50), jamCostMul: z.number().min(1).max(50), jamTtlSec: z.number().min(5).max(600), + giveUpRadiusM: z.number().min(3).max(50), + giveUpCostMul: z.number().min(1).max(200), rubbleRadiusM: z.number().min(1).max(40), rubbleCostMul: z.number().min(1).max(50), rubbleTtlSec: z.number().min(5).max(600), diff --git a/apps/server/src/tuning/ground-ai-tuning.ts b/apps/server/src/tuning/ground-ai-tuning.ts index 53c7014..1d94c8c 100644 --- a/apps/server/src/tuning/ground-ai-tuning.ts +++ b/apps/server/src/tuning/ground-ai-tuning.ts @@ -189,6 +189,10 @@ function readNavEngineSection(engine: TuningReader): GroundAiTuning['navEngine'] snapRadiusM: engine.number('snapRadiusM', { min: 2, max: 40 }), goalSnapRadiusM: engine.number('goalSnapRadiusM', { min: 5, max: 150 }), pathBudgetMsPerFrame: engine.number('pathBudgetMsPerFrame', { min: 0.05, max: 5 }), + trafficCostPerPath: engine.number('trafficCostPerPath', { min: 0, max: 3 }), + trafficCostMaxMul: engine.number('trafficCostMaxMul', { min: 1, max: 10 }), + trafficHoldSec: engine.number('trafficHoldSec', { min: 0, max: 120 }), + cornerOffsetM: engine.number('cornerOffsetM', { min: 0, max: 5 }), }; } @@ -234,8 +238,14 @@ function readPathFollowSection(pf: TuningReader): GroundAiPathFollow { bumperStopM: n('bumperStopM', 0.3, 6), bumperBlockSec: n('bumperBlockSec', 0.2, 5), trafficTtcSec: n('trafficTtcSec', 0.5, 8), - avoidShiftM: n('avoidShiftM', 0.5, 10), yieldWaitMaxSec: n('yieldWaitMaxSec', 0.5, 15), + stationarySpeedMps: n('stationarySpeedMps', 0.2, 4), + passMarginM: n('passMarginM', 0.2, 4), + passSpeedMps: n('passSpeedMps', 1, 12), + blockWaitSec: n('blockWaitSec', 0.5, 15), + blockTtlSec: n('blockTtlSec', 3, 120), + contactGapM: n('contactGapM', 0.2, 3), + contactReverseSec: n('contactReverseSec', 0.3, 5), stuckWindowSec: n('stuckWindowSec', 1, 15), stuckMinProgressM: n('stuckMinProgressM', 0.2, 10), unstickReverseM: n('unstickReverseM', 2, 25), @@ -245,6 +255,8 @@ function readPathFollowSection(pf: TuningReader): GroundAiPathFollow { jamRadiusM: n('jamRadiusM', 2, 50), jamCostMul: n('jamCostMul', 1, 50), jamTtlSec: n('jamTtlSec', 5, 600), + giveUpRadiusM: n('giveUpRadiusM', 3, 50), + giveUpCostMul: n('giveUpCostMul', 1, 200), rubbleRadiusM: n('rubbleRadiusM', 1, 40), rubbleCostMul: n('rubbleCostMul', 1, 50), rubbleTtlSec: n('rubbleTtlSec', 5, 600), diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index 95d6aba..f19fab9 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -113,7 +113,15 @@ // this value (wooden fences 2, dry-stone fences 12, car wrecks 20; buses 40). "crushableMaxRiExtraHp": 20, // Passages narrower than this many standard-tier vehicle widths are flagged as chokepoints. - "chokepointMaxWidthVehicles": 2.0 + "chokepointMaxWidthVehicles": 2.0, + // Water up to maxFordDepthM is forded (shallow water cost). Deeper water is a wall: besides the + // vehicle's half width, the mesh keeps deepWaterMarginM more ground from it where the bank is + // less than deepWaterBankHeightM above the water line, + // because low banks slope into the water and a hull at the water line slides in. Higher quays + // and ramps keep only the half width. + "maxFordDepthM": 0.9, + "deepWaterMarginM": 1.5, + "deepWaterBankHeightM": 1.0 }, "navigation": { @@ -144,7 +152,15 @@ // goal counts as unreachable. Also used to find the way back onto the mesh. "goalSnapRadiusM": 40.0, // Path searches are spread over frames; this is the search time allowed per frame. - "pathBudgetMsPerFrame": 0.5 + "pathBudgetMsPerFrame": 0.5, + // Team traffic: each teammate path planned within trafficHoldSec through a stretch of mesh + // raises its cost for the team's next searches by trafficCostPerPath, up to trafficCostMaxMul, + // so a team spreads over parallel routes instead of queueing on one road. + "trafficCostPerPath": 0.35, + "trafficCostMaxMul": 2.5, + "trafficHoldSec": 12.0, + // Path corners are moved this far away from the building or wall they turn around. + "cornerOffsetM": 1.5 }, // Path cost multipliers per surface for tracked vehicles; chokepoint multiplies the surface cost @@ -199,10 +215,21 @@ "bumperRayM": 7.0, "bumperStopM": 1.5, "bumperBlockSec": 0.6, - // Vehicles and wrecks that come within reach in trafficTtcSec: follow, step aside, or give way. + // Moving vehicles that come within reach in trafficTtcSec: follow them, or in narrow passages + // give way to the bigger one for at most yieldWaitMaxSec. "trafficTtcSec": 2.5, - "avoidShiftM": 3.0, "yieldWaitMaxSec": 3.0, + // Vehicles slower than stationarySpeedMps, wrecks and players' vehicles in the way are passed + // on the side the mesh leaves room, keeping passMarginM between hulls, at up to passSpeedMps. + "stationarySpeedMps": 1.0, + "passMarginM": 0.8, + "passSpeedMps": 4.0, + // No side free: stop short, and after blockWaitSec mark the obstacle for path searches for + // blockTtlSec and plan again. A hull within contactGapM of it for contactReverseSec backs off. + "blockWaitSec": 2.0, + "blockTtlSec": 15.0, + "contactGapM": 0.8, + "contactReverseSec": 1.0, // Less progress than stuckMinProgressM within stuckWindowSec while wanting to move is stuck. "stuckWindowSec": 3.0, "stuckMinProgressM": 0.8, @@ -211,11 +238,15 @@ "unstickRepeatSec": 8.0, "unstickMaxAttempts": 3, // Temporary path costs: jams found by unstick, fresh obstacles hit by the front rays, wrecks. + // A place given up on after unstickMaxAttempts is all but closed (giveUp*), so the next order + // routes elsewhere instead of returning to it. "jamRadiusM": 10.0, - "jamCostMul": 4.0, + "jamCostMul": 12.0, "jamTtlSec": 45.0, + "giveUpRadiusM": 15.0, + "giveUpCostMul": 40.0, "rubbleRadiusM": 6.0, - "rubbleCostMul": 8.0, + "rubbleCostMul": 25.0, "rubbleTtlSec": 90.0, "wreckRadiusM": 6.0, "wreckCostMul": 6.0, diff --git a/game-ai/ground/wto_ai_avoid_common.das b/game-ai/ground/wto_ai_avoid_common.das index c784f06..650bfbe 100644 --- a/game-ai/ground/wto_ai_avoid_common.das +++ b/game-ai/ground/wto_ai_avoid_common.das @@ -1,8 +1,7 @@ -// Local avoidance on top of the path: what the baked mesh cannot know. Two short physical rays -// from the front corners of the hull catch fresh obstacles (rubble, collapsed buildings) and let -// the vehicle drive through what it can knock down (fences, light walls); a -// time-to-collision check against vehicles and wrecks makes a bot follow slower traffic, step -// aside, or (in narrow passages) wait while the vehicle with priority passes. +// Fresh static obstacles on top of the path: what the baked mesh cannot know. Two short physical +// rays from the front corners of the hull catch rubble and collapsed buildings and let the vehicle +// drive through what it can knock down (fences, light walls). Vehicles and wrecks are handled by +// wto_ai_traffic_common. options indenting = 2 options no_global_heap = true module wto_ai_avoid_common shared @@ -14,9 +13,7 @@ require Dacoll require RendInst require PhysMat require %appGame.wtoai.wto_ai_config_common -require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_types_common -require %appGame.wtoai.wto_ai_nav_types_common let private AVOID_STATIC_MASK = ETF_STRUCTURES | ETF_FRT @@ -83,94 +80,3 @@ def public wto_avoid_bumper(myPos, dir : float3; spec : WtoVehicleSpec const&) : let clearL = wto_avoid_drive_ray(base + left * side, dir, WTO_AI_PF_BUMPER_RAY_M) let clearR = wto_avoid_drive_ray(base - left * side, dir, WTO_AI_PF_BUMPER_RAY_M) return min(clearL, clearR) - -// Whether another body ahead comes within reach in the next trafficTtcSec; `tHit` is when. -[never_inline] -def private wto_avoid_conflict(myPos, myVel, dir : float3; selfRad : float; otherPos, otherVel : float3; - otherRad : float; var tHit : float&) : bool - let rel = float3(otherPos.x - myPos.x, 0.0, otherPos.z - myPos.z) - if dot(rel, dir) <= 0.0 || dot(rel, rel) > 1600.0 - return false - let relVel = float3(otherVel.x - myVel.x, 0.0, otherVel.z - myVel.z) - let vv = dot(relVel, relVel) - tHit = vv > 0.01 ? clamp(-dot(rel, relVel) / vv, 0.0, WTO_AI_PF_TRAFFIC_TTC_SEC) : 0.0 - let closest = rel + relVel * tHit - let reach = selfRad + otherRad + 0.8 - return dot(closest, closest) < reach * reach - -// Earliest conflict among vehicles and wrecks; -1 when there is none. -[never_inline] -def private wto_avoid_find(world : WtoWorldSnap const&; myPos, dir : float3; speedMps : float; - slot : WtoBotSlot const&; var isWreck : bool&) : int - let selfRad = max(slot.spec.halfWid, 1.2) - let myVel = dir * speedMps - var best = 99.0 - var found = -1 - for i in range(world.unitCount) - assume u = world.units[i] - if !u.isAlive || !u.isGround || u.eid == slot.eid - continue - var tUnit = 0.0 - if wto_avoid_conflict(myPos, myVel, dir, selfRad, u.pos, u.vel, max(u.halfWid, 1.0), tUnit) && tUnit < best - best = tUnit - found = i - isWreck = false - for w in range(world.wreckCount) - var tWreck = 0.0 - let still = float3(0.0, 0.0, 0.0) - if wto_avoid_conflict(myPos, myVel, dir, selfRad, world.wrecks[w].pos, still, max(world.wrecks[w].halfWid, 1.0), tWreck) && tWreck < best - best = tWreck - found = w - isWreck = true - return found - -// The bigger vehicle goes first; equal sizes by entity id. Players always keep their way. -[never_inline] -def private wto_avoid_has_priority(slot : WtoBotSlot const&; other : WtoUnitSnap const&) : bool - if other.isHuman - return false - let mine = slot.spec.halfLen * slot.spec.halfWid - let theirs = other.halfLen * other.halfWid - if abs(mine - theirs) > 0.5 - return mine > theirs - return uint(slot.eid) < uint(other.eid) - -// Waits for the vehicle with priority, at most yieldWaitMaxSec, then not again for as long. -[never_inline] -def private wto_avoid_yield(now : float; var nav : WtoNavState&) - if nav.yieldUntil < now && now >= nav.yieldCooldownUntil - nav.yieldUntil = now + WTO_AI_PF_YIELD_WAIT_SEC - nav.yieldCooldownUntil = nav.yieldUntil + WTO_AI_PF_YIELD_WAIT_SEC - nav.avoidSpeedCap = now < nav.yieldUntil ? 0.0 : 2.0 - -// Sets slot.nav.avoidShiftM (sideways step, left positive) and avoidSpeedCap for this tick. -[never_inline] -def public wto_avoid_traffic(world : WtoWorldSnap const&; now : float; myPos, dir : float3; - speedMps : float; narrow : bool; var slot : WtoBotSlot&) - assume nav = slot.nav - nav.avoidShiftM = 0.0 - nav.avoidSpeedCap = 99.0 - var isWreck = false - let idx = wto_avoid_find(world, myPos, dir, speedMps, slot, isWreck) - if idx < 0 - nav.yieldUntil = -100.0 - return - let otherPos = isWreck ? world.wrecks[idx].pos : world.units[idx].pos - let otherVel = isWreck ? float3(0.0, 0.0, 0.0) : world.units[idx].vel - let along = dot(otherVel, dir) - if !isWreck && along > 1.0 && along > 0.7 * length(otherVel) - let gap = sqrt(wto_xz_dist_sq(myPos, otherPos)) - nav.avoidSpeedCap = along + max(0.0, gap - 12.0) * 0.4 - return - if !isWreck && wto_avoid_has_priority(slot, world.units[idx]) - return - let lateral = dot(otherPos - myPos, float3(-dir.z, 0.0, dir.x)) - if !narrow - nav.avoidShiftM = (lateral >= 0.0 ? -1.0 : 1.0) * WTO_AI_PF_AVOID_SHIFT_M - nav.avoidSpeedCap = max(2.0, speedMps * 0.7) - return - if isWreck - slot.route.replanRequested = true - nav.avoidSpeedCap = 2.0 - return - wto_avoid_yield(now, nav) diff --git a/game-ai/ground/wto_ai_lanes_build_common.das b/game-ai/ground/wto_ai_lanes_build_common.das index d96aa88..a0b5e4a 100644 --- a/game-ai/ground/wto_ai_lanes_build_common.das +++ b/game-ai/ground/wto_ai_lanes_build_common.das @@ -106,9 +106,9 @@ def private wto_lanes_request_legs(world : WtoWorldSnap const&; army, capIdx, k continue lanes.flankRelay[k * 2 + side] = relay lanes.ticket[k * 5 + 1 + side * 2] = wto_navq_path_request(wto_lanes_slot(k, 1 + side * 2), WTO_NAVMESH_TIER_STANDARD, - WTO_NAVMESH_FILTER_TRACKED, world.teamSpawnCenter[army], relay) + WTO_NAVMESH_FILTER_TRACKED, 0, world.teamSpawnCenter[army], relay) lanes.ticket[k * 5 + 2 + side * 2] = wto_navq_path_request(wto_lanes_slot(k, 2 + side * 2), WTO_NAVMESH_TIER_STANDARD, - WTO_NAVMESH_FILTER_TRACKED, relay, world.caps[capIdx].center) + WTO_NAVMESH_FILTER_TRACKED, 0, relay, world.caps[capIdx].center) lanes.phase[k] = WTO_LANES_LEGS // Center path queued: take it once found and queue the flank legs. @@ -166,7 +166,7 @@ def public wto_lanes_ensure_cap(world : WtoWorldSnap const&; army, capIdx : int; return if lanes.phase[k] == WTO_LANES_IDLE lanes.ticket[k * 5] = wto_navq_path_request(wto_lanes_slot(k, 0), WTO_NAVMESH_TIER_STANDARD, WTO_NAVMESH_FILTER_TRACKED, - world.teamSpawnCenter[army], world.caps[capIdx].center) + 0, world.teamSpawnCenter[army], world.caps[capIdx].center) lanes.phase[k] = WTO_LANES_CENTER elif lanes.phase[k] == WTO_LANES_CENTER wto_lanes_mesh_center(world, army, capIdx, k, lanes) diff --git a/game-ai/ground/wto_ai_nav_common.das b/game-ai/ground/wto_ai_nav_common.das index cb614e3..10a34c8 100644 --- a/game-ai/ground/wto_ai_nav_common.das +++ b/game-ai/ground/wto_ai_nav_common.das @@ -1,8 +1,9 @@ // Navigation layer of one bot per nav tick: turns the tactics goal into a drive command. // Stationary and hull-angle states hold or pivot in place; tactical withdrawals and unstick // manoeuvres back up along checked ground; otherwise the bot follows its corridor (route) with a -// lookahead point (follow), slows for corners, narrow passages, traffic and fresh obstacles -// (avoid), and escalates when it stops making progress (unstick). +// lookahead point it can reach in a straight line (follow), passes or follows vehicles and wrecks +// (traffic), slows for corners, narrow passages and fresh obstacles (avoid), backs off at once +// when pressed against a vehicle, and escalates when it stops making progress (unstick). options indenting = 2 options no_global_heap = true module wto_ai_nav_common shared @@ -19,6 +20,7 @@ require %appGame.wtoai.wto_ai_navmesh_common require %appGame.wtoai.wto_ai_route_common require %appGame.wtoai.wto_ai_follow_common require %appGame.wtoai.wto_ai_avoid_common +require %appGame.wtoai.wto_ai_traffic_common require %appGame.wtoai.wto_ai_unstick_common [never_inline] @@ -89,21 +91,23 @@ def private wto_nav_probe_mesh(navState : int; myPos : float3; var slot : WtoBot nav.surfaceArea = probe.area nav.chokepoint = (probe.flags & WTO_NAVQ_FLAG_CHOKEPOINT) != 0 -// A sideways step is taken only when the mesh allows the straight line to it. +// Lookahead point the bot can drive to in a straight line: around a corner the full lookahead +// would cut through the building the path turns around, so it is pulled back along the path +// until the mesh allows the straight line, at worst to the next path corner. [never_inline] -def private wto_nav_apply_shift(navState : int; myPos, target, dir : float3; var slot : WtoBotSlot&) : float3 - let shift = slot.nav.avoidShiftM - if abs(shift) < 0.01 +def private wto_nav_visible_target(navState : int; myPos : float3; lookM : float; slot : WtoBotSlot const&) : float3 + assume rt = slot.route + var look = lookM + var target = wto_follow_target(rt, look) + if navState != WTO_NAVMESH_LOADED || rt.tier < 0 || rt.source != WTO_ROUTE_SRC_MESH return target - let shifted = target + float3(-dir.z, 0.0, dir.x) * shift - if navState != WTO_NAVMESH_LOADED || slot.route.tier < 0 - return shifted - var frac = 0.0 - if wto_navq_raycast(slot.route.tier, slot.route.filter, myPos, shifted, frac) != 0 - return shifted - slot.nav.avoidShiftM = 0.0 - slot.nav.avoidSpeedCap = min(slot.nav.avoidSpeedCap, 2.0) - return target + for _try in range(3) + var frac = 0.0 + if wto_navq_raycast(rt.tier, rt.filter, myPos, target, frac) != 0 + return target + look *= 0.5 + target = wto_follow_target(rt, look) + return rt.corridor[min(rt.segIdx + 1, rt.corridorLen - 1)] // A fresh obstacle in front for bumperBlockSec: mark it for path searches and plan again. [never_inline] @@ -148,11 +152,16 @@ def private wto_nav_follow(var world : WtoWorldSnap&; navState : int; now : floa wto_follow_track(myPos, rt) let speedNow = abs(slot.drive.lastVFwd) let lookM = wto_follow_lookahead(slot.spec, speedNow) - let pathTarget = wto_follow_target(rt, lookM) + let pathTarget = wto_nav_visible_target(navState, myPos, lookM, slot) let pathDir = wto_xz_normalize(pathTarget - myPos, hullFwd) let narrow = slot.nav.wallDistM < WTO_AI_PF_NARROW_WALL_M || slot.nav.chokepoint - wto_avoid_traffic(world, now, myPos, pathDir, speedNow, narrow, slot) - let target = wto_nav_apply_shift(navState, myPos, pathTarget, pathDir, slot) + wto_traffic_update(world, navState, now, myPos, pathDir, speedNow, narrow, slot) + if wto_traffic_in_contact(now, slot.nav) + wto_unstick_contact(navState, now, myPos, hullFwd, slot) + if !wto_unstick_reversing(now, myPos, slot) + wto_nav_halt(myPos, hullFwd, slot) + return + let target = slot.nav.avoidActive ? slot.nav.avoidTarget : pathTarget let dir = wto_xz_normalize(target - myPos, hullFwd) let speed = wto_nav_speed(navState, now, myPos, dir, lookM, narrow, slot) slot.nav.steerDir = dir diff --git a/game-ai/ground/wto_ai_nav_types_common.das b/game-ai/ground/wto_ai_nav_types_common.das index 318f4db..e0bd269 100644 --- a/game-ai/ground/wto_ai_nav_types_common.das +++ b/game-ai/ground/wto_ai_nav_types_common.das @@ -49,8 +49,13 @@ struct public WtoNavState bumperBlockedSince : float = -100.0 yieldUntil : float = -100.0 yieldCooldownUntil : float = -100.0 - avoidShiftM : float = 0.0 + avoidActive : bool = false + avoidTarget : float3 = float3(0.0, 0.0, 0.0) + avoidSide : float = 0.0 + avoidSideUntil : float = -100.0 avoidSpeedCap : float = 99.0 + blockedSince : float = -100.0 + contactSince : float = -100.0 stuckOrigin : float3 = float3(0.0, 0.0, 0.0) stuckCheckAt : float = -100.0 unstickAnchor : float3 = float3(0.0, 0.0, 0.0) @@ -61,5 +66,7 @@ struct public WtoNavState reverseUntil : float = -100.0 reverseCount : int = 0 unstickEvents : int = 0 + contactEvents : int = 0 + blockEvents : int = 0 unreachableEvents : int = 0 ridgeWithdrawEvents : int = 0 diff --git a/game-ai/ground/wto_ai_navmesh_common.das b/game-ai/ground/wto_ai_navmesh_common.das index e14f978..6e17912 100644 --- a/game-ai/ground/wto_ai_navmesh_common.das +++ b/game-ai/ground/wto_ai_navmesh_common.das @@ -52,6 +52,14 @@ def private wto_navmesh_add_costs(var blk : DataBlock&) add(blk, "w_shallowWater", "{WTO_AI_NAVMESH_W_SHALLOW_WATER}") add(blk, "w_chokepoint", "{WTO_AI_NAVMESH_W_CHOKEPOINT}") +// Team traffic and corner offset of the battle's searches. +[never_inline] +def private wto_navmesh_add_tuning(var blk : DataBlock&) + add(blk, "trafficPerPath", "{WTO_AI_NAVMESH_TRAFFIC_PER_PATH}") + add(blk, "trafficMaxMul", "{WTO_AI_NAVMESH_TRAFFIC_MAX_MUL}") + add(blk, "trafficHoldSec", "{WTO_AI_NAVMESH_TRAFFIC_HOLD_SEC}") + add(blk, "cornerOffset", "{WTO_AI_NAVMESH_CORNER_OFFSET_M}") + // Battle loading: start reading this battle's pack on a background thread. [never_inline] def public wto_navmesh_prefetch() @@ -76,6 +84,7 @@ def public wto_navmesh_load() : int add(blk, "op", "load_map") add(blk, "allowFallback", WTO_AI_NAVMESH_ALLOW_FALLBACK ? "1" : "0") wto_navmesh_add_costs(blk) + wto_navmesh_add_tuning(blk) call_mission_action("wtoNav", blk) let answer = datablock_getStr(blk, "state", "") if answer == "loaded" @@ -115,7 +124,7 @@ def private wto_navmesh_self_test(world : WtoWorldSnap const&; var nm : WtoNavme return for army in range(1, 3) nm.selfTestTicket[army] = wto_navq_path_request(WTO_NAVQ_SELFTEST_SLOT0 + army - 1, WTO_NAVMESH_TIER_STANDARD, - WTO_NAVMESH_FILTER_TRACKED, world.teamSpawnCenter[army], world.caps[0].center) + WTO_NAVMESH_FILTER_TRACKED, 0, world.teamSpawnCenter[army], world.caps[0].center) nm.selfTestPhase = 1 return if nm.selfTestPhase != 1 @@ -176,4 +185,6 @@ def public wto_navmesh_log_stats(var nm : WtoNavmeshBattle&) let pumpMaxUs = datablock_getInt(blk, "pumpMaxUs", 0) let pending = datablock_getInt(blk, "pending", 0) let dynCount = datablock_getInt(blk, "dynamic", 0) - print("WTO_AI|NAVMESH_STATS|paths={queries}|failures={failures}|avgUs={avgUs}|maxUs={maxUs}|maxFrames={maxFrames}|pumpMaxUs={pumpMaxUs}|pending={pending}|dynamic={dynCount}|meshQueries={meshQueries}\n") + let traffic = datablock_getInt(blk, "traffic", 0) + let moved = datablock_getInt(blk, "cornersMoved", 0) + print("WTO_AI|NAVMESH_STATS|paths={queries}|failures={failures}|avgUs={avgUs}|maxUs={maxUs}|maxFrames={maxFrames}|pumpMaxUs={pumpMaxUs}|pending={pending}|dynamic={dynCount}|meshQueries={meshQueries}|traffic={traffic}|cornersMoved={moved}\n") diff --git a/game-ai/ground/wto_ai_navquery_common.das b/game-ai/ground/wto_ai_navquery_common.das index ffac737..626f01b 100644 --- a/game-ai/ground/wto_ai_navquery_common.das +++ b/game-ai/ground/wto_ai_navquery_common.das @@ -65,15 +65,17 @@ def private wto_navq_get_point(blk : DataBlock const&; kx, ky, kz : string) : fl let z = float(datablock_getInt(blk, kz, 0)) * 0.01 return float3(x, y, z) -// Queues a path search in native slot `slot`; returns its ticket (0 when refused). +// Queues a path search in native slot `slot`; returns its ticket (0 when refused). With a team +// (`group` 1 or 2) the search avoids routes teammates planned recently and counts as one itself. [never_inline] -def public wto_navq_path_request(slot, tier, costFilter : int; start, goal : float3) : int +def public wto_navq_path_request(slot, tier, costFilter, group : int; start, goal : float3) : int var ticket = 0 using() <| $(var blk : DataBlock) add(blk, "op", "path_request") add(blk, "slot", "{slot}") add(blk, "tier", "{tier}") add(blk, "filter", "{costFilter}") + add(blk, "group", "{group}") add(blk, "snap", "{WTO_AI_NAVMESH_SNAP_M}") add(blk, "goalSnap", "{WTO_AI_NAVMESH_GOAL_SNAP_M}") wto_navq_add_point(blk, "s", start) diff --git a/game-ai/ground/wto_ai_route_common.das b/game-ai/ground/wto_ai_route_common.das index 9185276..a249f93 100644 --- a/game-ai/ground/wto_ai_route_common.das +++ b/game-ai/ground/wto_ai_route_common.das @@ -71,7 +71,7 @@ def private wto_route_request(navState, slotIdx : int; now : float; myPos, goal rt.replanRequested = false rt.requests++ if navState == WTO_NAVMESH_LOADED - rt.ticket = wto_navq_path_request(slotIdx, rt.tier, rt.filter, myPos, goal) + rt.ticket = wto_navq_path_request(slotIdx, rt.tier, rt.filter, slot.army, myPos, goal) rt.pending = rt.ticket > 0 rt.pendingGoal = goal return diff --git a/game-ai/ground/wto_ai_traffic_common.das b/game-ai/ground/wto_ai_traffic_common.das new file mode 100644 index 0000000..9cc3bbf --- /dev/null +++ b/game-ai/ground/wto_ai_traffic_common.das @@ -0,0 +1,239 @@ +// Vehicles and wrecks on the path: what the baked mesh cannot know. Distances use each hull's +// length and width along the bot's heading, not a circle. A vehicle slower than stationarySpeedMps, +// a wreck or a parked player is an obstacle whatever its size: the bot passes it on the side where +// the mesh leaves room for its hull, or stops short and, after blockWaitSec, marks it for path +// searches and plans again. Moving traffic ahead is followed at its speed; oncoming traffic is +// passed in the open, and in narrow passages the bigger vehicle goes first. +options indenting = 2 +options no_global_heap = true +module wto_ai_traffic_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_nav_types_common +require %appGame.wtoai.wto_ai_navquery_common +require %appGame.wtoai.wto_ai_navmesh_common + +// A vehicle or wreck seen from the bot: how far ahead (along) and to the left (lat) its centre is, +// and the half extents of its hull along and across the bot's heading. +[safe_when_uninitialized] +struct private WtoTrafficBody + idx : int = -1 + isWreck : bool = false + pos : float3 = float3(0.0, 0.0, 0.0) + vel : float3 = float3(0.0, 0.0, 0.0) + along : float = 0.0 + lat : float = 0.0 + extAlong : float = 0.0 + extLat : float = 0.0 + +[never_inline] +def private wto_traffic_frame(myPos, dir, pos, vel, fwd : float3; halfLen, halfWid : float; var body : WtoTrafficBody&) + let left = float3(-dir.z, 0.0, dir.x) + let rel = float3(pos.x - myPos.x, 0.0, pos.z - myPos.z) + let fd = abs(dot(fwd, dir)) + let fl = abs(dot(fwd, left)) + body.pos = pos + body.vel = vel + body.along = dot(rel, dir) + body.lat = dot(rel, left) + body.extAlong = halfLen * fd + halfWid * fl + body.extLat = halfLen * fl + halfWid * fd + +// Free distance from the bot's front to the body's near end; negative once they overlap. +[never_inline] +def private wto_traffic_gap(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&) : float + return body.along - spec.halfLen - body.extAlong + +// Sideways distance between the centres that lets the hulls pass with passMarginM between them. +[never_inline] +def private wto_traffic_need(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&) : float + return spec.halfWid + body.extLat + WTO_AI_PF_PASS_MARGIN_M + +[never_inline] +def private wto_traffic_in_lane(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&; maxGap : float) : bool + return body.along > 0.0 && abs(body.lat) < wto_traffic_need(body, spec) && wto_traffic_gap(body, spec) < maxGap + +// The nearest standing body (stopped vehicle or wreck) in the bot's lane within `lookM`. +[never_inline] +def private wto_traffic_find_standing(world : WtoWorldSnap const&; myPos, dir : float3; lookM : float; + slot : WtoBotSlot const&; var best : WtoTrafficBody&) : bool + var maxGap = lookM + var found = false + var body = WtoTrafficBody() + for i in range(world.unitCount) + assume u = world.units[i] + let flatVel = float3(u.vel.x, 0.0, u.vel.z) + if !u.isAlive || !u.isGround || u.eid == slot.eid || length(flatVel) >= WTO_AI_PF_STATIONARY_MPS + continue + wto_traffic_frame(myPos, dir, u.pos, flatVel, u.hullFwd, u.halfLen, u.halfWid, body) + if wto_traffic_in_lane(body, slot.spec, maxGap) + maxGap = wto_traffic_gap(body, slot.spec) + body.idx = i + body.isWreck = false + best = body + found = true + let still = float3(0.0, 0.0, 0.0) + for w in range(world.wreckCount) + assume wr = world.wrecks[w] + wto_traffic_frame(myPos, dir, wr.pos, still, wr.hullFwd, wr.halfLen, wr.halfWid, body) + if wto_traffic_in_lane(body, slot.spec, maxGap) + maxGap = wto_traffic_gap(body, slot.spec) + body.idx = w + body.isWreck = true + best = body + found = true + return found + +// Whether a moving body and the bot come within passing distance in the next trafficTtcSec. +[never_inline] +def private wto_traffic_meets(dir : float3; speedMps : float; body : WtoTrafficBody const&; spec : WtoVehicleSpec const&) : bool + let left = float3(-dir.z, 0.0, dir.x) + let closeAlong = dot(body.vel, dir) - speedMps + let closeLat = dot(body.vel, left) + let need = wto_traffic_need(body, spec) + let reach = spec.halfLen + body.extAlong + WTO_AI_PF_PASS_MARGIN_M + for k in range(5) + let t = WTO_AI_PF_TRAFFIC_TTC_SEC * float(k) * 0.25 + if abs(body.lat + closeLat * t) < need && abs(body.along + closeAlong * t) < reach + return true + return false + +// Moving vehicles: one ahead in the lane going the same way caps the speed so the bot can still +// stop behind it; the nearest one the bot would meet is returned in `oncoming`. +[never_inline] +def private wto_traffic_moving(world : WtoWorldSnap const&; myPos, dir : float3; speedMps : float; + var slot : WtoBotSlot&; var oncoming : WtoTrafficBody&) : bool + let lookM = max(WTO_AI_PF_BUMPER_RAY_M, speedMps * WTO_AI_PF_TRAFFIC_TTC_SEC) + var nearest = 99999.0 + var body = WtoTrafficBody() + for i in range(world.unitCount) + assume u = world.units[i] + let flatVel = float3(u.vel.x, 0.0, u.vel.z) + let speed = length(flatVel) + if !u.isAlive || !u.isGround || u.eid == slot.eid || speed < WTO_AI_PF_STATIONARY_MPS + continue + wto_traffic_frame(myPos, dir, u.pos, flatVel, u.hullFwd, u.halfLen, u.halfWid, body) + let ahead = dot(flatVel, dir) + if ahead > 0.7 * speed + if wto_traffic_in_lane(body, slot.spec, lookM) + let room = max(0.0, wto_traffic_gap(body, slot.spec) - WTO_AI_PF_BUMPER_STOP_M) + slot.nav.avoidSpeedCap = min(slot.nav.avoidSpeedCap, ahead + sqrt(2.0 * WTO_AI_PF_BRAKE_DECEL * room)) + continue + if body.along > 0.0 && body.along < nearest && wto_traffic_meets(dir, speedMps, body, slot.spec) + nearest = body.along + body.idx = i + oncoming = body + return nearest < 99990.0 + +// Side room for the hull: the mesh must allow the straight line to the passing point. +[never_inline] +def private wto_traffic_room(navState : int; myPos, wp : float3; slot : WtoBotSlot const&) : bool + if navState != WTO_NAVMESH_LOADED || slot.route.tier < 0 + return true + var frac = 0.0 + return wto_navq_raycast(slot.route.tier, slot.route.filter, myPos, wp, frac) != 0 + +// Steers past `body` on the side with room: the nearer side first (or the side chosen within the +// last blockWaitSec, so the bot does not swing between sides), then the other. +[never_inline] +def private wto_traffic_pass(navState : int; now : float; myPos, dir : float3; body : WtoTrafficBody const&; + var slot : WtoBotSlot&) : bool + assume nav = slot.nav + let left = float3(-dir.z, 0.0, dir.x) + let need = wto_traffic_need(body, slot.spec) + var side = abs(body.lat + need) <= abs(body.lat - need) ? 1.0 : -1.0 + if now < nav.avoidSideUntil && nav.avoidSide != 0.0 + side = nav.avoidSide + let beyond = max(body.along + body.extAlong + slot.spec.halfLen, WTO_AI_PF_BUMPER_RAY_M) + for _k in range(2) + let wp = myPos + dir * beyond + left * (body.lat + side * need) + if wto_traffic_room(navState, myPos, wp, slot) + nav.avoidActive = true + nav.avoidTarget = wp + nav.avoidSide = side + nav.avoidSideUntil = now + WTO_AI_PF_BLOCK_WAIT_SEC + nav.avoidSpeedCap = min(nav.avoidSpeedCap, WTO_AI_PF_PASS_SPEED_MPS) + return true + side = -side + return false + +// No way past: stop short; after blockWaitSec mark the body for path searches and plan again. +[never_inline] +def private wto_traffic_blocked(navState : int; now : float; body : WtoTrafficBody const&; var slot : WtoBotSlot&) + assume nav = slot.nav + nav.avoidSpeedCap = min(nav.avoidSpeedCap, max(0.0, wto_traffic_gap(body, slot.spec) - WTO_AI_PF_CONTACT_GAP_M)) + if nav.blockedSince < -50.0 + nav.blockedSince = now + return + if now - nav.blockedSince < WTO_AI_PF_BLOCK_WAIT_SEC + return + nav.blockedSince = -100.0 + nav.blockEvents++ + if navState == WTO_NAVMESH_LOADED + wto_navq_add_dynamic(body.pos, wto_traffic_need(body, slot.spec), WTO_AI_PF_RUBBLE_COST_MUL, now + WTO_AI_PF_BLOCK_TTL_SEC) + slot.route.replanRequested = true + print("WTO_AI|NAV_BLOCKED_BY|eid={uint(slot.eid)}|wreck={body.isWreck}|pos={body.pos}\n") + +// The bigger vehicle goes first; equal sizes by entity id. Players always keep their way. +[never_inline] +def private wto_traffic_has_priority(slot : WtoBotSlot const&; other : WtoUnitSnap const&) : bool + if other.isHuman + return false + let mine = slot.spec.halfLen * slot.spec.halfWid + let theirs = other.halfLen * other.halfWid + if abs(mine - theirs) > 0.5 + return mine > theirs + return uint(slot.eid) < uint(other.eid) + +// Waits for the vehicle with priority, at most yieldWaitMaxSec, then not again for as long. +[never_inline] +def private wto_traffic_yield(now : float; var nav : WtoNavState&) + if nav.yieldUntil < now && now >= nav.yieldCooldownUntil + nav.yieldUntil = now + WTO_AI_PF_YIELD_WAIT_SEC + nav.yieldCooldownUntil = nav.yieldUntil + WTO_AI_PF_YIELD_WAIT_SEC + nav.avoidSpeedCap = min(nav.avoidSpeedCap, now < nav.yieldUntil ? 0.0 : WTO_AI_PF_PASS_SPEED_MPS) + +// Hull pressed against a standing body: when that started (cleared once there is room again). +[never_inline] +def private wto_traffic_contact(now, gap, speedMps : float; var nav : WtoNavState&) + if gap >= WTO_AI_PF_CONTACT_GAP_M || speedMps >= WTO_AI_PF_STATIONARY_MPS + nav.contactSince = -100.0 + elif nav.contactSince < -50.0 + nav.contactSince = now + +// True after contactReverseSec pressed against a vehicle or wreck: the caller backs off at once. +[never_inline] +def public wto_traffic_in_contact(now : float; nav : WtoNavState const&) : bool + return nav.contactSince > -50.0 && now - nav.contactSince >= WTO_AI_PF_CONTACT_REVERSE_SEC + +// Per nav tick: sets slot.nav.avoidActive / avoidTarget (a point beside an obstacle to steer at) +// and avoidSpeedCap for the bot heading along `dir` on its path. +[never_inline] +def public wto_traffic_update(world : WtoWorldSnap const&; navState : int; now : float; myPos, dir : float3; + speedMps : float; narrow : bool; var slot : WtoBotSlot&) + assume nav = slot.nav + nav.avoidActive = false + nav.avoidSpeedCap = 99.0 + var oncoming = WtoTrafficBody() + let meets = wto_traffic_moving(world, myPos, dir, speedMps, slot, oncoming) + var standing = WtoTrafficBody() + let lookM = max(WTO_AI_PF_BUMPER_RAY_M, speedMps * WTO_AI_PF_TRAFFIC_TTC_SEC) + if wto_traffic_find_standing(world, myPos, dir, lookM, slot, standing) + wto_traffic_contact(now, wto_traffic_gap(standing, slot.spec), speedMps, nav) + if !wto_traffic_pass(navState, now, myPos, dir, standing, slot) + wto_traffic_blocked(navState, now, standing, slot) + return + nav.blockedSince = -100.0 + nav.contactSince = -100.0 + if !meets + nav.yieldUntil = -100.0 + return + if !narrow + if !wto_traffic_pass(navState, now, myPos, dir, oncoming, slot) + nav.avoidSpeedCap = min(nav.avoidSpeedCap, WTO_AI_PF_PASS_SPEED_MPS) + return + if !wto_traffic_has_priority(slot, world.units[oncoming.idx]) + wto_traffic_yield(now, nav) diff --git a/game-ai/ground/wto_ai_types_common.das b/game-ai/ground/wto_ai_types_common.das index d388ff8..ca95f11 100644 --- a/game-ai/ground/wto_ai_types_common.das +++ b/game-ai/ground/wto_ai_types_common.das @@ -88,6 +88,7 @@ struct public WtoUnitSnap struct public WtoWreckSnap eid : EntityId = INVALID_ENTITY_ID pos : float3 = float3(0.0, 0.0, 0.0) + hullFwd : float3 = float3(1.0, 0.0, 0.0) halfLen : float = 3.4 halfWid : float = 1.75 diff --git a/game-ai/ground/wto_ai_unstick_common.das b/game-ai/ground/wto_ai_unstick_common.das index b9c4249..7f4b5bf 100644 --- a/game-ai/ground/wto_ai_unstick_common.das +++ b/game-ai/ground/wto_ai_unstick_common.das @@ -60,12 +60,23 @@ def private wto_unstick_mark(var world : WtoWorldSnap&; navState : int; now : fl def private wto_unstick_give_up(var world : WtoWorldSnap&; navState : int; now : float; myPos, ahead : float3; var slot : WtoBotSlot&) print("WTO_AI|NAV_UNREACHABLE|eid={uint(slot.eid)}|tier={slot.route.tier}|pos={myPos}|goal={slot.route.goal}|attempts={slot.nav.unstickAttempts}\n") - wto_unstick_mark(world, navState, now, ahead, WTO_AI_PF_JAM_RADIUS_M * 1.5, WTO_AI_PF_JAM_COST_MUL * 2.0) + wto_unstick_mark(world, navState, now, ahead, WTO_AI_PF_GIVE_UP_RADIUS_M, WTO_AI_PF_GIVE_UP_COST_MUL) slot.order.expiresAt = now slot.nav.unreachableEvents++ slot.nav.unstickAttempts = 0 slot.nav.unstickLevel = 0 +// Pressed against a vehicle or wreck: back up at once instead of waiting for the stuck window, +// and plan again so the next path or passing point accounts for it. +[never_inline] +def public wto_unstick_contact(navState : int; now : float; myPos, hullFwd : float3; var slot : WtoBotSlot&) + slot.nav.contactSince = -100.0 + slot.nav.contactEvents++ + slot.nav.stuckCheckAt = -100.0 + slot.route.replanRequested = true + print("WTO_AI|NAV_CONTACT|eid={uint(slot.eid)}|pos={myPos}\n") + wto_unstick_start_reverse(navState, now, myPos, hullFwd, slot) + // Backing up after being stuck; true while the manoeuvre runs (the drive command is set). [never_inline] def public wto_unstick_reversing(now : float; myPos : float3; var slot : WtoBotSlot&) : bool diff --git a/game-ai/ground/wto_ai_world_common.das b/game-ai/ground/wto_ai_world_common.das index 475be20..14b32e2 100644 --- a/game-ai/ground/wto_ai_world_common.das +++ b/game-ai/ground/wto_ai_world_common.das @@ -129,6 +129,7 @@ def private wto_record_wreck_once(var snap : WtoWorldSnap&; eid : EntityId; u : let wIdx = snap.wreckCount snap.wrecks[wIdx].eid = eid snap.wrecks[wIdx].pos = u.pos + snap.wrecks[wIdx].hullFwd = wto_xz_normalize(u.unitTm[0], float3(1.0, 0.0, 0.0)) snap.wrecks[wIdx].halfLen = max(2.0, max(abs(box.boxMin.x), abs(box.boxMax.x))) snap.wrecks[wIdx].halfWid = max(1.1, max(abs(box.boxMin.z), abs(box.boxMax.z))) snap.wreckCount = wIdx + 1 diff --git a/native/wto-nav/wto_nav_internal.h b/native/wto-nav/wto_nav_internal.h index 0cdae48..968d33a 100644 --- a/native/wto-nav/wto_nav_internal.h +++ b/native/wto-nav/wto_nav_internal.h @@ -37,14 +37,15 @@ struct DynamicCost { extern DynamicCost g_dynamic[WTO_NAV_RT_MAX_DYNAMIC]; extern uint32_t g_dynamic_count; -/* Area costs per WtoPolyArea, times the chokepoint multiplier and live dynamic costs. */ +/* Area costs per WtoPolyArea, times the chokepoint multiplier, live dynamic costs and the + * traffic of the searching path's group. */ class QueryFilter : public dtQueryFilter { public: float chokepointMul = 1.0f; float getCost(const float *pa, const float *pb, const dtPolyRef, const dtMeshTile *, const dtPoly *, - const dtPolyRef, const dtMeshTile *, const dtPoly *curPoly, + const dtPolyRef curRef, const dtMeshTile *, const dtPoly *curPoly, const dtPolyRef, const dtMeshTile *, const dtPoly *) const override; }; @@ -55,15 +56,27 @@ struct Pack { dtNavMeshQuery *pointQueries[WTO_NAV_TIER_COUNT] = {}; /* Snapping, raycasts, wall distance */ std::vector covers; std::vector tactical; + /* First flat polygon index of every tile slot, and per traffic group how many counted paths + * cross each polygon (indexed by tileBase[tile] + polygon). */ + std::vector tileBase[WTO_NAV_TIER_COUNT]; + std::vector traffic[WTO_NAV_TIER_COUNT][WTO_NAV_RT_TRAFFIC_GROUPS]; }; extern SRWLOCK g_lock; extern Pack *g_pack; extern QueryFilter g_filters[WTO_NAV_RT_FILTER_COUNT]; extern WtoNavStats g_stats; +extern WtoNavTuning g_tuning; + +/* Tier and traffic group (0-based, -1 none) of the search being advanced; read by getCost. */ +extern int g_cost_tier; +extern int g_cost_group; double now_micros(); +/* Flat polygon index for Pack::traffic, or -1. */ +int poly_index(const Pack &pack, uint32_t tier, dtPolyRef ref); + /* * Nearest polygon within `snap` metres; mission points (spawn and capture zone centres) carry * heights that are not on the ground, so a miss is retried over the mesh's whole height range, @@ -77,5 +90,6 @@ void paths_reset_locked(); void dynamic_reset_locked(); void dynamic_expire_locked(float now); uint32_t paths_pending_locked(); +uint32_t traffic_paths_locked(); } // namespace wtonav diff --git a/native/wto-nav/wto_nav_paths.cpp b/native/wto-nav/wto_nav_paths.cpp index 4c76d3a..5d16de2 100644 --- a/native/wto-nav/wto_nav_paths.cpp +++ b/native/wto-nav/wto_nav_paths.cpp @@ -3,15 +3,23 @@ * searched one at a time, oldest first, with Detour's sliced search; wto_nav_pump advances the * search in small iteration chunks until its per-frame time budget is spent, so one long path * across a 4 km map spreads over several frames instead of stalling one. + * + * Paths of a traffic group (a team) are remembered per slot for trafficHoldSec: their polygons + * cost more for the group's later searches, so a team spreads over parallel routes instead of + * queueing on one road. Finished corners are pulled away from the edges they turn around, so a + * vehicle cutting a corner does not clip the building the mesh was eroded from. */ #include "wto_nav_internal.h" +#include #include namespace wtonav { namespace { -constexpr int kIterChunk = 64; /* Detour node expansions between budget checks */ +constexpr int kIterChunk = 64; /* Detour node expansions between budget checks */ +constexpr float kStraightCos = 0.985f; /* Corners turning less than ~10 degrees stay put */ +constexpr int kCornerRayPolys = 256; enum class JobState : uint8_t { Empty, Queued, Running, Done }; @@ -20,6 +28,7 @@ struct PathJob { JobState state; uint32_t tier; uint32_t filter; + int group; /* 0-based traffic group, -1 none */ dtPolyRef startRef; dtPolyRef goalRef; float startPt[3]; @@ -31,11 +40,136 @@ struct PathJob { float corners[WTO_NAV_RT_MAX_CORNERS * 3]; }; +/* Polygons of a slot's last finished path while they count as its group's traffic. */ +struct Occupancy { + int group = -1; + uint32_t tier = 0; + float until = 0.0f; + std::vector polys; +}; + PathJob g_jobs[WTO_NAV_RT_PATH_SLOTS]; +Occupancy g_occupancy[WTO_NAV_RT_PATH_SLOTS]; uint32_t g_next_ticket = 1; uint32_t g_pump_serial; +float g_pump_now; int g_active = -1; /* Slot whose search owns its tier's path query */ dtPolyRef g_poly_path[kMaxPathPolys]; +dtPolyRef g_corner_refs[WTO_NAV_RT_MAX_CORNERS]; +unsigned char g_corner_flags[WTO_NAV_RT_MAX_CORNERS]; +dtPolyRef g_ray_polys[kCornerRayPolys]; + +void release(Occupancy &occ) +{ + if (occ.group >= 0 && g_pack != nullptr) { + std::vector &counts = g_pack->traffic[occ.tier][occ.group]; + for (uint32_t at : occ.polys) { + if (at < counts.size() && counts[at] != 0) + counts[at]--; + } + } + occ.group = -1; + occ.polys.clear(); +} + +void occupy(Occupancy &occ, const PathJob &job, int count) +{ + release(occ); + if (job.group < 0 || !(g_tuning.trafficCostPerPath > 0.0f) || !(g_tuning.trafficHoldSec > 0.0f)) + return; + std::vector &counts = g_pack->traffic[job.tier][job.group]; + for (int i = 0; i < count; i++) { + const int at = poly_index(*g_pack, job.tier, g_poly_path[i]); + if (at < 0 || counts[(size_t)at] == UINT16_MAX) + continue; + counts[(size_t)at]++; + occ.polys.push_back((uint32_t)at); + } + occ.group = job.group; + occ.tier = job.tier; + occ.until = g_pump_now + g_tuning.trafficHoldSec; +} + +void expire_occupancy(float now) +{ + for (Occupancy &occ : g_occupancy) { + if (occ.group >= 0 && occ.until < now) + release(occ); + } +} + +void normalize_xz(float v[3]) +{ + v[1] = 0.0f; + const float len = dtMathSqrtf(v[0] * v[0] + v[2] * v[2]); + if (len > 1e-4f) { + v[0] /= len; + v[2] /= len; + } else { + v[0] = v[2] = 0.0f; + } +} + +/* Whether the mesh lets a vehicle go straight from `from` (on `ref`) to `to`; `end` gets the + * polygon reached. */ +bool open_line(const dtNavMeshQuery *query, const dtQueryFilter &filter, dtPolyRef ref, const float from[3], + const float to[3], dtPolyRef *end) +{ + float t = 0.0f, normal[3]; + int visited = 0; + if (dtStatusFailed(query->raycast(ref, from, to, &filter, &t, normal, g_ray_polys, &visited, kCornerRayPolys)) || + t != FLT_MAX || visited <= 0) + return false; + if (end != nullptr) + *end = g_ray_polys[visited - 1]; + return true; +} + +/* Moves corner i (between corners i-1 and i+1) up to cornerOffsetM away from the edge it turns + * around, keeping both legs and the move itself on the mesh. */ +bool push_corner(const dtNavMeshQuery *query, const dtQueryFilter &filter, float *corners, int i, dtPolyRef prev_ref) +{ + float *c = corners + i * 3; + const float *p = c - 3, *n = c + 3; + float in[3] = { c[0] - p[0], 0.0f, c[2] - p[2] }, out[3] = { n[0] - c[0], 0.0f, n[2] - c[2] }; + normalize_xz(in); + normalize_xz(out); + if (dtVdot2D(in, out) > kStraightCos) + return false; + float push[3] = { in[0] - out[0], 0.0f, in[2] - out[2] }; + normalize_xz(push); + for (float scale = 1.0f; scale > 0.2f; scale *= 0.5f) { + const float step = g_tuning.cornerOffsetM * scale; + float moved[3] = { c[0] + push[0] * step, c[1], c[2] + push[2] * step }; + dtPolyRef moved_ref = 0; + if (!open_line(query, filter, g_corner_refs[i], c, moved, &moved_ref) || + !open_line(query, filter, prev_ref, p, moved, nullptr) || + !open_line(query, filter, moved_ref, moved, n, nullptr)) + continue; + float height = 0.0f; + if (dtStatusSucceed(query->getPolyHeight(moved_ref, moved, &height))) + moved[1] = height; + dtVcopy(c, moved); + g_corner_refs[i] = moved_ref; + return true; + } + return false; +} + +/* Corners on either end of an off-mesh link (one-way downhill) stay where they are. */ +void push_corners(const PathJob &job, float *corners, int count) +{ + if (!(g_tuning.cornerOffsetM > 0.0f) || count < 3) + return; + const dtNavMeshQuery *query = g_pack->pointQueries[job.tier]; + const QueryFilter &filter = g_filters[job.filter]; + for (int i = 1; i < count - 1; i++) { + const bool linked = (g_corner_flags[i] | g_corner_flags[i - 1]) & DT_STRAIGHTPATH_OFFMESH_CONNECTION; + if (!linked && g_corner_refs[i] != 0 && g_corner_refs[i - 1] != 0 && + push_corner(query, filter, corners, i, g_corner_refs[i - 1])) + g_stats.cornersMoved++; + } +} void finish(PathJob &job, WtoNavPathStatus status) { @@ -104,12 +238,14 @@ void finalize(PathJob &job, dtNavMeshQuery *query) return; } int corners = 0; - status = query->findStraightPath(job.startPt, goal, g_poly_path, count, job.corners, nullptr, nullptr, + status = query->findStraightPath(job.startPt, goal, g_poly_path, count, job.corners, g_corner_flags, g_corner_refs, &corners, WTO_NAV_RT_MAX_CORNERS, 0); if (dtStatusFailed(status) || corners == 0) { finish(job, WTO_NAV_PATH_FAILED); return; } + push_corners(job, job.corners, corners); + occupy(g_occupancy[&job - g_jobs], job, count); float length = 0.0f; for (int i = 1; i < corners; i++) length += dtVdist(job.corners + (i - 1) * 3, job.corners + i * 3); @@ -141,12 +277,25 @@ bool start_next() } // namespace +/* The pack is already replaced: its traffic counters start at zero, so nothing is released. */ void paths_reset_locked() { memset(g_jobs, 0, sizeof(g_jobs)); + for (Occupancy &occ : g_occupancy) { + occ.group = -1; + occ.polys.clear(); + } g_active = -1; } +uint32_t traffic_paths_locked() +{ + uint32_t paths = 0; + for (const Occupancy &occ : g_occupancy) + paths += occ.group >= 0; + return paths; +} + uint32_t paths_pending_locked() { uint32_t pending = 0; @@ -168,11 +317,13 @@ extern "C" uint32_t wto_nav_path_request(uint32_t slot, const WtoNavPathRequest if (g_active == (int)slot) g_active = -1; /* The next initSlicedFindPath discards the abandoned search */ memset(&job, 0, sizeof(job)); + release(g_occupancy[slot]); /* A path never counts as traffic against its own replacement */ if (g_next_ticket == 0) g_next_ticket = 1; job.ticket = g_next_ticket++; job.tier = request->tier; job.filter = request->filter; + job.group = request->group >= 1 && request->group <= WTO_NAV_RT_TRAFFIC_GROUPS ? (int)request->group - 1 : -1; prepare(job, *request); const uint32_t ticket = job.ticket; ReleaseSRWLockExclusive(&g_lock); @@ -207,6 +358,8 @@ extern "C" void wto_nav_pump(double budget_us, float now) const double began = now_micros(); dynamic_expire_locked(now); g_pump_serial++; + g_pump_now = now; + expire_occupancy(now); if (g_pack == nullptr) { for (PathJob &job : g_jobs) { if (job.state == JobState::Queued || job.state == JobState::Running) @@ -227,7 +380,10 @@ extern "C" void wto_nav_pump(double budget_us, float now) } const double chunk_began = now_micros(); int done = 0; + g_cost_tier = (int)job.tier; + g_cost_group = g_tuning.trafficCostPerPath > 0.0f ? job.group : -1; const dtStatus status = query->updateSlicedFindPath(kIterChunk, &done); + g_cost_group = -1; job.searchMicros += now_micros() - chunk_began; if (dtStatusFailed(status)) { finish(job, WTO_NAV_PATH_FAILED); diff --git a/native/wto-nav/wto_nav_runtime.cpp b/native/wto-nav/wto_nav_runtime.cpp index 72c5f61..a2b1824 100644 --- a/native/wto-nav/wto_nav_runtime.cpp +++ b/native/wto-nav/wto_nav_runtime.cpp @@ -18,6 +18,9 @@ SRWLOCK g_lock = SRWLOCK_INIT; Pack *g_pack; QueryFilter g_filters[WTO_NAV_RT_FILTER_COUNT]; WtoNavStats g_stats; +WtoNavTuning g_tuning; +int g_cost_tier = -1; +int g_cost_group = -1; namespace { @@ -99,6 +102,23 @@ bool init_queries(Pack *pack, uint32_t tier) dtStatusSucceed(pack->pointQueries[tier]->init(pack->meshes[tier], kPointSearchNodes)); } +/* Traffic counters: one per polygon and group, addressed through each tile slot's first index. */ +void init_traffic(Pack *pack, uint32_t tier) +{ + const dtNavMesh *mesh = pack->meshes[tier]; + const int max_tiles = mesh->getMaxTiles(); + uint32_t total = 0; + pack->tileBase[tier].assign((size_t)max_tiles, 0); + for (int i = 0; i < max_tiles; i++) { + pack->tileBase[tier][(size_t)i] = total; + const dtMeshTile *tile = mesh->getTile(i); + if (tile != nullptr && tile->header != nullptr) + total += (uint32_t)tile->header->polyCount; + } + for (std::vector &counts : pack->traffic[tier]) + counts.assign(total, 0); +} + bool load_tier(const std::vector &data, const WtoNavHeader &hdr, uint32_t tier, Pack *pack, uint32_t *polys, char *detail, size_t detail_size) { uint64_t at = hdr.tierOffsets[tier]; @@ -146,6 +166,7 @@ bool load_tier(const std::vector &data, const WtoNavHeader &hdr, uint32 } *polys += (uint32_t)((const dtMeshHeader *)tile)->polyCount; } + init_traffic(pack, tier); if (!init_queries(pack, tier)) { snprintf(detail, detail_size, "tier %u query init failed", tier); return false; @@ -263,12 +284,20 @@ void replace_pack(Pack *pack) float QueryFilter::getCost(const float *pa, const float *pb, const dtPolyRef, const dtMeshTile *, const dtPoly *, - const dtPolyRef, const dtMeshTile *, const dtPoly *curPoly, + const dtPolyRef curRef, const dtMeshTile *, const dtPoly *curPoly, const dtPolyRef, const dtMeshTile *, const dtPoly *) const { float cost = dtVdist(pa, pb) * getAreaCost(curPoly->getArea()); if (curPoly->flags & WTO_FLAG_CHOKEPOINT) cost *= chokepointMul; + if (g_cost_group >= 0 && g_pack != nullptr) { + const int at = poly_index(*g_pack, (uint32_t)g_cost_tier, curRef); + const uint16_t paths = at >= 0 ? g_pack->traffic[g_cost_tier][g_cost_group][(size_t)at] : 0; + if (paths != 0) { + const float mul = 1.0f + g_tuning.trafficCostPerPath * (float)paths; + cost *= mul < g_tuning.trafficCostMaxMul ? mul : g_tuning.trafficCostMaxMul; + } + } if (g_dynamic_count != 0) { const float mx = (pa[0] + pb[0]) * 0.5f, mz = (pa[2] + pb[2]) * 0.5f; float mul = 1.0f; @@ -293,6 +322,19 @@ bool snap_to_mesh(const dtNavMeshQuery *query, const dtQueryFilter &filter, floa return dtStatusSucceed(query->findNearestPoly(point, column_extents, &filter, ref, nearest)) && *ref != 0; } +int poly_index(const Pack &pack, uint32_t tier, dtPolyRef ref) +{ + if (tier >= WTO_NAV_TIER_COUNT || pack.meshes[tier] == nullptr || ref == 0) + return -1; + unsigned int salt = 0, tile = 0, poly = 0; + pack.meshes[tier]->decodePolyId(ref, salt, tile, poly); + const std::vector &base = pack.tileBase[tier]; + if (tile >= base.size()) + return -1; + const size_t at = (size_t)base[tile] + poly; + return at < pack.traffic[tier][0].size() ? (int)at : -1; +} + double now_micros() { static LARGE_INTEGER frequency; @@ -422,10 +464,28 @@ extern "C" void wto_nav_set_costs(uint32_t filter, const WtoNavCosts *costs) ReleaseSRWLockExclusive(&g_lock); } +extern "C" void wto_nav_set_tuning(const WtoNavTuning *tuning) +{ + if (tuning == nullptr) + return; + AcquireSRWLockExclusive(&g_lock); + g_tuning = *tuning; + if (!(g_tuning.trafficCostPerPath > 0.0f)) + g_tuning.trafficCostPerPath = 0.0f; + if (!(g_tuning.trafficCostMaxMul >= 1.0f)) + g_tuning.trafficCostMaxMul = 1.0f; + if (!(g_tuning.trafficHoldSec > 0.0f)) + g_tuning.trafficHoldSec = 0.0f; + if (!(g_tuning.cornerOffsetM > 0.0f)) + g_tuning.cornerOffsetM = 0.0f; + ReleaseSRWLockExclusive(&g_lock); +} + extern "C" void wto_nav_get_stats(WtoNavStats *stats) { AcquireSRWLockExclusive(&g_lock); g_stats.pending = paths_pending_locked(); + g_stats.trafficPaths = traffic_paths_locked(); g_stats.dynamic = g_dynamic_count; *stats = g_stats; ReleaseSRWLockExclusive(&g_lock); diff --git a/native/wto-nav/wto_nav_runtime.h b/native/wto-nav/wto_nav_runtime.h index e29c64a..7917c6a 100644 --- a/native/wto-nav/wto_nav_runtime.h +++ b/native/wto-nav/wto_nav_runtime.h @@ -18,6 +18,15 @@ extern "C" { #define WTO_NAV_RT_PATH_SLOTS 160 /* Independent path searches the script may keep in flight */ #define WTO_NAV_RT_MAX_CORNERS 96 /* Straight-path corners returned per path */ #define WTO_NAV_RT_MAX_DYNAMIC 64 /* Live dynamic cost circles (wrecks, jams, rubble) */ +#define WTO_NAV_RT_TRAFFIC_GROUPS 2 /* Teams whose planned paths count as traffic for each other */ + +/* Battle-wide search behaviour, set before the pack loads. */ +typedef struct WtoNavTuning { + float trafficCostPerPath; /* Cost added per path of the same group through a polygon; 0 = off */ + float trafficCostMaxMul; /* Highest traffic multiplier */ + float trafficHoldSec; /* A finished path counts as traffic this long (script seconds) */ + float cornerOffsetM; /* Path corners are moved this far away from the edge they turn around */ +} WtoNavTuning; /* Detour traversal costs for one vehicle class, indexed by WtoPolyArea. */ typedef struct WtoNavCosts { @@ -62,6 +71,7 @@ typedef struct WtoNavPathRequest { uint32_t filter; /* 0 tracked, 1 wheeled */ float snapM; /* Start (and first goal) snap radius */ float goalSnapM; /* Wider horizontal goal snap when the goal misses snapM */ + uint32_t group; /* 1..WTO_NAV_RT_TRAFFIC_GROUPS: avoids and adds to that group's traffic; 0 none */ float start[3]; float goal[3]; } WtoNavPathRequest; @@ -95,6 +105,8 @@ typedef struct WtoNavStats { uint32_t pending; /* Paths waiting or being searched now */ uint32_t dynamic; /* Live dynamic cost circles */ uint32_t meshQueries; /* Probe, raycast and nearest calls */ + uint32_t trafficPaths; /* Finished paths counting as traffic now */ + uint32_t cornersMoved; /* Path corners moved away from the edge they turn around */ } WtoNavStats; /* Reads the eVER SHA-1 of a Dagor level file (levels/.bin) without loading the level. */ @@ -119,10 +131,17 @@ int wto_nav_is_loaded(void); /* Replaces the traversal costs of one filter (0 tracked, 1 wheeled). */ void wto_nav_set_costs(uint32_t filter, const WtoNavCosts *costs); +/* Replaces the traffic and corner settings; applies to searches started afterwards. */ +void wto_nav_set_tuning(const WtoNavTuning *tuning); + /* * Queues a path search in `slot`, replacing whatever the slot held. Start and goal are snapped * at once; a miss is final and reported through the ticket's result. Returns the ticket that * wto_nav_path_result must quote (0 when the slot or request is invalid). + * + * With a traffic group the search pays more for polygons that other paths of the group (finished + * within trafficHoldSec) pass through, and its own result counts for the next ones. The slot's + * previous path stops counting as soon as the new request arrives. */ uint32_t wto_nav_path_request(uint32_t slot, const WtoNavPathRequest *request); diff --git a/native/wto-net/src/local_mp_nav.c b/native/wto-net/src/local_mp_nav.c index 6c391d1..0fb4c43 100644 --- a/native/wto-net/src/local_mp_nav.c +++ b/native/wto-net/src/local_mp_nav.c @@ -4,13 +4,14 @@ * module answers synchronously by writing into the same block: * * op=prefetch -> state=started|skipped, level, reason (battle still loading) - * op=load_map allowFallback="0|1", tracked/wheeled costs t_, w_ + * op=load_map allowFallback="0|1", tracked/wheeled costs t_, w_, + * trafficPerPath, trafficMaxMul, trafficHoldSec, cornerOffset * -> state=loaded|fallback|failed, fingerprint=match|mismatch|unknown, level, * reason, tiers, covers * op=unload_map -> ok * op=pump now (script seconds), budgetUs -> pending - * op=path_request slot, tier, filter (0 tracked, 1 wheeled), snap, goalSnap, sx..sz, gx..gz - * -> ticket + * op=path_request slot, tier, filter (0 tracked, 1 wheeled), group (team, 0 none), snap, + * goalSnap, sx..sz, gx..gz -> ticket * op=path_result slot, ticket -> status=pending|full|partial|no_start|no_goal|failed|stale, * count, lenCm, truncated, goalMoved, px/py/pz * op=probe tier, filter, snap, wallR, px..pz -> onMesh, offCm, wallCm, area, flags, @@ -19,7 +20,7 @@ * op=nearest tier, filter, radius, px..pz -> found, x/y/z * op=dynamic px..pz, radius, mul, until (script seconds) -> count * op=get_stats -> loaded, queries, failures, avgUs, maxUs, maxFrames, pumpMaxUs, pending, - * dynamic, meshQueries + * dynamic, meshQueries, traffic, cornersMoved * * Coordinates in replies are centimetres (ints). Request values are strings: the script only uses * the DataBlock string add it already relies on. Replies are ints and strings written with the @@ -245,6 +246,16 @@ static void read_costs(const void *blk, const char *prefix, WtoNavCosts *costs) costs->chokepointMul = 1.0f; } +static void read_tuning(const void *blk) +{ + WtoNavTuning tuning; + tuning.trafficCostPerPath = get_real(blk, "trafficPerPath", 0.0f); + tuning.trafficCostMaxMul = get_real(blk, "trafficMaxMul", 1.0f); + tuning.trafficHoldSec = get_real(blk, "trafficHoldSec", 0.0f); + tuning.cornerOffsetM = get_real(blk, "cornerOffset", 0.0f); + wto_nav_set_tuning(&tuning); +} + static void log_loaded(const WtoNavLoadInfo *info) { char expected[41], actual[41]; @@ -270,6 +281,7 @@ static void decide_locked(const void *blk, int allow_fallback) wto_nav_set_costs(0, &costs); read_costs(blk, "w", &costs); wto_nav_set_costs(1, &costs); + read_tuning(blk); wto_nav_load(pack, level_path[0] ? level_path : NULL, &info); if (info.result != WTO_NAV_LOAD_OK) snprintf(g_battle.reason, sizeof(g_battle.reason), "%s", info.detail); @@ -337,10 +349,10 @@ static void unload_locked(const char *why) if (wto_nav_is_loaded()) { WtoNavStats stats; wto_nav_get_stats(&stats); - log_line("WTO_NAV|UNLOADED|level=%s|why=%s|paths=%u|failures=%u|avgUs=%.0f|maxUs=%.0f|maxFrames=%u|pumpMaxUs=%.0f|meshQueries=%u", + log_line("WTO_NAV|UNLOADED|level=%s|why=%s|paths=%u|failures=%u|avgUs=%.0f|maxUs=%.0f|maxFrames=%u|pumpMaxUs=%.0f|meshQueries=%u|cornersMoved=%u", g_battle.level, why, stats.queries, stats.failures, stats.queries ? stats.totalMicros / stats.queries : 0.0, stats.maxMicros, - stats.maxFrames, stats.pumpMaxMicros, stats.meshQueries); + stats.maxFrames, stats.pumpMaxMicros, stats.meshQueries, stats.cornersMoved); wto_nav_unload(); } memset(&g_battle, 0, sizeof(g_battle)); @@ -350,11 +362,13 @@ static void path_request(void *blk) { WtoNavPathRequest req; const long slot = get_long(blk, "slot", -1), tier = get_long(blk, "tier", -1), filter = get_long(blk, "filter", 0); + const long group = get_long(blk, "group", 0); uint32_t ticket = 0; memset(&req, 0, sizeof(req)); req.tier = (uint32_t)tier; req.filter = (uint32_t)filter; + req.group = group > 0 ? (uint32_t)group : 0u; req.snapM = get_real(blk, "snap", 0.0f); req.goalSnapM = get_real(blk, "goalSnap", 0.0f); get_vec(blk, 's', req.start); @@ -453,6 +467,8 @@ static void get_stats(void *blk) set_int(blk, "pending", (int32_t)stats.pending); set_int(blk, "dynamic", (int32_t)stats.dynamic); set_int(blk, "meshQueries", (int32_t)stats.meshQueries); + set_int(blk, "traffic", (int32_t)stats.trafficPaths); + set_int(blk, "cornersMoved", (int32_t)stats.cornersMoved); } static void pump(void *blk) diff --git a/packages/patcher/src/ground-ai/ground-ai-config.ts b/packages/patcher/src/ground-ai/ground-ai-config.ts index a4f2500..17e2f18 100644 --- a/packages/patcher/src/ground-ai/ground-ai-config.ts +++ b/packages/patcher/src/ground-ai/ground-ai-config.ts @@ -56,8 +56,14 @@ export interface GroundAiPathFollow { readonly bumperStopM: number; readonly bumperBlockSec: number; readonly trafficTtcSec: number; - readonly avoidShiftM: number; readonly yieldWaitMaxSec: number; + readonly stationarySpeedMps: number; + readonly passMarginM: number; + readonly passSpeedMps: number; + readonly blockWaitSec: number; + readonly blockTtlSec: number; + readonly contactGapM: number; + readonly contactReverseSec: number; readonly stuckWindowSec: number; readonly stuckMinProgressM: number; readonly unstickReverseM: number; @@ -67,6 +73,8 @@ export interface GroundAiPathFollow { readonly jamRadiusM: number; readonly jamCostMul: number; readonly jamTtlSec: number; + readonly giveUpRadiusM: number; + readonly giveUpCostMul: number; readonly rubbleRadiusM: number; readonly rubbleCostMul: number; readonly rubbleTtlSec: number; @@ -160,6 +168,12 @@ export interface GroundAiConfig { readonly goalSnapRadiusM: number; /** Time queued path searches may take per game frame. */ readonly pathBudgetMsPerFrame: number; + /** Team traffic: cost added per teammate path through a polygon, its cap, and how long a path counts. */ + readonly trafficCostPerPath: number; + readonly trafficCostMaxMul: number; + readonly trafficHoldSec: number; + /** Path corners are moved this far away from the edge they turn around. */ + readonly cornerOffsetM: number; }; readonly navCostsTracked: GroundAiNavCosts; readonly navCostsWheeled: GroundAiNavCosts; @@ -355,6 +369,10 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['WTO_AI_NAVMESH_SNAP_M', 'float', c.navEngine.snapRadiusM], ['WTO_AI_NAVMESH_GOAL_SNAP_M', 'float', c.navEngine.goalSnapRadiusM], ['WTO_AI_NAVMESH_PATH_BUDGET_US', 'float', c.navEngine.pathBudgetMsPerFrame * 1000], + ['WTO_AI_NAVMESH_TRAFFIC_PER_PATH', 'float', c.navEngine.trafficCostPerPath], + ['WTO_AI_NAVMESH_TRAFFIC_MAX_MUL', 'float', c.navEngine.trafficCostMaxMul], + ['WTO_AI_NAVMESH_TRAFFIC_HOLD_SEC', 'float', c.navEngine.trafficHoldSec], + ['WTO_AI_NAVMESH_CORNER_OFFSET_M', 'float', c.navEngine.cornerOffsetM], ...navCostEntries('T', c.navCostsTracked), ...navCostEntries('W', c.navCostsWheeled), ...pathFollowEntries(c.pathFollow), @@ -457,8 +475,14 @@ function pathFollowEntries(p: GroundAiPathFollow): readonly DasEntry[] { ['WTO_AI_PF_BUMPER_STOP_M', 'float', p.bumperStopM], ['WTO_AI_PF_BUMPER_BLOCK_SEC', 'float', p.bumperBlockSec], ['WTO_AI_PF_TRAFFIC_TTC_SEC', 'float', p.trafficTtcSec], - ['WTO_AI_PF_AVOID_SHIFT_M', 'float', p.avoidShiftM], ['WTO_AI_PF_YIELD_WAIT_SEC', 'float', p.yieldWaitMaxSec], + ['WTO_AI_PF_STATIONARY_MPS', 'float', p.stationarySpeedMps], + ['WTO_AI_PF_PASS_MARGIN_M', 'float', p.passMarginM], + ['WTO_AI_PF_PASS_SPEED_MPS', 'float', p.passSpeedMps], + ['WTO_AI_PF_BLOCK_WAIT_SEC', 'float', p.blockWaitSec], + ['WTO_AI_PF_BLOCK_TTL_SEC', 'float', p.blockTtlSec], + ['WTO_AI_PF_CONTACT_GAP_M', 'float', p.contactGapM], + ['WTO_AI_PF_CONTACT_REVERSE_SEC', 'float', p.contactReverseSec], ['WTO_AI_PF_STUCK_WINDOW_SEC', 'float', p.stuckWindowSec], ['WTO_AI_PF_STUCK_MIN_PROGRESS_M', 'float', p.stuckMinProgressM], ['WTO_AI_PF_UNSTICK_REV_M', 'float', p.unstickReverseM], @@ -468,6 +492,8 @@ function pathFollowEntries(p: GroundAiPathFollow): readonly DasEntry[] { ['WTO_AI_PF_JAM_RADIUS_M', 'float', p.jamRadiusM], ['WTO_AI_PF_JAM_COST_MUL', 'float', p.jamCostMul], ['WTO_AI_PF_JAM_TTL_SEC', 'float', p.jamTtlSec], + ['WTO_AI_PF_GIVE_UP_RADIUS_M', 'float', p.giveUpRadiusM], + ['WTO_AI_PF_GIVE_UP_COST_MUL', 'float', p.giveUpCostMul], ['WTO_AI_PF_RUBBLE_RADIUS_M', 'float', p.rubbleRadiusM], ['WTO_AI_PF_RUBBLE_COST_MUL', 'float', p.rubbleCostMul], ['WTO_AI_PF_RUBBLE_TTL_SEC', 'float', p.rubbleTtlSec], diff --git a/tools/navgen/bake/bake.cpp b/tools/navgen/bake/bake.cpp index c72fdc0..c01d259 100644 --- a/tools/navgen/bake/bake.cpp +++ b/tools/navgen/bake/bake.cpp @@ -19,8 +19,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -57,9 +59,17 @@ struct CoverBake { float retreatMinM; }; +/* navBake water settings (ground-ai.jsonc, copied into the POI file by mission-bounds.mts). */ +struct WaterBake { + float maxFordDepthM; /* Deeper water is a wall */ + float marginM; /* Extra room kept from it on low banks */ + float bankHeightM; /* Banks up to this height above the water line get the extra room */ +}; + struct PoisData { CoverBake cover{}; float chokepointMaxWidthVehicles = 0.0f; + WaterBake water{ -1.0f, -1.0f, -1.0f }; std::vector t1Spawns; std::vector t2Spawns; std::vector caps; @@ -83,7 +93,6 @@ static constexpr float kCellSize = 0.50f; static constexpr float kCellHeight = 0.25f; static constexpr int kTileSize = 256; /* 128.0 m per tile */ static constexpr float kTileWorldSize = kTileSize * kCellSize; -static constexpr float kShallowWaterMaxM = 0.60f; static constexpr float kShallowWaterMinM = 0.05f; static constexpr float kRoughSlopeDeg = 18.0f; static constexpr float kCoverProbeStartM = 0.6f; @@ -275,7 +284,15 @@ static bool loadPois(const std::string &path, PoisData &out) { return false; } out.chokepointMaxWidthVehicles = readJsonNumber(content, "chokepointMaxWidthVehicles", -1.0f); - if (!(out.chokepointMaxWidthVehicles >= 1.0f && out.chokepointMaxWidthVehicles <= 4.0f)) { + out.water = { + readJsonNumber(content, "maxFordDepthM", -1.0f), + readJsonNumber(content, "deepWaterMarginM", -1.0f), + readJsonNumber(content, "deepWaterBankHeightM", -1.0f) + }; + if (!(out.chokepointMaxWidthVehicles >= 1.0f && out.chokepointMaxWidthVehicles <= 4.0f) || + !(out.water.maxFordDepthM >= 0.1f && out.water.maxFordDepthM <= 3.0f) || + !(out.water.marginM >= 0.0f && out.water.marginM <= 10.0f) || + !(out.water.bankHeightM >= 0.0f && out.water.bankHeightM <= 10.0f)) { std::fprintf(stderr, "Invalid navigation baking settings in %s. Regenerate it with mission-bounds.mts.\n", path.c_str()); return false; } @@ -328,6 +345,65 @@ static bool isCoverArea(unsigned char area) { return area != RC_NULL_AREA && area != WTO_AREA_DEEP_WATER && area != WTO_AREA_SHALLOW_WATER; } +/* Turns deep water into a wall before erosion, so walkable ground keeps the tier's radius from it + * like from any obstacle. Returns the indices of the water spans for wallOffWaterBank. */ +static std::vector wallOffDeepWater(rcCompactHeightfield &chf) { + std::vector water; + for (int i = 0; i < chf.spanCount; ++i) { + if (chf.areas[i] == WTO_AREA_DEEP_WATER) { + chf.areas[i] = RC_NULL_AREA; + water.push_back(i); + } + } + return water; +} + +/* After erosion: removes every span within `reachCells` of deep water (radius plus bank margin) + * whose surface is at most `maxSpanY` (cells), i.e. low bank that slopes into the water. The walk + * follows span connections and stops at higher ground, so bridges, quays and ramps above the + * water line keep only the erosion. Each span keeps the cell of its nearest water source; a span + * is revisited when a closer source reaches it. */ +static void wallOffWaterBank(rcCompactHeightfield &chf, const std::vector &water, float reachCells, int maxSpanY) { + if (water.empty() || !(reachCells > 0.0f)) return; + std::vector cellOf(chf.spanCount, -1); + for (int z = 0; z < chf.height; ++z) { + for (int x = 0; x < chf.width; ++x) { + const rcCompactCell &c = chf.cells[x + z * chf.width]; + for (int i = (int)c.index, n = (int)(c.index + c.count); i < n; ++i) cellOf[i] = x + z * chf.width; + } + } + const float limit = reachCells * reachCells; + std::vector source(chf.spanCount, -1); + std::vector best(chf.spanCount, FLT_MAX); + std::deque open; + for (int i : water) { + source[i] = cellOf[i]; + best[i] = 0.0f; + open.push_back(i); + } + while (!open.empty()) { + const int i = open.front(); + open.pop_front(); + const int cell = cellOf[i]; + const int x = cell % chf.width, z = cell / chf.width; + const int sx = source[i] % chf.width, sz = source[i] / chf.width; + for (int dir = 0; dir < 4; ++dir) { + const int con = rcGetCon(chf.spans[i], dir); + if (con == RC_NOT_CONNECTED) continue; + const int nx = x + rcGetDirOffsetX(dir), nz = z + rcGetDirOffsetY(dir); + const int ni = (int)chf.cells[nx + nz * chf.width].index + con; + const float d2 = (float)((nx - sx) * (nx - sx) + (nz - sz) * (nz - sz)); + if (d2 > limit || d2 >= best[ni] || (int)chf.spans[ni].y > maxSpanY) continue; + best[ni] = d2; + source[ni] = source[i]; + open.push_back(ni); + } + } + for (int i = 0; i < chf.spanCount; ++i) { + if (best[i] < FLT_MAX) chf.areas[i] = RC_NULL_AREA; + } +} + static bool isCoverBoundary(const rcCompactHeightfield &field, int x, int z, const rcCompactSpan &span) { for (int dir = 0; dir < 4; ++dir) { int connection = rcGetCon(span, dir); @@ -493,7 +569,7 @@ static TileBakeResult buildSingleTile( int tx, int tz, float mapMinX, float mapMinZ, const CoverBake &coverTuning, bool bakeCovers, - float chokeClearanceM + float chokeClearanceM, const WaterBake &water ) { TileBakeResult res; res.tile.tx = tx; @@ -514,7 +590,7 @@ static TileBakeResult buildSingleTile( cfg.mergeRegionArea = 400; cfg.maxVertsPerPoly = 6; cfg.tileSize = kTileSize; - cfg.borderSize = cfg.walkableRadius + 3; + cfg.borderSize = cfg.walkableRadius + (int)std::ceil(water.marginM / cfg.cs) + 3; // Cover and corner rays must see hard collision on the other side of tile boundaries. if (bakeCovers) cfg.borderSize = std::max(cfg.borderSize, coverBorderCells(coverTuning)); // Erosion walls off the heightfield edge; chokepoint reach must stay clear of that band. @@ -567,7 +643,7 @@ static TileBakeResult buildSingleTile( float cy = (a.y + b.y + c.y) * (1.0f / 3.0f); if (hasWater) { float depth = waterY - cy; - if (depth > kShallowWaterMaxM) return WTO_AREA_DEEP_WATER; + if (depth > water.maxFordDepthM) return WTO_AREA_DEEP_WATER; if (depth > kShallowWaterMinM) return WTO_AREA_SHALLOW_WATER; } if (ny < cosRoughSlope) return WTO_AREA_ROUGH; @@ -647,12 +723,16 @@ static TileBakeResult buildSingleTile( rcFreeHeightField(solid); solid = nullptr; - /* Erode walkable area by tank radius (guaranteed full hull clearance from hard obstacles!) */ + /* Erode walkable area by tank radius (guaranteed full hull clearance from hard obstacles and + * deep water), then keep the bank margin from deep water on top of it. */ + const std::vector deepWater = wallOffDeepWater(*chf); if (!rcErodeWalkableArea(&ctx, cfg.walkableRadius, *chf)) { rcFreeHeightField(hardHf); rcFreeCompactHeightfield(chf); return res; } + wallOffWaterBank(*chf, deepWater, (tier.agentRadius + water.marginM) / cfg.cs, + (int)std::floor((waterY + water.bankHeightM - cfg.bmin[1]) / cfg.ch)); /* Tag crushable fences & thin forest areas directly onto overlapping walkable cells (O(N), fast!) */ for (const auto &sm : softMarks) { @@ -1339,7 +1419,8 @@ int main(int argc, char **argv) { if (idx >= totalTiles) break; int tx = idx % tilesX; int tz = idx / tilesX; - auto br = buildSingleTile(geo, buckets[(size_t)idx], tierIdx, tx, tz, mapMinX, mapMinZ, pois.cover, doCovers, chokeClearanceM); + auto br = buildSingleTile(geo, buckets[(size_t)idx], tierIdx, tx, tz, mapMinX, mapMinZ, pois.cover, doCovers, + chokeClearanceM, pois.water); tierTiles[tierIdx][(size_t)idx] = br.tile; if (doCovers && !br.covers.empty()) { localCov.insert(localCov.end(), br.covers.begin(), br.covers.end()); @@ -1605,6 +1686,9 @@ int main(int argc, char **argv) { } } } + /* Deep water is no longer part of any mesh; mark it from the terrain. */ + if ((fl & 7u) == 0 && geo.hdr.waterLevel > -1e5f && geo.hdr.waterLevel - gy > pois.water.maxFordDepthM) + fl |= 16; pFlags[(size_t)rz * pw + rx] = fl; } } diff --git a/tools/navgen/mission-bounds.mts b/tools/navgen/mission-bounds.mts index a3b6e91..bd3b178 100644 --- a/tools/navgen/mission-bounds.mts +++ b/tools/navgen/mission-bounds.mts @@ -162,6 +162,9 @@ function readNavBake() { crushableMaxImpulse: nav.number('crushableMaxImpulse', { min: 0 }), crushableMaxRiExtraHp: nav.number('crushableMaxRiExtraHp', { min: 0 }), chokepointMaxWidthVehicles: nav.number('chokepointMaxWidthVehicles', { min: 1, max: 4 }), + maxFordDepthM: nav.number('maxFordDepthM', { min: 0.1, max: 3 }), + deepWaterMarginM: nav.number('deepWaterMarginM', { min: 0, max: 10 }), + deepWaterBankHeightM: nav.number('deepWaterBankHeightM', { min: 0, max: 10 }), }; } From 58fde2030ca15330a78f64816b94cc9803be850a Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sat, 5 Dec 2026 22:12:37 +0800 Subject: [PATCH 09/19] fix(ground-ai): escalate repeated contacts with vehicles and wrecks A bot pressed against the same wreck or stopped vehicle backed off, planned the same path again and drove into it once more, every few seconds for minutes, because a contact reset the stuck watch and left no trace for path searches. A second contact within pathFollow.contactRepeatSec near the same place now marks the body for path searches and switches the passing side; after unstickMaxAttempts repeats the bot gives its order up and the place is avoided like any other unreachable spot. NAV_CONTACT logs the repeat count and the body position. --- .../src/renderer/src/i18n/locales/en.json | 1 + .../src/renderer/src/i18n/locales/zh-CN.json | 1 + .../src/pages/tuning/bot-tuning-fields.ts | 1 + apps/launcher/src/shared/schemas/tuning.ts | 1 + apps/server/src/tuning/ground-ai-tuning.ts | 1 + apps/server/tuning/ground-ai.jsonc | 3 ++ game-ai/ground/wto_ai_nav_common.das | 2 +- game-ai/ground/wto_ai_nav_types_common.das | 5 +++ game-ai/ground/wto_ai_traffic_common.das | 15 ++++--- game-ai/ground/wto_ai_unstick_common.das | 42 +++++++++++++++---- .../patcher/src/ground-ai/ground-ai-config.ts | 2 + 11 files changed, 61 insertions(+), 13 deletions(-) diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 34e5f6a..e4f6b74 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -736,6 +736,7 @@ "blockTtlSec": "Blocked passage cost duration", "contactGapM": "Gap to an obstacle that counts as contact", "contactReverseSec": "Time in contact before backing off", + "contactRepeatSec": "Window in which a second contact counts as a repeat", "stuckWindowSec": "Stuck detection window", "stuckMinProgressM": "Min progress within the stuck window", "unstickReverseM": "Unstick reverse distance", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index 2f0f6d2..5c6abf9 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -736,6 +736,7 @@ "blockTtlSec": "被堵路段代价持续时间", "contactGapM": "离障碍多近算作顶上", "contactReverseSec": "顶上多久后倒车", + "contactRepeatSec": "多久内在同一处再顶上算作反复顶上", "stuckWindowSec": "卡住检测窗口时长", "stuckMinProgressM": "检测窗口内的最小前进距离", "unstickReverseM": "脱困倒车距离", diff --git a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts index b9325f5..1cc5ed8 100644 --- a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts +++ b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts @@ -318,6 +318,7 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ num('pathFollow', 'blockTtlSec', 3, 120, 's'), num('pathFollow', 'contactGapM', 0.2, 3, 'm'), num('pathFollow', 'contactReverseSec', 0.3, 5, 's'), + num('pathFollow', 'contactRepeatSec', 3, 120, 's'), num('pathFollow', 'stuckWindowSec', 1, 15, 's'), num('pathFollow', 'stuckMinProgressM', 0.2, 10, 'm'), num('pathFollow', 'unstickReverseM', 2, 25, 'm'), diff --git a/apps/launcher/src/shared/schemas/tuning.ts b/apps/launcher/src/shared/schemas/tuning.ts index 94b4217..850e93c 100644 --- a/apps/launcher/src/shared/schemas/tuning.ts +++ b/apps/launcher/src/shared/schemas/tuning.ts @@ -148,6 +148,7 @@ const GroundAiPathFollowSchema = z.object({ blockTtlSec: z.number().min(3).max(120), contactGapM: z.number().min(0.2).max(3), contactReverseSec: z.number().min(0.3).max(5), + contactRepeatSec: z.number().min(3).max(120), stuckWindowSec: z.number().min(1).max(15), stuckMinProgressM: z.number().min(0.2).max(10), unstickReverseM: z.number().min(2).max(25), diff --git a/apps/server/src/tuning/ground-ai-tuning.ts b/apps/server/src/tuning/ground-ai-tuning.ts index 1d94c8c..f959970 100644 --- a/apps/server/src/tuning/ground-ai-tuning.ts +++ b/apps/server/src/tuning/ground-ai-tuning.ts @@ -246,6 +246,7 @@ function readPathFollowSection(pf: TuningReader): GroundAiPathFollow { blockTtlSec: n('blockTtlSec', 3, 120), contactGapM: n('contactGapM', 0.2, 3), contactReverseSec: n('contactReverseSec', 0.3, 5), + contactRepeatSec: n('contactRepeatSec', 3, 120), stuckWindowSec: n('stuckWindowSec', 1, 15), stuckMinProgressM: n('stuckMinProgressM', 0.2, 10), unstickReverseM: n('unstickReverseM', 2, 25), diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index f19fab9..23efc43 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -226,10 +226,13 @@ "passSpeedMps": 4.0, // No side free: stop short, and after blockWaitSec mark the obstacle for path searches for // blockTtlSec and plan again. A hull within contactGapM of it for contactReverseSec backs off. + // Pressed again within contactRepeatSec near the same place: mark the obstacle, try the other + // side, and after unstickMaxAttempts such repeats give the order up. "blockWaitSec": 2.0, "blockTtlSec": 15.0, "contactGapM": 0.8, "contactReverseSec": 1.0, + "contactRepeatSec": 20.0, // Less progress than stuckMinProgressM within stuckWindowSec while wanting to move is stuck. "stuckWindowSec": 3.0, "stuckMinProgressM": 0.8, diff --git a/game-ai/ground/wto_ai_nav_common.das b/game-ai/ground/wto_ai_nav_common.das index 10a34c8..bb58bde 100644 --- a/game-ai/ground/wto_ai_nav_common.das +++ b/game-ai/ground/wto_ai_nav_common.das @@ -157,7 +157,7 @@ def private wto_nav_follow(var world : WtoWorldSnap&; navState : int; now : floa let narrow = slot.nav.wallDistM < WTO_AI_PF_NARROW_WALL_M || slot.nav.chokepoint wto_traffic_update(world, navState, now, myPos, pathDir, speedNow, narrow, slot) if wto_traffic_in_contact(now, slot.nav) - wto_unstick_contact(navState, now, myPos, hullFwd, slot) + wto_unstick_contact(world, navState, now, myPos, hullFwd, slot) if !wto_unstick_reversing(now, myPos, slot) wto_nav_halt(myPos, hullFwd, slot) return diff --git a/game-ai/ground/wto_ai_nav_types_common.das b/game-ai/ground/wto_ai_nav_types_common.das index e0bd269..4791783 100644 --- a/game-ai/ground/wto_ai_nav_types_common.das +++ b/game-ai/ground/wto_ai_nav_types_common.das @@ -56,6 +56,11 @@ struct public WtoNavState avoidSpeedCap : float = 99.0 blockedSince : float = -100.0 contactSince : float = -100.0 + contactBodyPos : float3 = float3(0.0, 0.0, 0.0) + contactBodyRadiusM : float = 0.0 + lastContactAt : float = -100.0 + lastContactPos : float3 = float3(0.0, 0.0, 0.0) + contactRepeats : int = 0 stuckOrigin : float3 = float3(0.0, 0.0, 0.0) stuckCheckAt : float = -100.0 unstickAnchor : float3 = float3(0.0, 0.0, 0.0) diff --git a/game-ai/ground/wto_ai_traffic_common.das b/game-ai/ground/wto_ai_traffic_common.das index 9cc3bbf..dd27736 100644 --- a/game-ai/ground/wto_ai_traffic_common.das +++ b/game-ai/ground/wto_ai_traffic_common.das @@ -196,13 +196,18 @@ def private wto_traffic_yield(now : float; var nav : WtoNavState&) nav.yieldCooldownUntil = nav.yieldUntil + WTO_AI_PF_YIELD_WAIT_SEC nav.avoidSpeedCap = min(nav.avoidSpeedCap, now < nav.yieldUntil ? 0.0 : WTO_AI_PF_PASS_SPEED_MPS) -// Hull pressed against a standing body: when that started (cleared once there is room again). +// Hull pressed against a standing body: when that started (cleared once there is room again), +// and where the body is and how much room passing it takes, for marking it on repeats. [never_inline] -def private wto_traffic_contact(now, gap, speedMps : float; var nav : WtoNavState&) - if gap >= WTO_AI_PF_CONTACT_GAP_M || speedMps >= WTO_AI_PF_STATIONARY_MPS +def private wto_traffic_contact(now, speedMps : float; body : WtoTrafficBody const&; var slot : WtoBotSlot&) + assume nav = slot.nav + if wto_traffic_gap(body, slot.spec) >= WTO_AI_PF_CONTACT_GAP_M || speedMps >= WTO_AI_PF_STATIONARY_MPS nav.contactSince = -100.0 - elif nav.contactSince < -50.0 + return + if nav.contactSince < -50.0 nav.contactSince = now + nav.contactBodyPos = body.pos + nav.contactBodyRadiusM = wto_traffic_need(body, slot.spec) // True after contactReverseSec pressed against a vehicle or wreck: the caller backs off at once. [never_inline] @@ -222,7 +227,7 @@ def public wto_traffic_update(world : WtoWorldSnap const&; navState : int; now : var standing = WtoTrafficBody() let lookM = max(WTO_AI_PF_BUMPER_RAY_M, speedMps * WTO_AI_PF_TRAFFIC_TTC_SEC) if wto_traffic_find_standing(world, myPos, dir, lookM, slot, standing) - wto_traffic_contact(now, wto_traffic_gap(standing, slot.spec), speedMps, nav) + wto_traffic_contact(now, speedMps, standing, slot) if !wto_traffic_pass(navState, now, myPos, dir, standing, slot) wto_traffic_blocked(navState, now, standing, slot) return diff --git a/game-ai/ground/wto_ai_unstick_common.das b/game-ai/ground/wto_ai_unstick_common.das index 7f4b5bf..4e349ff 100644 --- a/game-ai/ground/wto_ai_unstick_common.das +++ b/game-ai/ground/wto_ai_unstick_common.das @@ -66,15 +66,43 @@ def private wto_unstick_give_up(var world : WtoWorldSnap&; navState : int; now : slot.nav.unstickAttempts = 0 slot.nav.unstickLevel = 0 -// Pressed against a vehicle or wreck: back up at once instead of waiting for the stuck window, -// and plan again so the next path or passing point accounts for it. +// Pressed against the same body again: mark it for path searches and try its other side; after +// unstickMaxAttempts repeats give the order up like a bot stuck for good. [never_inline] -def public wto_unstick_contact(navState : int; now : float; myPos, hullFwd : float3; var slot : WtoBotSlot&) - slot.nav.contactSince = -100.0 - slot.nav.contactEvents++ - slot.nav.stuckCheckAt = -100.0 +def private wto_unstick_contact_repeat(var world : WtoWorldSnap&; navState : int; now : float; myPos : float3; + var slot : WtoBotSlot&) + assume nav = slot.nav + nav.contactRepeats++ + if nav.contactRepeats >= WTO_AI_PF_UNSTICK_MAX_ATTEMPTS + nav.unstickAttempts = nav.contactRepeats + nav.contactRepeats = 0 + wto_unstick_give_up(world, navState, now, myPos, nav.contactBodyPos, slot) + return + if navState == WTO_NAVMESH_LOADED + wto_navq_add_dynamic(nav.contactBodyPos, nav.contactBodyRadiusM, WTO_AI_PF_RUBBLE_COST_MUL, now + WTO_AI_PF_BLOCK_TTL_SEC) + if nav.avoidSide != 0.0 + nav.avoidSide = -nav.avoidSide + nav.avoidSideUntil = now + WTO_AI_PF_UNSTICK_REV_SEC + WTO_AI_PF_BLOCK_WAIT_SEC + +// Pressed against a vehicle or wreck: back up at once instead of waiting for the stuck window, +// and plan again. Pressed again near the same place within contactRepeatSec escalates. +[never_inline] +def public wto_unstick_contact(var world : WtoWorldSnap&; navState : int; now : float; myPos, hullFwd : float3; + var slot : WtoBotSlot&) + assume nav = slot.nav + let again = (now - nav.lastContactAt <= WTO_AI_PF_CONTACT_REPEAT_SEC && + wto_xz_dist_sq(myPos, nav.lastContactPos) <= WTO_AI_PF_JAM_RADIUS_M * WTO_AI_PF_JAM_RADIUS_M) + nav.lastContactAt = now + nav.lastContactPos = myPos + nav.contactSince = -100.0 + nav.contactEvents++ + nav.stuckCheckAt = -100.0 slot.route.replanRequested = true - print("WTO_AI|NAV_CONTACT|eid={uint(slot.eid)}|pos={myPos}\n") + if again + wto_unstick_contact_repeat(world, navState, now, myPos, slot) + else + nav.contactRepeats = 0 + print("WTO_AI|NAV_CONTACT|eid={uint(slot.eid)}|repeat={nav.contactRepeats}|pos={myPos}|body={nav.contactBodyPos}\n") wto_unstick_start_reverse(navState, now, myPos, hullFwd, slot) // Backing up after being stuck; true while the manoeuvre runs (the drive command is set). diff --git a/packages/patcher/src/ground-ai/ground-ai-config.ts b/packages/patcher/src/ground-ai/ground-ai-config.ts index 17e2f18..11c101b 100644 --- a/packages/patcher/src/ground-ai/ground-ai-config.ts +++ b/packages/patcher/src/ground-ai/ground-ai-config.ts @@ -64,6 +64,7 @@ export interface GroundAiPathFollow { readonly blockTtlSec: number; readonly contactGapM: number; readonly contactReverseSec: number; + readonly contactRepeatSec: number; readonly stuckWindowSec: number; readonly stuckMinProgressM: number; readonly unstickReverseM: number; @@ -483,6 +484,7 @@ function pathFollowEntries(p: GroundAiPathFollow): readonly DasEntry[] { ['WTO_AI_PF_BLOCK_TTL_SEC', 'float', p.blockTtlSec], ['WTO_AI_PF_CONTACT_GAP_M', 'float', p.contactGapM], ['WTO_AI_PF_CONTACT_REVERSE_SEC', 'float', p.contactReverseSec], + ['WTO_AI_PF_CONTACT_REPEAT_SEC', 'float', p.contactRepeatSec], ['WTO_AI_PF_STUCK_WINDOW_SEC', 'float', p.stuckWindowSec], ['WTO_AI_PF_STUCK_MIN_PROGRESS_M', 'float', p.stuckMinProgressM], ['WTO_AI_PF_UNSTICK_REV_M', 'float', p.unstickReverseM], From 4136021c8c3d22a659e93668f49a2431e5c57497 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sat, 5 Dec 2026 22:49:31 +0800 Subject: [PATCH 10/19] feat(ground-ai): log battle statistics for comparing builds The decision layer rework is judged against a baseline, so the runtime now accumulates per vehicle role and logs WTO_AI|BATTLE_STATS every diagnostics.statsLogIntervalSec and when the battle ends: - time from acquiring a ground target to the first shot at it, and targets let go without a shot; - time with a target in sight within range and the gun ready, split by the last reason a shot was refused (WTO_AI|BATTLE_STATS_FIRE); - shots by distance band and how many were fired on the move, and the autocannon rate; - every statsSampleSec, the nearest enemy in line of sight within statsSampleRangeM: whether the bot knows it, how far the turret is off it, and whether a tank or tank destroyer shows it its rear (statsRearArcDeg). The five diagnostics settings go through the server reader, the generated script constants and the launcher fields in both languages. --- .../src/renderer/src/i18n/locales/en.json | 7 +- .../src/renderer/src/i18n/locales/zh-CN.json | 7 +- .../src/pages/tuning/bot-tuning-fields.ts | 5 + apps/launcher/src/shared/schemas/tuning.ts | 5 + apps/server/src/tuning/ground-ai-tuning.ts | 5 + apps/server/tuning/ground-ai.jsonc | 11 +- game-ai/ground/wto_ai_runtime.das | 5 + game-ai/ground/wto_ai_stats_common.das | 216 ++++++++++++++++++ game-ai/ground/wto_ai_types_common.das | 11 + .../patcher/src/ground-ai/ground-ai-config.ts | 10 + 10 files changed, 279 insertions(+), 3 deletions(-) create mode 100644 game-ai/ground/wto_ai_stats_common.das diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index b63dfd4..4f6ead7 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -799,7 +799,12 @@ }, "diagnostics": { "telemetry": "Enable AI telemetry logs", - "telemetryIntervalSec": "Telemetry logging interval" + "telemetryIntervalSec": "Telemetry logging interval", + "battleStats": "Log battle statistics for comparing builds", + "statsLogIntervalSec": "Battle statistics logging interval", + "statsSampleSec": "Statistics sampling interval per bot", + "statsSampleRangeM": "Range of the nearest-enemy statistics sample", + "statsRearArcDeg": "Rear arc counted as showing the rear" } }, "shared": "These settings apply to all saves in this client.", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index a209d6d..522490d 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -799,7 +799,12 @@ }, "diagnostics": { "telemetry": "输出 AI 诊断遥测日志", - "telemetryIntervalSec": "遥测日志输出间隔" + "telemetryIntervalSec": "遥测日志输出间隔", + "battleStats": "输出用于版本对比的每局统计", + "statsLogIntervalSec": "每局统计的输出间隔", + "statsSampleSec": "每辆车的统计抽查间隔", + "statsSampleRangeM": "统计抽查最近敌人的范围", + "statsRearArcDeg": "算作车尾对敌的后方扇区角度" } }, "shared": "这些数值适用于此客户端的全部存档。", diff --git a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts index 1cc5ed8..a569ed3 100644 --- a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts +++ b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts @@ -375,6 +375,11 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ num('cadence', 'navTickSec', 0.05, 2, 's'), { id: 'groundAi.diagnostics.telemetry', section: 'diagnostics', field: 'telemetry', kind: 'bool' }, num('diagnostics', 'telemetryIntervalSec', 0.5, 60, 's'), + { id: 'groundAi.diagnostics.battleStats', section: 'diagnostics', field: 'battleStats', kind: 'bool' }, + num('diagnostics', 'statsLogIntervalSec', 10, 600, 's'), + num('diagnostics', 'statsSampleSec', 0.2, 5, 's'), + num('diagnostics', 'statsSampleRangeM', 50, 1000, 'm'), + num('diagnostics', 'statsRearArcDeg', 30, 180, '°'), ], }, ]; diff --git a/apps/launcher/src/shared/schemas/tuning.ts b/apps/launcher/src/shared/schemas/tuning.ts index 850e93c..3296b13 100644 --- a/apps/launcher/src/shared/schemas/tuning.ts +++ b/apps/launcher/src/shared/schemas/tuning.ts @@ -250,6 +250,11 @@ const GroundAiFireControlSchema = z.object({ const GroundAiDiagnosticsSchema = z.object({ telemetry: z.boolean(), telemetryIntervalSec: z.number().min(0.5).max(60), + battleStats: z.boolean(), + statsLogIntervalSec: z.number().min(10).max(600), + statsSampleSec: z.number().min(0.2).max(5), + statsSampleRangeM: z.number().min(50).max(1000), + statsRearArcDeg: z.number().min(30).max(180), }); export const GroundAiTuningSchema = z.object({ diff --git a/apps/server/src/tuning/ground-ai-tuning.ts b/apps/server/src/tuning/ground-ai-tuning.ts index f959970..76d882e 100644 --- a/apps/server/src/tuning/ground-ai-tuning.ts +++ b/apps/server/src/tuning/ground-ai-tuning.ts @@ -61,6 +61,11 @@ export function readGroundAiTuning(reader: TuningReader): GroundAiTuning { diagnostics: { telemetry: diag.bool('telemetry'), telemetryIntervalSec: diag.number('telemetryIntervalSec', { min: 0.5, max: 60 }), + battleStats: diag.bool('battleStats'), + statsLogIntervalSec: diag.number('statsLogIntervalSec', { min: 10, max: 600 }), + statsSampleSec: diag.number('statsSampleSec', { min: 0.2, max: 5 }), + statsSampleRangeM: diag.number('statsSampleRangeM', { min: 50, max: 1000 }), + statsRearArcDeg: diag.number('statsRearArcDeg', { min: 30, max: 180 }), }, }; } diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index 23efc43..68e5fa4 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -343,6 +343,15 @@ "diagnostics": { "telemetry": true, - "telemetryIntervalSec": 5.0 + "telemetryIntervalSec": 5.0, + // Battle statistics for comparing builds (WTO_AI|BATTLE_STATS): cumulative per vehicle class, + // logged every statsLogIntervalSec and when the battle ends. Every statsSampleSec each bot + // checks the nearest enemy in line of sight within statsSampleRangeM: whether it knows it, + // how far the turret is off it, and whether its rear (statsRearArcDeg wide) faces it. + "battleStats": true, + "statsLogIntervalSec": 60.0, + "statsSampleSec": 1.0, + "statsSampleRangeM": 300.0, + "statsRearArcDeg": 120.0 } } diff --git a/game-ai/ground/wto_ai_runtime.das b/game-ai/ground/wto_ai_runtime.das index d5f3309..8916db4 100644 --- a/game-ai/ground/wto_ai_runtime.das +++ b/game-ai/ground/wto_ai_runtime.das @@ -39,6 +39,7 @@ require %appGame.wtoai.wto_ai_navmesh_common require %appGame.wtoai.wto_ai_drive_common require %appGame.wtoai.wto_ai_fire_common require %appGame.wtoai.wto_ai_diag_common +require %appGame.wtoai.wto_ai_stats_common var private @safe_when_uninitialized g_world : WtoWorldSnap var private @safe_when_uninitialized g_crowd : WtoCrowdSummary @@ -52,6 +53,7 @@ var private g_last_zone_ver : int = -1 var private g_fire_budget : int = 0 var private g_next_diag_at : float = 0.0 var private @safe_when_uninitialized g_navmesh : WtoNavmeshBattle +var private @safe_when_uninitialized g_stats : WtoBattleStats // Custom ground AI must only run inside a real multiplayer battle. Single-player test // drives also dispatch tag=server ECS, but their target vehicles must never be taken over. @@ -66,6 +68,7 @@ def wto_ai_script_init() [never_inline] def private wto_reset_runtime() + wto_stats_battle_end(float(get_app().usefulTotalTime), g_stats) wto_world_reset(g_world) wto_lanes_reset(g_lanes) g_crowd = WtoCrowdSummary() @@ -240,6 +243,7 @@ def wto_ai_world_tick_es(act : UpdateStageInfoAct) g_next_diag_at = now + WTO_AI_DIAG_INTERVAL_SEC wto_diag_log_telemetry(g_world, now, g_bots, g_crowd) wto_navmesh_log_stats(g_navmesh) + wto_stats_tick(now, g_stats) [es(tag=server, no_order)] def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&; @@ -272,6 +276,7 @@ def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : if now >= slot.nextNavAt && g_navmesh.state != WTO_NAVMESH_FAILED slot.nextNavAt = now + WTO_AI_NAV_TICK_SEC wto_nav_update(g_world, g_navmesh.state, idx, now, unit.pos, unit.unitTm[0], slot) + wto_stats_bot_frame(g_world, now, act.dt, unit.pos, unit.unitTm[0], slot, g_stats) [es(tag=server, after=wto_ai_pipeline_es)] def wto_ai_phys_tick_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&; diff --git a/game-ai/ground/wto_ai_stats_common.das b/game-ai/ground/wto_ai_stats_common.das new file mode 100644 index 0000000..1004683 --- /dev/null +++ b/game-ai/ground/wto_ai_stats_common.das @@ -0,0 +1,216 @@ +// Battle statistics for comparing builds (decision layer design, section 12). Cumulative per +// vehicle role and logged as WTO_AI|BATTLE_STATS every statsLogIntervalSec and when the battle +// ends: time from acquiring a target to the first shot at it, time with a target in sight and the +// gun ready split by the last reason a shot was refused, shots by distance band and motion, and a +// sample every statsSampleSec of the nearest enemy in line of sight (known or not, turret error, +// rear facing it). +options indenting = 2 +options no_global_heap = true +module wto_ai_stats_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_sight_common + +// Arrays of five are indexed by WTO_ROLE_*; bands are within closeRangeM, within midRangeM and +// beyond; denySec is indexed by WTO_DENY_*. +[safe_when_uninitialized] +struct public WtoBattleStats + active : bool = false + nextLogAt : float = 0.0 + spotted : int[5] + spotShot : int[5] + spotShotSec : float[5] + spotNoShot : int[5] + windowSec : float[5] + samples : int[5] + unaware : int[5] + turretSamples : int[5] + turretErrSum : float[5] + rearSamples : int[5] + rearExposed : int[5] + shots : int[5] + movingShots : int[5] + bandShots : int[3] + bandMoving : int[3] + denySec : float[13] + acWindowSec : float = 0.0 + acShots : int = 0 + +def private wto_stats_role(slot : WtoBotSlot const&) : int + return clamp(slot.spec.role, 0, 4) + +def private wto_stats_role_name(role : int) : string + if role == WTO_ROLE_LIGHT + return "light" + if role == WTO_ROLE_HEAVY + return "heavy" + if role == WTO_ROLE_TD + return "td" + if role == WTO_ROLE_SPAA + return "spaa" + return "medium" + +def private wto_stats_ratio(part, whole : int) : float + return whole > 0 ? float(part) / float(whole) : 0.0 + +def private wto_stats_band(dist : float) : int + if dist <= WTO_AI_FC_CLOSE_RANGE_M + return 0 + return dist <= WTO_AI_FC_MID_RANGE_M ? 1 : 2 + +// A target acquired (seen clearly) and whether it was shot at before the bot let it go. +[never_inline] +def private wto_stats_spot(now : float; groundTgt : bool; var slot : WtoBotSlot&; var bs : WtoBattleStats&) + assume st = slot.stats + let role = wto_stats_role(slot) + if st.spotPending && slot.fire.shotCount > st.spotShots + st.spotPending = false + bs.spotShot[role]++ + bs.spotShotSec[role] += now - st.spotAt + let tgt = slot.perceive.targetEid + if groundTgt && tgt != st.spotEid + if st.spotPending + bs.spotNoShot[role]++ + st.spotEid = tgt + st.spotAt = now + st.spotShots = slot.fire.shotCount + st.spotPending = true + bs.spotted[role]++ + elif !tgt + if st.spotPending + bs.spotNoShot[role]++ + st.spotPending = false + st.spotEid = INVALID_ENTITY_ID + +[never_inline] +def private wto_stats_shots(myPos : float3; var slot : WtoBotSlot&; var bs : WtoBattleStats&) + assume st = slot.stats + let fired = slot.fire.shotCount - st.lastShots + st.lastShots = slot.fire.shotCount + if fired <= 0 + return + let role = wto_stats_role(slot) + let band = wto_stats_band(sqrt(wto_xz_dist_sq(myPos, slot.perceive.knownPos))) + bs.shots[role] += fired + bs.bandShots[band] += fired + if abs(slot.drive.lastVFwd) >= WTO_AI_PF_STATIONARY_MPS + bs.movingShots[role] += fired + bs.bandMoving[band] += fired + if slot.spec.isAutocannonBelt + bs.acShots += fired + +// A shooting window: a ground target seen clearly within engagement range and the gun ready. +[never_inline] +def private wto_stats_window(dt : float; myPos : float3; groundTgt : bool; slot : WtoBotSlot const&; + var bs : WtoBattleStats&) + if !groundTgt || !slot.fire.gunReady || slot.fire.reloading + return + if wto_xz_dist_sq(myPos, slot.perceive.knownPos) > WTO_AI_FC_MAX_RANGE_M * WTO_AI_FC_MAX_RANGE_M + return + bs.windowSec[wto_stats_role(slot)] += dt + bs.denySec[clamp(slot.fire.lastDenyReason, 0, 12)] += dt + if slot.spec.isAutocannonBelt + bs.acWindowSec += dt + +// The nearest enemy ground vehicle within statsSampleRangeM if it is in line of sight, else -1. +[never_inline] +def private wto_stats_nearest_seen(world : WtoWorldSnap const&; myPos : float3; slot : WtoBotSlot const&) : int + var best = -1 + var bestDistSq = WTO_AI_STATS_RANGE_M * WTO_AI_STATS_RANGE_M + for i in range(world.unitCount) + assume u = world.units[i] + if !u.isAlive || !u.isGround || u.army == slot.army + continue + let distSq = wto_xz_dist_sq(myPos, u.pos) + if distSq < bestDistSq + bestDistSq = distSq + best = i + if best < 0 + return -1 + let eye = myPos + float3(0.0, 2.15, 0.0) + assume enemy = world.units[best] + return wto_sight_visual_clear(world, slot.eid, enemy.eid, eye, enemy.pos + float3(0.0, 1.3, 0.0)) == WTO_BLOCK_NONE ? best : -1 + +def private wto_stats_knows(slot : WtoBotSlot const&; eid : EntityId) : bool + if slot.perceive.targetEid == eid + return true + for k in range(WTO_MAX_EXPOSURE_TRACKS) + if slot.perceive.expEids[k] == eid && slot.perceive.expScore[k] >= 0.5 + return true + return false + +[never_inline] +def private wto_stats_sample(world : WtoWorldSnap const&; now : float; myPos, hullFwd : float3; + var slot : WtoBotSlot&; var bs : WtoBattleStats&) + if now < slot.stats.nextSampleAt + return + slot.stats.nextSampleAt = now + WTO_AI_STATS_SAMPLE_SEC + let idx = wto_stats_nearest_seen(world, myPos, slot) + if idx < 0 + return + assume u = world.units[idx] + let role = wto_stats_role(slot) + let fwd = wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0)) + let toEnemy = wto_xz_normalize(u.pos - myPos, fwd) + bs.samples[role]++ + if !wto_stats_knows(slot, u.eid) + bs.unaware[role]++ + if slot.fire.servoInit + let yaw = atan2(fwd.z, fwd.x) - slot.fire.curYawDeg * WTO_DEG_TO_RAD + let gunDir = float3(cos(yaw), 0.0, sin(yaw)) + bs.turretSamples[role]++ + bs.turretErrSum[role] += acos(clamp(dot(gunDir, toEnemy), -1.0, 1.0)) * WTO_RAD_TO_DEG + if role == WTO_ROLE_MEDIUM || role == WTO_ROLE_HEAVY || role == WTO_ROLE_TD + bs.rearSamples[role]++ + if acos(clamp(dot(-fwd, toEnemy), -1.0, 1.0)) * WTO_RAD_TO_DEG <= WTO_AI_STATS_REAR_ARC_DEG * 0.5 + bs.rearExposed[role]++ + +// Per frame and bot, after fire control. +[never_inline] +def public wto_stats_bot_frame(world : WtoWorldSnap const&; now, dt : float; myPos, hullFwd : float3; + var slot : WtoBotSlot&; var bs : WtoBattleStats&) + if !WTO_AI_STATS_ENABLED + return + bs.active = true + let groundTgt = slot.perceive.hasClearLos && !!slot.perceive.targetEid && !slot.perceive.targetIsAir + wto_stats_spot(now, groundTgt, slot, bs) + wto_stats_shots(myPos, slot, bs) + wto_stats_window(dt, myPos, groundTgt, slot, bs) + wto_stats_sample(world, now, myPos, hullFwd, slot, bs) + +[never_inline] +def private wto_stats_log_role(now : float; why : string; role : int; bs : WtoBattleStats const&) + let spotAvg = bs.spotShot[role] > 0 ? bs.spotShotSec[role] / float(bs.spotShot[role]) : 0.0 + let turretErr = bs.turretSamples[role] > 0 ? bs.turretErrSum[role] / float(bs.turretSamples[role]) : 0.0 + print("WTO_AI|BATTLE_STATS|why={why}|t={now}|class={wto_stats_role_name(role)}|spotted={bs.spotted[role]}|spotToShotSec={spotAvg}|spotShot={bs.spotShot[role]}|spotNoShot={bs.spotNoShot[role]}|windowSec={bs.windowSec[role]}|samples={bs.samples[role]}|unaware={wto_stats_ratio(bs.unaware[role], bs.samples[role])}|turretErrDeg={turretErr}|rear={wto_stats_ratio(bs.rearExposed[role], bs.rearSamples[role])}|shots={bs.shots[role]}|moving={wto_stats_ratio(bs.movingShots[role], bs.shots[role])}\n") + +[never_inline] +def private wto_stats_log(now : float; why : string; bs : WtoBattleStats const&) + for role in range(5) + if bs.spotted[role] + bs.samples[role] + bs.shots[role] > 0 + wto_stats_log_role(now, why, role, bs) + assume d = bs.denySec + print("WTO_AI|BATTLE_STATS_FIRE|why={why}|t={now}|shotsBand={bs.bandShots[0]}/{bs.bandShots[1]}/{bs.bandShots[2]}|movingBand={bs.bandMoving[0]}/{bs.bandMoving[1]}/{bs.bandMoving[2]}|denySec=ok:{d[0]},noTarget:{d[1]},notReady:{d[2]},speed:{d[3]},longWindow:{d[4]},aimErr:{d[5]},settle:{d[6]},budget:{d[7]},muzzle:{d[8]},arc:{d[9]},friendly:{d[10]},multiGun:{d[11]},traverse:{d[12]}|acWindowSec={bs.acWindowSec}|acShots={bs.acShots}\n") + +// Per world tick: the cumulative statistics every statsLogIntervalSec. +[never_inline] +def public wto_stats_tick(now : float; var bs : WtoBattleStats&) + if !WTO_AI_STATS_ENABLED || !bs.active + return + if bs.nextLogAt <= 0.0 + bs.nextLogAt = now + WTO_AI_STATS_LOG_SEC + elif now >= bs.nextLogAt + bs.nextLogAt = now + WTO_AI_STATS_LOG_SEC + wto_stats_log(now, "periodic", bs) + +// Battle over (or a new one loading): the final statistics, then a clean slate. +[never_inline] +def public wto_stats_battle_end(now : float; var bs : WtoBattleStats&) + if WTO_AI_STATS_ENABLED && bs.active + wto_stats_log(now, "end", bs) + bs = WtoBattleStats() diff --git a/game-ai/ground/wto_ai_types_common.das b/game-ai/ground/wto_ai_types_common.das index d5ea123..a1e8964 100644 --- a/game-ai/ground/wto_ai_types_common.das +++ b/game-ai/ground/wto_ai_types_common.das @@ -221,6 +221,16 @@ struct public WtoDriveState prevStr : float = 0.0 lastVFwd : float = 0.0 +// Per-bot bookkeeping of the battle statistics (wto_ai_stats_common.das). +[safe_when_uninitialized] +struct public WtoBotStats + spotEid : EntityId = INVALID_ENTITY_ID + spotAt : float = -100.0 + spotShots : int = 0 + spotPending : bool = false + lastShots : int = 0 + nextSampleAt : float = 0.0 + [safe_when_uninitialized] struct public WtoBotSlot used : bool = false @@ -240,3 +250,4 @@ struct public WtoBotSlot driveCmd : WtoDriveCmd = WtoDriveCmd() drive : WtoDriveState = WtoDriveState() fire : WtoFireState = WtoFireState() + stats : WtoBotStats = WtoBotStats() diff --git a/packages/patcher/src/ground-ai/ground-ai-config.ts b/packages/patcher/src/ground-ai/ground-ai-config.ts index 11c101b..54b66ce 100644 --- a/packages/patcher/src/ground-ai/ground-ai-config.ts +++ b/packages/patcher/src/ground-ai/ground-ai-config.ts @@ -263,6 +263,11 @@ export interface GroundAiConfig { readonly diagnostics: { readonly telemetry: boolean; readonly telemetryIntervalSec: number; + readonly battleStats: boolean; + readonly statsLogIntervalSec: number; + readonly statsSampleSec: number; + readonly statsSampleRangeM: number; + readonly statsRearArcDeg: number; }; } @@ -444,6 +449,11 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['WTO_AI_FC_MAX_CHECKS_PER_TICK', 'int', c.fireControl.maxPreFireChecksPerTick], ['WTO_AI_DIAG_TELEMETRY', 'bool', c.diagnostics.telemetry], ['WTO_AI_DIAG_INTERVAL_SEC', 'float', c.diagnostics.telemetryIntervalSec], + ['WTO_AI_STATS_ENABLED', 'bool', c.diagnostics.battleStats], + ['WTO_AI_STATS_LOG_SEC', 'float', c.diagnostics.statsLogIntervalSec], + ['WTO_AI_STATS_SAMPLE_SEC', 'float', c.diagnostics.statsSampleSec], + ['WTO_AI_STATS_RANGE_M', 'float', c.diagnostics.statsSampleRangeM], + ['WTO_AI_STATS_REAR_ARC_DEG', 'float', c.diagnostics.statsRearArcDeg], ]; } From 1590a2fea9095faf38adc4246ba6097092078635 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sun, 6 Dec 2026 00:03:55 +0800 Subject: [PATCH 11/19] feat(ground-ai): layered perception, threat table and turret channel First step of the single-bot decision layer. Not yet checked in game: the decision layer is coupled, so it is tested once its hull and fire parts are in. Perception is layered: the gun sight covers perception.gunFovHalfDeg either side of the barrel; within nearAwareM the crew notices enemies around the hull except a rear blind arc, which a periodic look-around opens; within midAwareM the commander covers the hull's front half. Near and mid layers take longer to see an enemy clearly. Each track remembers when and where its enemy was last in sight. Each bot keeps a threat table of the enemies it has discovered, rated by distance, whether seen clearly, whether aiming at it or recently hitting it, and whether it is in their sight. Penetration is left out until the engine damage test is usable. The turret no longer rests on the hull's front: without a clearly seen target it looks at the most dangerous discovered threat, then the last exit, the remembered target, cues, and otherwise sweeps across the route. A threat clearly more dangerous than the engaged target takes the turret first. Bot slot bookkeeping moves out of the runtime entry into wto_ai_slots_common.das, and battle statistics count an enemy as known when it is in the threat table. Tuning: perception gains nine settings and loses frontConeHalfDeg and peripheralCloseM, tactics loses visionFovDeg and peripheralRangeM, and the new threat and turret sections are wired through the server reader, generated constants and launcher fields in both languages. --- .../src/renderer/src/i18n/locales/en.json | 32 ++++- .../src/renderer/src/i18n/locales/zh-CN.json | 32 ++++- .../src/pages/tuning/bot-tuning-fields.ts | 38 +++++- apps/launcher/src/shared/schemas/tuning.ts | 34 ++++- apps/server/src/tuning/ground-ai-tuning.ts | 36 ++++- apps/server/tuning/ground-ai.jsonc | 47 ++++++- game-ai/ground/wto_ai_combat_types_common.das | 33 +++++ game-ai/ground/wto_ai_fire_common.das | 13 +- game-ai/ground/wto_ai_perceive_common.das | 128 ++++++++++++------ game-ai/ground/wto_ai_runtime.das | 107 +++------------ game-ai/ground/wto_ai_slots_common.das | 113 ++++++++++++++++ game-ai/ground/wto_ai_stats_common.das | 6 +- game-ai/ground/wto_ai_threat_common.das | 76 +++++++++++ game-ai/ground/wto_ai_turret_common.das | 70 ++++++++++ game-ai/ground/wto_ai_types_common.das | 2 + .../patcher/src/ground-ai/ground-ai-config.ts | 52 +++++-- 16 files changed, 642 insertions(+), 177 deletions(-) create mode 100644 game-ai/ground/wto_ai_slots_common.das create mode 100644 game-ai/ground/wto_ai_threat_common.das create mode 100644 game-ai/ground/wto_ai_turret_common.das diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 4f6ead7..da1d14a 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -533,6 +533,8 @@ "perception": "Visual perception & exposure", "tactics": "Situational awareness & memory", "estimation": "Lead estimation & aim bias", + "threat": "Threat assessment", + "turret": "Turret attention", "fireControl": "Fire control & fire gate", "navigation": "Driving & navigation", "navEngine": "Map navigation mesh & path costs", @@ -551,6 +553,8 @@ "perception": "Foliage transparency, exposure accumulation and decay", "tactics": "Vision range, audio detection, radio sharing and target memory", "estimation": "Sample-based velocity lead, exit watch and natural shot spread", + "threat": "How dangerous each discovered enemy is: distance, aim, line of sight and recent hits", + "turret": "Where the turret looks without a target: threats, cues and scanning along the route", "fireControl": "Range bands, speed gates, barrel settle and ballistic safety", "navigation": "Drive backend, pivot turns and tactical reverse", "navEngine": "Baked map navigation packs, their fallback, and path costs per surface for tracked and wheeled vehicles", @@ -639,13 +643,18 @@ "normalSpotSec": "Normal exposure spot time", "farSpotSec": "Long-range exposure spot time", "decayPerSec": "Exposure decay rate per second", - "frontConeHalfDeg": "Forward vision cone half-angle", - "peripheralCloseM": "Close peripheral spot distance" + "gunFovHalfDeg": "Gun sight half-angle", + "nearAwareM": "Close all-round awareness range", + "nearArcDeg": "Close awareness arc around the hull", + "midAwareM": "Commander awareness range (hull front half)", + "nearSpotMul": "Close awareness spotting time multiplier", + "midSpotMul": "Commander awareness spotting time multiplier", + "lookAroundSec": "Look-around interval", + "lookAroundHoldSec": "Look-around duration", + "discoverScore": "Exposure at which an enemy counts as discovered" }, "tactics": { "visionRangeM": "Max visual detection range", - "visionFovDeg": "Vision field of view", - "peripheralRangeM": "Peripheral detection range", "engineAudioRangeM": "Engine audio hearing range", "shotAudioRangeM": "Gunshot audio hearing range", "radioShareRangeM": "Allied radio sharing range", @@ -663,6 +672,21 @@ "leadErrorFrac": "Lead estimation error fraction", "maxBiasM": "Max per-opportunity aim bias" }, + "threat": { + "rangeScaleM": "Distance at which danger halves", + "discoveredMul": "Danger multiplier until seen clearly", + "aimConeDeg": "Cone in which an enemy counts as aiming at the bot", + "notAimingMul": "Danger multiplier when not aiming at the bot", + "unseenMul": "Danger multiplier when the bot is out of its sight", + "hitMemorySec": "How long a hit raises the shooter's danger", + "hitMul": "Danger multiplier after a hit" + }, + "turret": { + "minDwellSec": "Minimum time on a chosen look direction", + "switchMargin": "Extra danger needed to turn from the engaged target", + "scanArcDeg": "Scan arc either side of the route", + "scanPeriodSec": "Scan sweep period" + }, "fireControl": { "maxEngageRangeM": "Max engagement range", "closeRangeM": "Close range band threshold", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index 522490d..2be4ada 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -533,6 +533,8 @@ "perception": "视觉感知与曝光", "tactics": "态势感知与目标记忆", "estimation": "目击测速与瞄准偏差", + "threat": "威胁评估", + "turret": "炮塔关注方向", "fireControl": "火控与开火许可", "navigation": "机动与寻路控制", "navEngine": "地图导航网格与通行代价", @@ -551,6 +553,8 @@ "perception": "植被透光、曝光累计速度与衰减", "tactics": "视距、听觉发现范围、电台共享与记忆时长", "estimation": "本车目击测速、守出口时长与自然散布", + "threat": "每个已发现敌人的危险程度:距离、是否瞄着本车、视线与最近是否命中本车", + "turret": "没有目标时炮塔看哪里:威胁、线索与沿路线扫视", "fireControl": "距离分档、车速门槛、稳定等待与弹道防误伤", "navigation": "驱动方式、原地转向与战术倒车", "navEngine": "离线地图导航包的启用与降级,以及履带 / 轮式车在各类地表上的寻路代价", @@ -639,13 +643,18 @@ "normalSpotSec": "常规曝光用时", "farSpotSec": "远距曝光用时", "decayPerSec": "失联曝光每秒衰减率", - "frontConeHalfDeg": "前向主视锥半角", - "peripheralCloseM": "近身余光发现距离" + "gunFovHalfDeg": "瞄准镜视野半角", + "nearAwareM": "近距环视感知距离", + "nearArcDeg": "近距感知覆盖车体周围的角度", + "midAwareM": "车长感知距离(车体前半球)", + "nearSpotMul": "近距感知看清耗时倍数", + "midSpotMul": "车长感知看清耗时倍数", + "lookAroundSec": "环视间隔", + "lookAroundHoldSec": "环视持续时间", + "discoverScore": "曝光积分达到多少算发现" }, "tactics": { "visionRangeM": "最大视觉索敌距离", - "visionFovDeg": "视野总张角", - "peripheralRangeM": "外围余光索敌距离", "engineAudioRangeM": "引擎声听觉距离", "shotAudioRangeM": "炮声听觉距离", "radioShareRangeM": "友军电台报点共享距离", @@ -663,6 +672,21 @@ "leadErrorFrac": "提前量误差比例", "maxBiasM": "单次射击最大偏移上限" }, + "threat": { + "rangeScaleM": "危险度减半的距离", + "discoveredMul": "尚未看清时的危险度倍数", + "aimConeDeg": "算作对方瞄着本车的夹角范围", + "notAimingMul": "对方没瞄着本车时的危险度倍数", + "unseenMul": "本车不在对方视线内时的危险度倍数", + "hitMemorySec": "被命中后提高射手危险度的时长", + "hitMul": "被命中后的危险度倍数" + }, + "turret": { + "minDwellSec": "选定的观察方向至少保持的时间", + "switchMargin": "从交战目标转向其他威胁所需高出的危险度", + "scanArcDeg": "沿路线向两侧扫视的角度", + "scanPeriodSec": "扫视一个来回的时长" + }, "fireControl": { "maxEngageRangeM": "最大交战开火距离", "closeRangeM": "近距交战分界距离", diff --git a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts index a569ed3..5fb1f94 100644 --- a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts +++ b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts @@ -189,8 +189,15 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ num('perception', 'normalSpotSec', 0.1, 3, 's'), num('perception', 'farSpotSec', 0.3, 6, 's'), num('perception', 'decayPerSec', 0.2, 10), - num('perception', 'frontConeHalfDeg', 10, 90, '°'), - num('perception', 'peripheralCloseM', 30, 250, 'm'), + num('perception', 'gunFovHalfDeg', 5, 90, '°'), + num('perception', 'nearAwareM', 30, 400, 'm'), + num('perception', 'nearArcDeg', 90, 360, '°'), + num('perception', 'midAwareM', 100, 1500, 'm'), + num('perception', 'nearSpotMul', 1, 5), + num('perception', 'midSpotMul', 1, 6), + num('perception', 'lookAroundSec', 2, 60, 's'), + num('perception', 'lookAroundHoldSec', 0.2, 5, 's'), + num('perception', 'discoverScore', 0.05, 0.95), ], }, { @@ -199,8 +206,6 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ customOnly: true, fields: [ num('tactics', 'visionRangeM', 200, 3500, 'm'), - num('tactics', 'visionFovDeg', 40, 180, '°'), - num('tactics', 'peripheralRangeM', 30, 800, 'm'), num('tactics', 'engineAudioRangeM', 10, 250, 'm'), num('tactics', 'shotAudioRangeM', 50, 1200, 'm'), num('tactics', 'radioShareRangeM', 50, 1500, 'm'), @@ -224,6 +229,31 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ num('estimation', 'maxBiasM', 0, 6, 'm'), ], }, + { + id: 'threat', + defaultOpen: false, + customOnly: true, + fields: [ + num('threat', 'rangeScaleM', 50, 3000, 'm'), + num('threat', 'discoveredMul', 0, 1), + num('threat', 'aimConeDeg', 5, 90, '°'), + num('threat', 'notAimingMul', 0, 1), + num('threat', 'unseenMul', 0, 1), + num('threat', 'hitMemorySec', 0, 60, 's'), + num('threat', 'hitMul', 1, 5), + ], + }, + { + id: 'turret', + defaultOpen: false, + customOnly: true, + fields: [ + num('turret', 'minDwellSec', 0, 5, 's'), + num('turret', 'switchMargin', 0, 3), + num('turret', 'scanArcDeg', 0, 180, '°'), + num('turret', 'scanPeriodSec', 1, 30, 's'), + ], + }, { id: 'fireControl', defaultOpen: false, diff --git a/apps/launcher/src/shared/schemas/tuning.ts b/apps/launcher/src/shared/schemas/tuning.ts index 3296b13..c900114 100644 --- a/apps/launcher/src/shared/schemas/tuning.ts +++ b/apps/launcher/src/shared/schemas/tuning.ts @@ -176,8 +176,15 @@ const GroundAiPerceptionSchema = z.object({ normalSpotSec: z.number().min(0.1).max(3), farSpotSec: z.number().min(0.3).max(6), decayPerSec: z.number().min(0.2).max(10), - frontConeHalfDeg: z.number().min(10).max(90), - peripheralCloseM: z.number().min(30).max(250), + gunFovHalfDeg: z.number().min(5).max(90), + nearAwareM: z.number().min(30).max(400), + nearArcDeg: z.number().min(90).max(360), + midAwareM: z.number().min(100).max(1500), + nearSpotMul: z.number().min(1).max(5), + midSpotMul: z.number().min(1).max(6), + lookAroundSec: z.number().min(2).max(60), + lookAroundHoldSec: z.number().min(0.2).max(5), + discoverScore: z.number().min(0.05).max(0.95), }); const GroundAiStateMachineSchema = z.object({ @@ -202,8 +209,6 @@ const GroundAiStateMachineSchema = z.object({ const GroundAiTacticsSchema = z.object({ visionRangeM: z.number().min(200).max(3500), - visionFovDeg: z.number().min(40).max(180), - peripheralRangeM: z.number().min(30).max(800), engineAudioRangeM: z.number().min(10).max(250), shotAudioRangeM: z.number().min(50).max(1200), radioShareRangeM: z.number().min(50).max(1500), @@ -212,6 +217,23 @@ const GroundAiTacticsSchema = z.object({ peekCooldownSec: z.number().min(1).max(30), }); +const GroundAiThreatSchema = z.object({ + rangeScaleM: z.number().min(50).max(3000), + discoveredMul: z.number().min(0).max(1), + aimConeDeg: z.number().min(5).max(90), + notAimingMul: z.number().min(0).max(1), + unseenMul: z.number().min(0).max(1), + hitMemorySec: z.number().min(0).max(60), + hitMul: z.number().min(1).max(5), +}); + +const GroundAiTurretSchema = z.object({ + minDwellSec: z.number().min(0).max(5), + switchMargin: z.number().min(0).max(3), + scanArcDeg: z.number().min(0).max(180), + scanPeriodSec: z.number().min(1).max(30), +}); + const GroundAiEstimationSchema = z.object({ watchMinSec: z.number().min(0.5).max(10), watchMaxSec: z.number().min(1).max(15), @@ -275,6 +297,8 @@ export const GroundAiTuningSchema = z.object({ stateMachine: GroundAiStateMachineSchema, tactics: GroundAiTacticsSchema, estimation: GroundAiEstimationSchema, + threat: GroundAiThreatSchema, + turret: GroundAiTurretSchema, fireControl: GroundAiFireControlSchema, diagnostics: GroundAiDiagnosticsSchema, }); @@ -297,6 +321,8 @@ export const GroundAiTuningPatchSchema = z.object({ stateMachine: GroundAiStateMachineSchema.partial().optional(), tactics: GroundAiTacticsSchema.partial().optional(), estimation: GroundAiEstimationSchema.partial().optional(), + threat: GroundAiThreatSchema.partial().optional(), + turret: GroundAiTurretSchema.partial().optional(), fireControl: GroundAiFireControlSchema.partial().optional(), diagnostics: GroundAiDiagnosticsSchema.partial().optional(), }); diff --git a/apps/server/src/tuning/ground-ai-tuning.ts b/apps/server/src/tuning/ground-ai-tuning.ts index 76d882e..2865a5c 100644 --- a/apps/server/src/tuning/ground-ai-tuning.ts +++ b/apps/server/src/tuning/ground-ai-tuning.ts @@ -57,6 +57,8 @@ export function readGroundAiTuning(reader: TuningReader): GroundAiTuning { stateMachine: readStateMachineSection(reader.object('stateMachine')), tactics: readTacticsSection(reader.object('tactics')), estimation: readEstimationSection(reader.object('estimation')), + threat: readThreatSection(reader.object('threat')), + turret: readTurretSection(reader.object('turret')), fireControl: readFireControlSection(reader.object('fireControl')), diagnostics: { telemetry: diag.bool('telemetry'), @@ -304,8 +306,15 @@ function readPerceptionSection(perc: TuningReader): GroundAiTuning['perception'] normalSpotSec: perc.number('normalSpotSec', { min: 0.1, max: 3.0 }), farSpotSec: perc.number('farSpotSec', { min: 0.3, max: 6.0 }), decayPerSec: perc.number('decayPerSec', { min: 0.2, max: 10.0 }), - frontConeHalfDeg: perc.number('frontConeHalfDeg', { min: 10, max: 90 }), - peripheralCloseM: perc.number('peripheralCloseM', { min: 30, max: 250 }), + gunFovHalfDeg: perc.number('gunFovHalfDeg', { min: 5, max: 90 }), + nearAwareM: perc.number('nearAwareM', { min: 30, max: 400 }), + nearArcDeg: perc.number('nearArcDeg', { min: 90, max: 360 }), + midAwareM: perc.number('midAwareM', { min: 100, max: 1500 }), + nearSpotMul: perc.number('nearSpotMul', { min: 1, max: 5 }), + midSpotMul: perc.number('midSpotMul', { min: 1, max: 6 }), + lookAroundSec: perc.number('lookAroundSec', { min: 2, max: 60 }), + lookAroundHoldSec: perc.number('lookAroundHoldSec', { min: 0.2, max: 5 }), + discoverScore: perc.number('discoverScore', { min: 0.05, max: 0.95 }), }; } @@ -339,8 +348,6 @@ function readStateMachineSection(sm: TuningReader): GroundAiTuning['stateMachine function readTacticsSection(tactics: TuningReader): GroundAiTuning['tactics'] { return { visionRangeM: tactics.number('visionRangeM', { min: 200, max: 3500 }), - visionFovDeg: tactics.number('visionFovDeg', { min: 40, max: 180 }), - peripheralRangeM: tactics.number('peripheralRangeM', { min: 30, max: 800 }), engineAudioRangeM: tactics.number('engineAudioRangeM', { min: 10, max: 250 }), shotAudioRangeM: tactics.number('shotAudioRangeM', { min: 50, max: 1200 }), radioShareRangeM: tactics.number('radioShareRangeM', { min: 50, max: 1500 }), @@ -350,6 +357,27 @@ function readTacticsSection(tactics: TuningReader): GroundAiTuning['tactics'] { }; } +function readThreatSection(threat: TuningReader): GroundAiTuning['threat'] { + return { + rangeScaleM: threat.number('rangeScaleM', { min: 50, max: 3000 }), + discoveredMul: threat.number('discoveredMul', { min: 0, max: 1 }), + aimConeDeg: threat.number('aimConeDeg', { min: 5, max: 90 }), + notAimingMul: threat.number('notAimingMul', { min: 0, max: 1 }), + unseenMul: threat.number('unseenMul', { min: 0, max: 1 }), + hitMemorySec: threat.number('hitMemorySec', { min: 0, max: 60 }), + hitMul: threat.number('hitMul', { min: 1, max: 5 }), + }; +} + +function readTurretSection(turret: TuningReader): GroundAiTuning['turret'] { + return { + minDwellSec: turret.number('minDwellSec', { min: 0, max: 5 }), + switchMargin: turret.number('switchMargin', { min: 0, max: 3 }), + scanArcDeg: turret.number('scanArcDeg', { min: 0, max: 180 }), + scanPeriodSec: turret.number('scanPeriodSec', { min: 1, max: 30 }), + }; +} + function readEstimationSection(est: TuningReader): GroundAiTuning['estimation'] { const watchMinSec = est.number('watchMinSec', { min: 0.5, max: 10.0 }); const watchMaxSec = est.number('watchMaxSec', { min: 1.0, max: 15.0 }); diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index 68e5fa4..a001f75 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -265,8 +265,21 @@ "normalSpotSec": 0.60, "farSpotSec": 1.45, "decayPerSec": 1.5, - "frontConeHalfDeg": 60.0, - "peripheralCloseM": 100.0 + // Layered awareness (decision layer design, section 3): the gun sight sees gunFovHalfDeg either + // side of the barrel; within nearAwareM the crew notices enemies all round the hull except a + // rear blind arc (nearArcDeg wide is covered), and every lookAroundSec for lookAroundHoldSec + // the rear too; within midAwareM the commander covers the hull's front half. Near and mid + // spotting take nearSpotMul / midSpotMul times as long as through the gun sight. An enemy whose + // exposure reaches discoverScore counts as discovered (position known, not yet fireable). + "gunFovHalfDeg": 30.0, + "nearAwareM": 150.0, + "nearArcDeg": 270.0, + "midAwareM": 600.0, + "nearSpotMul": 1.5, + "midSpotMul": 2.0, + "lookAroundSec": 8.0, + "lookAroundHoldSec": 1.0, + "discoverScore": 0.35 }, // Per-bot hull state machine timings and thresholds (offline values). @@ -293,9 +306,7 @@ "tactics": { "visionRangeM": 1250.0, - "visionFovDeg": 115.0, - "peripheralRangeM": 230.0, - "engineAudioRangeM": 65.0, + "engineAudioRangeM": 150.0, "shotAudioRangeM": 380.0, "radioShareRangeM": 450.0, "memoryTtlSec": 12.0, @@ -315,6 +326,32 @@ "maxBiasM": 2.2 }, + // Threat table (decision layer design, section 4): how dangerous each discovered enemy is to the + // bot. Danger falls with distance as 1 / (1 + distance / rangeScaleM) and is multiplied by + // discoveredMul until the enemy is seen clearly, by notAimingMul unless its hull or gun points + // within aimConeDeg of the bot (or it hit the bot), by unseenMul when the bot is out of its + // sight, and by hitMul for hitMemorySec after it hit the bot. Penetration is not counted yet. + "threat": { + "rangeScaleM": 400.0, + "discoveredMul": 0.7, + "aimConeDeg": 25.0, + "notAimingMul": 0.5, + "unseenMul": 0.4, + "hitMemorySec": 6.0, + "hitMul": 2.0 + }, + + // Turret channel (decision layer design, section 5): with no target in sight the turret looks at + // the most dangerous discovered threat, then at cues, then sweeps scanArcDeg either side of the + // route over scanPeriodSec. It turns from the engaged target to another threat only when that + // one is switchMargin more dangerous, and keeps a chosen look for at least minDwellSec. + "turret": { + "minDwellSec": 0.6, + "switchMargin": 0.25, + "scanArcDeg": 60.0, + "scanPeriodSec": 6.0 + }, + "fireControl": { "maxEngageRangeM": 1250.0, "closeRangeM": 100.0, diff --git a/game-ai/ground/wto_ai_combat_types_common.das b/game-ai/ground/wto_ai_combat_types_common.das index 14a0301..a949a3f 100644 --- a/game-ai/ground/wto_ai_combat_types_common.das +++ b/game-ai/ground/wto_ai_combat_types_common.das @@ -76,6 +76,39 @@ struct public WtoPerceiveState expEids : EntityId[8] expScore : float[8] expGoodLosSec : float[8] + expSeenAt : float[8] + expPos : float3[8] + nextLookAroundAt : float = 0.0 + lookAroundUntil : float = -100.0 + +// One discovered enemy in the bot's threat table (decision layer design, section 4). `seen`: seen +// clearly (fireable); `seesMe`: in line of sight this tick; `aiming`: its hull points at the bot or +// it hit the bot recently. +[safe_when_uninitialized] +struct public WtoThreatEntry + eid : EntityId = INVALID_ENTITY_ID + seen : bool = false + pos : float3 = float3(0.0, 0.0, 0.0) + dist : float = 0.0 + aiming : bool = false + seesMe : bool = false + danger : float = 0.0 + +// Rebuilt every perception tick; topIdx is the most dangerous entry, topUnseenIdx the most +// dangerous one not seen clearly yet (both -1 when there is none). +[safe_when_uninitialized] +struct public WtoThreatTable + count : int = 0 + entries : WtoThreatEntry[8] + topIdx : int = -1 + topUnseenIdx : int = -1 + +// Turret channel (decision layer design, section 5): the threat it is looking at and until when +// that look is held. +[safe_when_uninitialized] +struct public WtoTurretState + lookEid : EntityId = INVALID_ENTITY_ID + holdUntil : float = -100.0 [safe_when_uninitialized] struct public WtoGunTraverse diff --git a/game-ai/ground/wto_ai_fire_common.das b/game-ai/ground/wto_ai_fire_common.das index 73bfcbd..a2dd027 100644 --- a/game-ai/ground/wto_ai_fire_common.das +++ b/game-ai/ground/wto_ai_fire_common.das @@ -23,6 +23,7 @@ require %appGame.wtoai.wto_ai_world_common require %appGame.wtoai.wto_ai_estimate_common require %appGame.wtoai.wto_ai_fire_gate_common require %appGame.wtoai.wto_ai_traverse_common +require %appGame.wtoai.wto_ai_turret_common [never_inline] def private wto_sync_active_shell(gun : WTGun const?; spec : WtoVehicleSpec const&; var fc : WtoFireState&) @@ -220,17 +221,15 @@ def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; classN var wishWorldDir = hFwd var aimPt = muzzlePos + hFwd * 50.0 var distToTgt = 9999.0 + // A clearly seen target is aimed at unless a more dangerous threat calls the turret away; + // otherwise the turret channel picks where to look (wto_ai_turret_common.das). let engageValid = (slot.perceive.hasClearLos && !!slot.perceive.targetEid && !slot.perceive.targetIsAir && - !(slot.spec.role == WTO_ROLE_SPAA && slot.tactics.state == WTO_STATE_DISABLED)) + !(slot.spec.role == WTO_ROLE_SPAA && slot.tactics.state == WTO_STATE_DISABLED) && !wto_turret_prefers_threat(slot)) if engageValid let baseAim = slot.perceive.visibleAimPt distToTgt = wto_solve_ballistic_aim(muzzlePos, unit.vel, slot, baseAim, aimPt, wishWorldDir) - elif now < slot.perceive.watchUntil - wishWorldDir = normalize(slot.perceive.watchPos - muzzlePos) - elif !!slot.perceive.targetEid && (now - slot.perceive.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC - wishWorldDir = normalize((slot.perceive.knownPos + float3(0.0, 1.4, 0.0)) - muzzlePos) - elif now < slot.perceive.alertUntil - wishWorldDir = float3(cos(slot.perceive.alertYawRad), 0.0, sin(slot.perceive.alertYawRad)) + else + wishWorldDir = wto_turret_look_dir(now, muzzlePos, unit.pos, hFwd, slot) var wishYaw = 0.0 var wishPitch = 0.0 diff --git a/game-ai/ground/wto_ai_perceive_common.das b/game-ai/ground/wto_ai_perceive_common.das index afb560b..c46018d 100644 --- a/game-ai/ground/wto_ai_perceive_common.das +++ b/game-ai/ground/wto_ai_perceive_common.das @@ -54,7 +54,7 @@ def private wto_exp_decay_all(world : WtoWorldSnap const&; dt : float; var p : W [never_inline] def private wto_spot_fill_time(dist : float; cosAngle : float; isShooting : bool; visCount : int) : float - let cosFront = cos(WTO_AI_PERC_FRONT_CONE_DEG * WTO_DEG_TO_RAD) + let cosFront = cos(WTO_AI_PERC_GUN_FOV_HALF_DEG * WTO_DEG_TO_RAD) var t = WTO_AI_PERC_FAR_SPOT_SEC if dist < WTO_AI_PERC_NEAR_SPOT_M || (isShooting && dist < WTO_AI_PERC_FIRING_SPOT_M) t = WTO_AI_PERC_FAST_SPOT_SEC @@ -99,15 +99,70 @@ def private wto_update_audio_and_radio_alerts(world : WtoWorldSnap const&; now : p.alertUntil = now + 2.8 return +// Spotting-time multiplier of the perception layer that covers an enemy (decision layer design, +// section 3.1): 1 in the gun sight, nearSpotMul within close awareness around the hull (the rear +// blind arc only during a look-around), midSpotMul in the commander's front half; 0 when no layer +// covers it. +def private wto_perc_layer_mul(dist, cosGun, cosHull : float; lookAround : bool) : float + if cosGun >= cos(WTO_AI_PERC_GUN_FOV_HALF_DEG * WTO_DEG_TO_RAD) + return 1.0 + if dist <= WTO_AI_PERC_NEAR_AWARE_M && (lookAround || cosHull >= cos(0.5 * WTO_AI_PERC_NEAR_ARC_DEG * WTO_DEG_TO_RAD)) + return WTO_AI_PERC_NEAR_SPOT_MUL + if dist <= WTO_AI_PERC_MID_AWARE_M && cosHull >= 0.0 + return WTO_AI_PERC_MID_SPOT_MUL + return 0.0 + +// Integrates one enemy's exposure this tick; its track index, or -1 when no perception layer +// covers it or it is hidden. `vis` gets the visible sample count, `aimPt` the first visible one. +[never_inline] +def private wto_exp_observe(world : WtoWorldSnap const&; now, dt : float; myEye, lookDir, hullDir : float3; + lookAround : bool; u : WtoUnitSnap const&; var slot : WtoBotSlot&; + var vis : int&; var aimPt : float3&) : int + assume p = slot.perceive + let delta = u.pos - myEye + let dist = length(delta) + if dist > (u.isAir ? 2600.0 : WTO_AI_TACTICS_VISION_RANGE_M) || dist < 1.0 + return -1 + let dirXZ = wto_xz_normalize(delta, lookDir) + let cosAng = dot(dirXZ, lookDir) + let layerMul = u.isAir ? 1.0 : wto_perc_layer_mul(dist, cosAng, dot(dirXZ, hullDir), lookAround) + if layerMul <= 0.0 + return -1 + aimPt = u.pos + float3(0.0, 1.3, 0.0) + vis = wto_sight_check_target_samples(world, slot.eid, myEye, u, dist > WTO_AI_FC_LONG_RANGE_M ? 2 : 4, aimPt) + if vis <= 0 + for k in range(WTO_MAX_EXPOSURE_TRACKS) + if p.expEids[k] == u.eid + p.expGoodLosSec[k] = 0.0 + return -1 + let tIdx = wto_exp_find_or_alloc(p, u.eid) + let fillSec = wto_spot_fill_time(dist, cosAng, u.isShooting, vis) * layerMul + p.expScore[tIdx] = clamp(p.expScore[tIdx] + WTO_AI_PERC_DECAY_PER_SEC * dt + dt / fillSec, 0.0, 1.0) + p.expGoodLosSec[tIdx] = vis >= 2 ? (p.expGoodLosSec[tIdx] + dt) : 0.0 + p.expSeenAt[tIdx] = now + p.expPos[tIdx] = u.pos + return tIdx + +// Target preference among clearly seen enemies: lower is better. +def private wto_exp_target_score(now, dist : float; u : WtoUnitSnap const&; isSpaa : bool; p : WtoPerceiveState const&) : float + var score = dist - (u.isAir && isSpaa ? 900.0 : 0.0) + if u.eid == p.lockedEid && now < p.lockedUntil + score -= 320.0 + elif u.eid == p.lastOffenderEid && (now - p.lastDamagedAt) <= 5.0 + score -= 90.0 + elif u.isShooting && dist < 220.0 + score -= 35.0 + if dist < 45.0 + score -= 180.0 + return score + [never_inline] def private wto_scan_visual_exposure(world : WtoWorldSnap const&; now, dt : float; - myEye, lookDir : float3; var slot : WtoBotSlot&; + myEye, lookDir, hullDir : float3; lookAround : bool; var slot : WtoBotSlot&; var outBestIdx, outVisCount : int&; var outGoodLosSec : float&; var outAimPt : float3&) assume p = slot.perceive - let cosHalfFov = cos(0.5 * WTO_AI_TACTICS_VISION_FOV_DEG * WTO_DEG_TO_RAD) let isSpaa = slot.spec.role == WTO_ROLE_SPAA - let decay = WTO_AI_PERC_DECAY_PER_SEC * dt var bestScore = 1.0e9 outBestIdx = -1 outVisCount = 0 @@ -116,62 +171,49 @@ def private wto_scan_visual_exposure(world : WtoWorldSnap const&; now, dt : floa assume u = world.units[i] if !u.isAlive || u.army == slot.army || (u.isAir && !isSpaa) continue - let delta = u.pos - myEye - let dist = length(delta) - let maxRange = u.isAir ? 2600.0 : WTO_AI_TACTICS_VISION_RANGE_M - if dist > maxRange || dist < 1.0 + var vis = 0 + var aimPt = u.pos + let tIdx = wto_exp_observe(world, now, dt, myEye, lookDir, hullDir, lookAround, u, slot, vis, aimPt) + if tIdx < 0 || p.expScore[tIdx] < 0.999 continue - let dirXZ = wto_xz_normalize(delta, lookDir) - let cosAng = dot(dirXZ, lookDir) - let inFov = cosAng >= cosHalfFov || (dist <= WTO_AI_PERC_PERIPH_CLOSE_M && cosAng >= 0.0) - if !inFov && !u.isAir - continue - let maxSamples = dist > WTO_AI_FC_LONG_RANGE_M ? 2 : 4 - var samplePt = u.pos + float3(0.0, 1.3, 0.0) - let vis = wto_sight_check_target_samples(world, slot.eid, myEye, u, maxSamples, samplePt) - if vis <= 0 - for k in range(WTO_MAX_EXPOSURE_TRACKS) - if p.expEids[k] == u.eid - p.expGoodLosSec[k] = 0.0 - continue - let tIdx = wto_exp_find_or_alloc(p, u.eid) - let fillSec = wto_spot_fill_time(dist, cosAng, u.isShooting, vis) - p.expScore[tIdx] = clamp(p.expScore[tIdx] + decay + dt / fillSec, 0.0, 1.0) - p.expGoodLosSec[tIdx] = vis >= 2 ? (p.expGoodLosSec[tIdx] + dt) : 0.0 - if p.expScore[tIdx] < 0.999 - continue - var score = dist - (u.isAir && isSpaa ? 900.0 : 0.0) - if u.eid == p.lockedEid && now < p.lockedUntil - score -= 320.0 - elif u.eid == p.lastOffenderEid && (now - p.lastDamagedAt) <= 5.0 - score -= 90.0 - elif u.isShooting && dist < 220.0 - score -= 35.0 - if dist < 45.0 - score -= 180.0 + let score = wto_exp_target_score(now, length(u.pos - myEye), u, isSpaa, p) if score < bestScore bestScore = score outBestIdx = i outVisCount = vis outGoodLosSec = p.expGoodLosSec[tIdx] - outAimPt = samplePt + outAimPt = aimPt + +// The gun sight's flat direction (the hull's until the turret servo is known), and the +// look-around (pressing C): every lookAroundSec, while not engaging, the rear blind arc opens. +[never_inline] +def private wto_perc_look(now : float; hullDir : float3; var slot : WtoBotSlot&; var lookDir : float3&) : bool + assume p = slot.perceive + lookDir = hullDir + if slot.fire.servoInit + let worldYaw = atan2(hullDir.z, hullDir.x) - slot.fire.curYawDeg * WTO_DEG_TO_RAD + lookDir = float3(cos(worldYaw), 0.0, sin(worldYaw)) + if p.nextLookAroundAt <= 0.0 + p.nextLookAroundAt = now + float(int(uint(slot.eid) % 8u)) + elif now >= p.nextLookAroundAt && !p.hasClearLos + p.lookAroundUntil = now + WTO_AI_PERC_LOOK_AROUND_HOLD_SEC + p.nextLookAroundAt = now + WTO_AI_PERC_LOOK_AROUND_SEC + return now < p.lookAroundUntil [never_inline] def public wto_perceive_update(var world : WtoWorldSnap&; now, dt : float; myPos, hullFwd : float3; var slot : WtoBotSlot&) assume p = slot.perceive let myEye = myPos + float3(0.0, 2.15, 0.0) - var lookDir = wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0)) - if slot.fire.servoInit - let worldYaw = atan2(hullFwd.z, hullFwd.x) - slot.fire.curYawDeg * WTO_DEG_TO_RAD - lookDir = float3(cos(worldYaw), 0.0, sin(worldYaw)) - + let hullDir = wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0)) + var lookDir = hullDir + let lookAround = wto_perc_look(now, hullDir, slot, lookDir) wto_exp_decay_all(world, dt, p) var bestIdx = -1 var visCount = 0 var goodLosSec = 0.0 var aimPt = myPos - wto_scan_visual_exposure(world, now, dt, myEye, lookDir, slot, bestIdx, visCount, goodLosSec, aimPt) + wto_scan_visual_exposure(world, now, dt, myEye, lookDir, hullDir, lookAround, slot, bestIdx, visCount, goodLosSec, aimPt) if bestIdx >= 0 assume tgt = world.units[bestIdx] p.targetEid = tgt.eid diff --git a/game-ai/ground/wto_ai_runtime.das b/game-ai/ground/wto_ai_runtime.das index 8916db4..10ac9f8 100644 --- a/game-ai/ground/wto_ai_runtime.das +++ b/game-ai/ground/wto_ai_runtime.das @@ -40,6 +40,8 @@ require %appGame.wtoai.wto_ai_drive_common require %appGame.wtoai.wto_ai_fire_common require %appGame.wtoai.wto_ai_diag_common require %appGame.wtoai.wto_ai_stats_common +require %appGame.wtoai.wto_ai_slots_common +require %appGame.wtoai.wto_ai_threat_common var private @safe_when_uninitialized g_world : WtoWorldSnap var private @safe_when_uninitialized g_crowd : WtoCrowdSummary @@ -79,68 +81,7 @@ def private wto_reset_runtime() g_last_zone_ver = -1 g_next_diag_at = 0.0 wto_navmesh_battle_reset(g_navmesh) - for i in range(WTO_MAX_BOTS) - if g_bots[i].drive.routeBOwned - wto_drive_request_control(g_bots[i].eid, 0) - g_bots[i] = WtoBotSlot() - wto_drive_release_all() - -[never_inline] -def private wto_find_slot(eid : EntityId) : int - let cap = min(WTO_MAX_BOTS, WTO_AI_MAX_TRACKED_BOTS) - for i in range(cap) - if g_bots[i].used && g_bots[i].eid == eid - return i - return -1 - -[never_inline] -def private wto_forget_unit(eid : EntityId) - let idx = wto_find_slot(eid) - if idx >= 0 - if g_bots[idx].drive.routeBOwned - wto_drive_request_control(eid, 0) - g_bots[idx] = WtoBotSlot() - g_cmd_dirty = true - for i in range(WTO_MAX_BOTS) - if g_bots[i].used && g_bots[i].tactics.engageTargetEid == eid - g_bots[i].tactics.engageShotsNoEffect = 0 - g_bots[i].tactics.engageNoShotHalts = 0 - g_bots[i].tactics.engageTotalHaltSec = 0.0 - -[never_inline] -def private wto_acquire_slot(eid : EntityId; army : int; now : float) : int - let cap = min(WTO_MAX_BOTS, WTO_AI_MAX_TRACKED_BOTS) - var freeIdx = -1 - for i in range(cap) - if g_bots[i].used && g_bots[i].eid == eid - g_bots[i].army = army - g_bots[i].lastSeenAt = now - return i - if !g_bots[i].used && freeIdx < 0 - freeIdx = i - if freeIdx >= 0 - g_bots[freeIdx] = WtoBotSlot() - g_bots[freeIdx].used = true - g_bots[freeIdx].eid = eid - g_bots[freeIdx].army = army - g_bots[freeIdx].lastSeenAt = now - g_bots[freeIdx].nextTacticsAt = now - 0.01 - g_bots[freeIdx].nextNavAt = now - 0.01 - g_bots[freeIdx].route.nextReplanAt = now - 0.01 - g_cmd_dirty = true - return freeIdx - -[never_inline] -def private wto_phys_slot_available() : bool - if WTO_AI_NAV_MAX_PHYS_BOTS <= 0 - return false - var count = 0 - for i in range(WTO_MAX_BOTS) - if g_bots[i].used && g_bots[i].drive.routeBOwned && !g_bots[i].drive.routeAFallback - count++ - if count >= WTO_AI_NAV_MAX_PHYS_BOTS - return false - return true + wto_slots_reset_all(g_bots) [es(tag=server, on_event=(EventMissionUnload, EventEntityManagerBeforeClear, EventEcsMissionLoaded))] def wto_ai_mission_reset_es(evt : Event) @@ -168,11 +109,13 @@ def wto_ai_unit_dead_es(evt : Event; eid : EntityId; unit__ref : UnitRef) let now = float(get_app().usefulTotalTime) wto_world_record_death(g_world, eid, int(u.army), u.pos, now) wto_route_report_wreck(g_navmesh.state, now, u.pos, g_bots) - wto_forget_unit(eid) + if wto_slots_forget(g_bots, eid) + g_cmd_dirty = true [es(tag=server, on_disappear, on_event=EventUnitRespawn)] def wto_ai_unit_cleanup_es(evt : Event; eid : EntityId) - wto_forget_unit(eid) + if wto_slots_forget(g_bots, eid) + g_cmd_dirty = true [es(tag=server)] def wto_ai_unit_damage_es(evt : EventUnitDamage; eid : EntityId; unit__ref : UnitRef) @@ -182,27 +125,8 @@ def wto_ai_unit_damage_es(evt : EventUnitDamage; eid : EntityId; unit__ref : Uni let u = unit__ref.unit if u == null || !offEid || offEid == eid return - let now = float(get_app().usefulTotalTime) - let vicArmy = int(u.army) - // Outgoing effective damage confirmation for our firing bot (resets stalemate counters). - let offBotIdx = wto_find_slot(offEid) - if offBotIdx >= 0 && g_bots[offBotIdx].army != vicArmy && uint(evt.hpFixed) < uint(evt.prevHpFixed) - assume tac = g_bots[offBotIdx].tactics - if tac.engageTargetEid == eid || g_bots[offBotIdx].perceive.targetEid == eid - tac.engageShotsNoEffect = 0 - tac.engageNoShotHalts = 0 - tac.lastEffectAt = now - // Incoming hit direction cue for our damaged bot (never leaks hidden offender coords). - let idx = wto_find_slot(eid) - if idx < 0 - return - let offUnitIdx = wto_world_find_unit(g_world, offEid) - if offUnitIdx >= 0 && g_world.units[offUnitIdx].army == g_bots[idx].army - return - let imp = evt.pos - u.pos - g_bots[idx].perceive.lastHitYawRad = (imp.x * imp.x + imp.z * imp.z) > 0.04 ? atan2(imp.z, imp.x) : atan2(u.unitTm[0].z, u.unitTm[0].x) - g_bots[idx].perceive.lastDamagedAt = now - g_bots[idx].perceive.lastOffenderEid = offEid + let hpDropped = uint(evt.hpFixed) < uint(evt.prevHpFixed) + wto_slots_on_damage(g_world, g_bots, eid, offEid, u, evt.pos, hpDropped, float(get_app().usefulTotalTime)) [es(tag=server, before=wto_ai_pipeline_es)] def wto_ai_world_tick_es(act : UpdateStageInfoAct) @@ -215,9 +139,7 @@ def wto_ai_world_tick_es(act : UpdateStageInfoAct) let now = float(get_app().usefulTotalTime) if g_world.valid && now < g_world.time - 1.0 wto_reset_runtime() - for i in range(WTO_MAX_BOTS) - if g_bots[i].used && (now - g_bots[i].lastSeenAt) > 3.5 - g_bots[i] = WtoBotSlot() + wto_slots_drop_stale(g_bots, now) if !g_world.valid wto_drive_announce_script_ready() print("WTO_AI|RUNTIME_READY\n") @@ -259,7 +181,9 @@ def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : if (army != 1 && army != 2) || gm == null || gm.moveSys == null || as_hv(unit) == null return let now = float(get_app().usefulTotalTime) - let idx = wto_acquire_slot(eid, army, now) + var created = false + let idx = wto_slots_acquire(g_bots, eid, army, now, created) + g_cmd_dirty = g_cmd_dirty || created if idx < 0 return assume slot = g_bots[idx] @@ -270,6 +194,7 @@ def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : slot.nextTacticsAt = now + WTO_AI_TACTICS_TICK_SEC if WTO_AI_LAYER_TACTICS || WTO_AI_LAYER_FIRE_CONTROL wto_perceive_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], slot) + wto_threat_update(g_world, now, unit.pos, slot) wto_tactics_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], unit.isBurn, repair_system_remaining_repair_time, slot, g_crowd) wto_fire_update(g_world, unit, unit__className, now, act.dt, slot, g_fire_budget) // A failed pack with navEngine.allowFallback off leaves every bot standing for the battle. @@ -286,10 +211,10 @@ def wto_ai_phys_tick_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref var unit = unit__ref.unit if unit == null || !unit.isAlive || unit.isDelayed || unit.isHumanPlayer || vehicle_net_phys.physEdit == null return - let idx = wto_find_slot(eid) + let idx = wto_slots_find(g_bots, eid) if idx < 0 return - if !g_bots[idx].drive.routeBOwned && !wto_phys_slot_available() + if !g_bots[idx].drive.routeBOwned && !wto_slots_phys_available(g_bots) return let now = float(get_app().usefulTotalTime) wto_drive_step_phys(unit, unit__missionName, as_gm(unit), vehicle_net_phys, act.dt, now, g_bots[idx]) diff --git a/game-ai/ground/wto_ai_slots_common.das b/game-ai/ground/wto_ai_slots_common.das new file mode 100644 index 0000000..fd19219 --- /dev/null +++ b/game-ai/ground/wto_ai_slots_common.das @@ -0,0 +1,113 @@ +// Bot slots of the ground AI runtime: finding, acquiring and freeing a bot's slot, the cap on +// bots driven through vehicle physics, and the per-hit bookkeeping of EventUnitDamage. +options indenting = 2 +options no_global_heap = true +module wto_ai_slots_common shared + +require ecs +require math +require Unit +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_world_common +require %appGame.wtoai.wto_ai_drive_common + +[never_inline] +def public wto_slots_find(bots : WtoBotSlot[64]; eid : EntityId) : int + let cap = min(WTO_MAX_BOTS, WTO_AI_MAX_TRACKED_BOTS) + for i in range(cap) + if bots[i].used && bots[i].eid == eid + return i + return -1 + +// Frees the unit's slot and clears engagement counters aimed at it; true when a slot was freed. +[never_inline] +def public wto_slots_forget(var bots : WtoBotSlot[64]; eid : EntityId) : bool + let idx = wto_slots_find(bots, eid) + if idx >= 0 + if bots[idx].drive.routeBOwned + wto_drive_request_control(eid, 0) + bots[idx] = WtoBotSlot() + for i in range(WTO_MAX_BOTS) + if bots[i].used && bots[i].tactics.engageTargetEid == eid + bots[i].tactics.engageShotsNoEffect = 0 + bots[i].tactics.engageNoShotHalts = 0 + bots[i].tactics.engageTotalHaltSec = 0.0 + return idx >= 0 + +// The unit's slot, taking a free one for a new unit (then `created` is set); -1 when full. +[never_inline] +def public wto_slots_acquire(var bots : WtoBotSlot[64]; eid : EntityId; army : int; now : float; + var created : bool&) : int + let cap = min(WTO_MAX_BOTS, WTO_AI_MAX_TRACKED_BOTS) + var freeIdx = -1 + for i in range(cap) + if bots[i].used && bots[i].eid == eid + bots[i].army = army + bots[i].lastSeenAt = now + return i + if !bots[i].used && freeIdx < 0 + freeIdx = i + if freeIdx >= 0 + bots[freeIdx] = WtoBotSlot() + bots[freeIdx].used = true + bots[freeIdx].eid = eid + bots[freeIdx].army = army + bots[freeIdx].lastSeenAt = now + bots[freeIdx].nextTacticsAt = now - 0.01 + bots[freeIdx].nextNavAt = now - 0.01 + bots[freeIdx].route.nextReplanAt = now - 0.01 + created = true + return freeIdx + +// Releases vehicle control of every bot and clears all slots. +[never_inline] +def public wto_slots_reset_all(var bots : WtoBotSlot[64]) + for i in range(WTO_MAX_BOTS) + if bots[i].drive.routeBOwned + wto_drive_request_control(bots[i].eid, 0) + bots[i] = WtoBotSlot() + wto_drive_release_all() + +// Slots not refreshed by the pipeline for a while belong to units that are gone. +[never_inline] +def public wto_slots_drop_stale(var bots : WtoBotSlot[64]; now : float) + for i in range(WTO_MAX_BOTS) + if bots[i].used && (now - bots[i].lastSeenAt) > 3.5 + bots[i] = WtoBotSlot() + +[never_inline] +def public wto_slots_phys_available(bots : WtoBotSlot[64]) : bool + if WTO_AI_NAV_MAX_PHYS_BOTS <= 0 + return false + var count = 0 + for i in range(WTO_MAX_BOTS) + if bots[i].used && bots[i].drive.routeBOwned && !bots[i].drive.routeAFallback + count++ + if count >= WTO_AI_NAV_MAX_PHYS_BOTS + return false + return true + +// A hit on `eid` by `offEid`: confirms an effective shot of our firing bot (resetting its stalemate +// counters) and gives our damaged bot the direction it was hit from (never the offender's position). +[never_inline] +def public wto_slots_on_damage(world : WtoWorldSnap const&; var bots : WtoBotSlot[64]; eid, offEid : EntityId; + u : Unit const?; hitPos : float3; hpDropped : bool; now : float) + let offBotIdx = wto_slots_find(bots, offEid) + if offBotIdx >= 0 && bots[offBotIdx].army != int(u.army) && hpDropped + assume tac = bots[offBotIdx].tactics + if tac.engageTargetEid == eid || bots[offBotIdx].perceive.targetEid == eid + tac.engageShotsNoEffect = 0 + tac.engageNoShotHalts = 0 + tac.lastEffectAt = now + let idx = wto_slots_find(bots, eid) + if idx < 0 + return + let offUnitIdx = wto_world_find_unit(world, offEid) + if offUnitIdx >= 0 && world.units[offUnitIdx].army == bots[idx].army + return + let imp = hitPos - u.pos + bots[idx].perceive.lastHitYawRad = (imp.x * imp.x + imp.z * imp.z) > 0.04 ? atan2(imp.z, imp.x) : atan2(u.unitTm[0].z, u.unitTm[0].x) + bots[idx].perceive.lastDamagedAt = now + bots[idx].perceive.lastOffenderEid = offEid diff --git a/game-ai/ground/wto_ai_stats_common.das b/game-ai/ground/wto_ai_stats_common.das index 1004683..83fce0c 100644 --- a/game-ai/ground/wto_ai_stats_common.das +++ b/game-ai/ground/wto_ai_stats_common.das @@ -3,7 +3,7 @@ // ends: time from acquiring a target to the first shot at it, time with a target in sight and the // gun ready split by the last reason a shot was refused, shots by distance band and motion, and a // sample every statsSampleSec of the nearest enemy in line of sight (known or not, turret error, -// rear facing it). +// rear facing it). "Known" means discovered: in the bot's threat table. options indenting = 2 options no_global_heap = true module wto_ai_stats_common shared @@ -139,8 +139,8 @@ def private wto_stats_nearest_seen(world : WtoWorldSnap const&; myPos : float3; def private wto_stats_knows(slot : WtoBotSlot const&; eid : EntityId) : bool if slot.perceive.targetEid == eid return true - for k in range(WTO_MAX_EXPOSURE_TRACKS) - if slot.perceive.expEids[k] == eid && slot.perceive.expScore[k] >= 0.5 + for i in range(slot.threat.count) + if slot.threat.entries[i].eid == eid return true return false diff --git a/game-ai/ground/wto_ai_threat_common.das b/game-ai/ground/wto_ai_threat_common.das new file mode 100644 index 0000000..41ffeee --- /dev/null +++ b/game-ai/ground/wto_ai_threat_common.das @@ -0,0 +1,76 @@ +// Threat table (decision layer design, section 4): every enemy the bot has discovered (exposure at +// least perception.discoverScore), with how dangerous it is to the bot. Rebuilt every perception +// tick from the bot's own exposure tracks, so it never knows more than the bot perceived. +// Penetration is not counted yet (see docs/AI-imporve/armor-probe). +options indenting = 2 +options no_global_heap = true +module wto_ai_threat_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_world_common + +// Seen this tick: the perception tick writes expSeenAt for every enemy in line of sight. +def private wto_threat_in_sight(now, seenAt : float) : bool + return now - seenAt <= WTO_AI_TACTICS_TICK_SEC * 1.5 + +// The enemy's hull points within aimConeDeg of the bot, or it hit the bot within hitMemorySec. +def private wto_threat_aiming(now : float; myPos : float3; u : WtoUnitSnap const&; p : WtoPerceiveState const&) : bool + if p.lastOffenderEid == u.eid && now - p.lastDamagedAt <= WTO_AI_THREAT_HIT_MEMORY_SEC + return true + let toMe = wto_xz_normalize(myPos - u.pos, u.hullFwd) + return dot(u.hullFwd, toMe) >= cos(WTO_AI_THREAT_AIM_CONE_DEG * WTO_DEG_TO_RAD) + +[never_inline] +def private wto_threat_danger(now : float; e : WtoThreatEntry const&; eid : EntityId; p : WtoPerceiveState const&) : float + var danger = 1.0 / (1.0 + e.dist / WTO_AI_THREAT_RANGE_SCALE_M) + if !e.seen + danger *= WTO_AI_THREAT_DISCOVERED_MUL + if !e.aiming + danger *= WTO_AI_THREAT_NOT_AIMING_MUL + if !e.seesMe + danger *= WTO_AI_THREAT_UNSEEN_MUL + if p.lastOffenderEid == eid && now - p.lastDamagedAt <= WTO_AI_THREAT_HIT_MEMORY_SEC + danger *= WTO_AI_THREAT_HIT_MUL + return danger + +[never_inline] +def private wto_threat_add(now : float; myPos : float3; u : WtoUnitSnap const&; track : int; var slot : WtoBotSlot&) + assume tt = slot.threat + assume p = slot.perceive + assume e = tt.entries[tt.count] + e.eid = u.eid + e.seesMe = wto_threat_in_sight(now, p.expSeenAt[track]) + e.seen = e.seesMe && p.expScore[track] >= 0.999 + e.pos = p.expPos[track] + e.dist = sqrt(wto_xz_dist_sq(myPos, e.pos)) + e.aiming = wto_threat_aiming(now, myPos, u, p) + e.danger = wto_threat_danger(now, e, u.eid, p) + if tt.topIdx < 0 || e.danger > tt.entries[tt.topIdx].danger + tt.topIdx = tt.count + if !e.seen && (tt.topUnseenIdx < 0 || e.danger > tt.entries[tt.topUnseenIdx].danger) + tt.topUnseenIdx = tt.count + tt.count++ + +// Per perception tick, right after wto_perceive_update. +[never_inline] +def public wto_threat_update(world : WtoWorldSnap const&; now : float; myPos : float3; var slot : WtoBotSlot&) + slot.threat = WtoThreatTable() + assume p = slot.perceive + for k in range(WTO_MAX_EXPOSURE_TRACKS) + if !p.expEids[k] || p.expScore[k] < WTO_AI_PERC_DISCOVER_SCORE + continue + let uIdx = wto_world_find_unit(world, p.expEids[k]) + if uIdx >= 0 && world.units[uIdx].isAlive && !world.units[uIdx].isAir + wto_threat_add(now, myPos, world.units[uIdx], k, slot) + +// Danger of `eid` in the bot's table; 0 when it is not there. +def public wto_threat_danger_of(slot : WtoBotSlot const&; eid : EntityId) : float + for i in range(slot.threat.count) + if slot.threat.entries[i].eid == eid + return slot.threat.entries[i].danger + return 0.0 diff --git a/game-ai/ground/wto_ai_turret_common.das b/game-ai/ground/wto_ai_turret_common.das new file mode 100644 index 0000000..28f71db --- /dev/null +++ b/game-ai/ground/wto_ai_turret_common.das @@ -0,0 +1,70 @@ +// Turret channel (decision layer design, section 5): where the turret looks when it is not aiming +// at an engaged target. Never the hull's front by default: the most dangerous discovered threat +// not seen clearly yet, then the last exit of a lost target, the remembered target, a cue (hit, +// sound, radio), and otherwise a sweep across the route ahead. A chosen threat is kept for at +// least turret.minDwellSec so the turret does not swing between two of them. +options indenting = 2 +options no_global_heap = true +module wto_ai_turret_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_nav_types_common +require %appGame.wtoai.wto_ai_threat_common + +// Whether a threat not seen clearly yet is enough more dangerous than the engaged target that +// the turret should turn to it instead of aiming (turret.switchMargin). +def public wto_turret_prefers_threat(slot : WtoBotSlot const&) : bool + let top = slot.threat.topUnseenIdx + if top < 0 + return false + let engaged = wto_threat_danger_of(slot, slot.perceive.targetEid) + return slot.threat.entries[top].danger > engaged * (1.0 + WTO_AI_TURRET_SWITCH_MARGIN) + +// The threat to look at: the most dangerous one not seen clearly, or the one already looked at +// while its minimum dwell lasts and it is still in the table; -1 for none. +[never_inline] +def private wto_turret_pick_threat(now : float; var slot : WtoBotSlot&) : int + assume tr = slot.turret + assume tt = slot.threat + if now < tr.holdUntil + for i in range(tt.count) + if tt.entries[i].eid == tr.lookEid && !tt.entries[i].seen + return i + let top = tt.topUnseenIdx + if top >= 0 && tt.entries[top].eid != tr.lookEid + tr.lookEid = tt.entries[top].eid + tr.holdUntil = now + WTO_AI_TURRET_MIN_DWELL_SEC + return top + +// Sweep across the route: scanArcDeg either side of where the bot drives (or of its order goal +// when it stands), one sweep every scanPeriodSec, phase spread by entity id. +[never_inline] +def private wto_turret_scan_dir(now : float; myPos, hullFwd : float3; slot : WtoBotSlot const&) : float3 + var base = wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0)) + if slot.tactics.desiredSpeedMps > 0.5 + base = wto_xz_normalize(slot.nav.steerDir, base) + elif slot.order.valid + base = wto_xz_normalize(slot.order.goalPos - myPos, base) + let phase = now * 6.2831853 / WTO_AI_TURRET_SCAN_PERIOD_SEC + float(int(uint(slot.eid) % 16u)) * 0.4 + let yaw = atan2(base.z, base.x) + WTO_AI_TURRET_SCAN_ARC_DEG * WTO_DEG_TO_RAD * sin(phase) + return float3(cos(yaw), 0.0, sin(yaw)) + +// World direction from the muzzle for the turret when it is not aiming at an engaged target. +[never_inline] +def public wto_turret_look_dir(now : float; muzzlePos, myPos, hullFwd : float3; var slot : WtoBotSlot&) : float3 + assume p = slot.perceive + let threat = wto_turret_pick_threat(now, slot) + if threat >= 0 + return normalize((slot.threat.entries[threat].pos + float3(0.0, 1.4, 0.0)) - muzzlePos) + if now < p.watchUntil + return normalize(p.watchPos - muzzlePos) + if !!p.targetEid && (now - p.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC + return normalize((p.knownPos + float3(0.0, 1.4, 0.0)) - muzzlePos) + if now < p.alertUntil + return float3(cos(p.alertYawRad), 0.0, sin(p.alertYawRad)) + return wto_turret_scan_dir(now, myPos, hullFwd, slot) diff --git a/game-ai/ground/wto_ai_types_common.das b/game-ai/ground/wto_ai_types_common.das index a1e8964..ae643b9 100644 --- a/game-ai/ground/wto_ai_types_common.das +++ b/game-ai/ground/wto_ai_types_common.das @@ -251,3 +251,5 @@ struct public WtoBotSlot drive : WtoDriveState = WtoDriveState() fire : WtoFireState = WtoFireState() stats : WtoBotStats = WtoBotStats() + threat : WtoThreatTable = WtoThreatTable() + turret : WtoTurretState = WtoTurretState() diff --git a/packages/patcher/src/ground-ai/ground-ai-config.ts b/packages/patcher/src/ground-ai/ground-ai-config.ts index 54b66ce..e06c03f 100644 --- a/packages/patcher/src/ground-ai/ground-ai-config.ts +++ b/packages/patcher/src/ground-ai/ground-ai-config.ts @@ -194,8 +194,15 @@ export interface GroundAiConfig { readonly normalSpotSec: number; readonly farSpotSec: number; readonly decayPerSec: number; - readonly frontConeHalfDeg: number; - readonly peripheralCloseM: number; + readonly gunFovHalfDeg: number; + readonly nearAwareM: number; + readonly nearArcDeg: number; + readonly midAwareM: number; + readonly nearSpotMul: number; + readonly midSpotMul: number; + readonly lookAroundSec: number; + readonly lookAroundHoldSec: number; + readonly discoverScore: number; }; readonly stateMachine: { readonly preaimAngleDeg: number; @@ -218,8 +225,6 @@ export interface GroundAiConfig { }; readonly tactics: { readonly visionRangeM: number; - readonly visionFovDeg: number; - readonly peripheralRangeM: number; readonly engineAudioRangeM: number; readonly shotAudioRangeM: number; readonly radioShareRangeM: number; @@ -237,6 +242,21 @@ export interface GroundAiConfig { readonly leadErrorFrac: number; readonly maxBiasM: number; }; + readonly threat: { + readonly rangeScaleM: number; + readonly discoveredMul: number; + readonly aimConeDeg: number; + readonly notAimingMul: number; + readonly unseenMul: number; + readonly hitMemorySec: number; + readonly hitMul: number; + }; + readonly turret: { + readonly minDwellSec: number; + readonly switchMargin: number; + readonly scanArcDeg: number; + readonly scanPeriodSec: number; + }; readonly fireControl: { readonly maxEngageRangeM: number; readonly closeRangeM: number; @@ -390,8 +410,15 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['WTO_AI_PERC_NORMAL_SPOT_SEC', 'float', c.perception.normalSpotSec], ['WTO_AI_PERC_FAR_SPOT_SEC', 'float', c.perception.farSpotSec], ['WTO_AI_PERC_DECAY_PER_SEC', 'float', c.perception.decayPerSec], - ['WTO_AI_PERC_FRONT_CONE_DEG', 'float', c.perception.frontConeHalfDeg], - ['WTO_AI_PERC_PERIPH_CLOSE_M', 'float', c.perception.peripheralCloseM], + ['WTO_AI_PERC_GUN_FOV_HALF_DEG', 'float', c.perception.gunFovHalfDeg], + ['WTO_AI_PERC_NEAR_AWARE_M', 'float', c.perception.nearAwareM], + ['WTO_AI_PERC_NEAR_ARC_DEG', 'float', c.perception.nearArcDeg], + ['WTO_AI_PERC_MID_AWARE_M', 'float', c.perception.midAwareM], + ['WTO_AI_PERC_NEAR_SPOT_MUL', 'float', c.perception.nearSpotMul], + ['WTO_AI_PERC_MID_SPOT_MUL', 'float', c.perception.midSpotMul], + ['WTO_AI_PERC_LOOK_AROUND_SEC', 'float', c.perception.lookAroundSec], + ['WTO_AI_PERC_LOOK_AROUND_HOLD_SEC', 'float', c.perception.lookAroundHoldSec], + ['WTO_AI_PERC_DISCOVER_SCORE', 'float', c.perception.discoverScore], ['WTO_AI_SM_PREAIM_DEG', 'float', c.stateMachine.preaimAngleDeg], ['WTO_AI_SM_MOVING_SHOT_WAIT_SEC', 'float', c.stateMachine.movingShotWaitSec], ['WTO_AI_SM_SHORT_HALT_MAX_SEC', 'float', c.stateMachine.shortHaltMaxSec], @@ -410,8 +437,6 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['WTO_AI_SM_REPOS_STEP_M', 'float', c.stateMachine.repositionStepM], ['WTO_AI_SM_REPAIR_SAFE_DIST_M', 'float', c.stateMachine.repairSafeEnemyDistM], ['WTO_AI_TACTICS_VISION_RANGE_M', 'float', c.tactics.visionRangeM], - ['WTO_AI_TACTICS_VISION_FOV_DEG', 'float', c.tactics.visionFovDeg], - ['WTO_AI_TACTICS_PERIPHERAL_RANGE_M', 'float', c.tactics.peripheralRangeM], ['WTO_AI_TACTICS_ENGINE_AUDIO_M', 'float', c.tactics.engineAudioRangeM], ['WTO_AI_TACTICS_SHOT_AUDIO_M', 'float', c.tactics.shotAudioRangeM], ['WTO_AI_TACTICS_RADIO_SHARE_M', 'float', c.tactics.radioShareRangeM], @@ -426,6 +451,17 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['WTO_AI_EST_BASE_SIGMA_M', 'float', c.estimation.baseAimSigmaM], ['WTO_AI_EST_LEAD_ERR_FRAC', 'float', c.estimation.leadErrorFrac], ['WTO_AI_EST_MAX_BIAS_M', 'float', c.estimation.maxBiasM], + ['WTO_AI_THREAT_RANGE_SCALE_M', 'float', c.threat.rangeScaleM], + ['WTO_AI_THREAT_DISCOVERED_MUL', 'float', c.threat.discoveredMul], + ['WTO_AI_THREAT_AIM_CONE_DEG', 'float', c.threat.aimConeDeg], + ['WTO_AI_THREAT_NOT_AIMING_MUL', 'float', c.threat.notAimingMul], + ['WTO_AI_THREAT_UNSEEN_MUL', 'float', c.threat.unseenMul], + ['WTO_AI_THREAT_HIT_MEMORY_SEC', 'float', c.threat.hitMemorySec], + ['WTO_AI_THREAT_HIT_MUL', 'float', c.threat.hitMul], + ['WTO_AI_TURRET_MIN_DWELL_SEC', 'float', c.turret.minDwellSec], + ['WTO_AI_TURRET_SWITCH_MARGIN', 'float', c.turret.switchMargin], + ['WTO_AI_TURRET_SCAN_ARC_DEG', 'float', c.turret.scanArcDeg], + ['WTO_AI_TURRET_SCAN_PERIOD_SEC', 'float', c.turret.scanPeriodSec], ['WTO_AI_FC_MAX_RANGE_M', 'float', c.fireControl.maxEngageRangeM], ['WTO_AI_FC_CLOSE_RANGE_M', 'float', c.fireControl.closeRangeM], ['WTO_AI_FC_MID_RANGE_M', 'float', c.fireControl.midRangeM], From 4e658cae9c4ac80ef118c8d04c4eac573f1c5ca9 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sun, 6 Dec 2026 01:11:55 +0800 Subject: [PATCH 12/19] feat(ground-ai): add the trigger decision channel Estimate hit probability and request movement speed from the weapon solution. Use visible aim samples, stock shell penetration, and separate burst paths. --- .../src/renderer/src/i18n/locales/en.json | 29 +++- .../src/renderer/src/i18n/locales/zh-CN.json | 29 +++- .../src/pages/tuning/BotTuningPanel.tsx | 2 +- .../src/pages/tuning/bot-tuning-fields.ts | 27 ++- apps/launcher/src/shared/schemas/tuning.ts | 27 ++- apps/server/src/tuning/ground-ai-tuning.ts | 32 +++- apps/server/tuning/ground-ai.jsonc | 48 +++++- game-ai/ground/wto_ai_combat_types_common.das | 37 +++- game-ai/ground/wto_ai_estimate_common.das | 2 +- game-ai/ground/wto_ai_fire_aux_common.das | 114 +++++++++++++ game-ai/ground/wto_ai_fire_common.das | 62 +++++-- game-ai/ground/wto_ai_fire_gate_common.das | 158 ++++++++++++------ game-ai/ground/wto_ai_perceive_common.das | 2 + game-ai/ground/wto_ai_sight_common.das | 10 +- game-ai/ground/wto_ai_specs_common.das | 4 +- game-ai/ground/wto_ai_stats_common.das | 13 +- game-ai/ground/wto_ai_tactics_common.das | 2 +- game-ai/ground/wto_ai_trigger_common.das | 151 +++++++++++++++++ game-ai/ground/wto_ai_types_common.das | 3 +- .../patcher/src/ground-ai/ground-ai-config.ts | 54 +++++- 20 files changed, 693 insertions(+), 113 deletions(-) create mode 100644 game-ai/ground/wto_ai_fire_aux_common.das create mode 100644 game-ai/ground/wto_ai_trigger_common.das diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index da1d14a..c86cb1a 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -555,7 +555,7 @@ "estimation": "Sample-based velocity lead, exit watch and natural shot spread", "threat": "How dangerous each discovered enemy is: distance, aim, line of sight and recent hits", "turret": "Where the turret looks without a target: threats, cues and scanning along the route", - "fireControl": "Range bands, speed gates, barrel settle and ballistic safety", + "fireControl": "Hit probability and fire threshold, autocannon bursts, secondary weapons, barrel settle and ballistic safety", "navigation": "Drive backend, pivot turns and tactical reverse", "navEngine": "Baked map navigation packs, their fallback, and path costs per surface for tracked and wheeled vehicles", "pathFollow": "Replanning, lookahead steering, corner and arrival braking, narrow passages, bumper rays, passing stopped vehicles and wrecks, giving way, three-level unstick and temporary path costs", @@ -699,12 +699,33 @@ "stopSpeedMaxMps": "Stopped speed threshold", "longRangeWindowSec": "Long-range clear LOS window", "baseAlignDeg": "Base gun alignment tolerance", - "closeHitRadiusM": "Close-range hit acceptance radius", "barrelSettleDegSec": "Max aim error drift outside close range", "closeSettleHoldSec": "Close-range settle hold time", "settleHoldSec": "Standard settle hold time", - "unstabilizedStopSpeedMps": "Unstabilized stop speed cap", - "stabilizedCreepSpeedMps": "Stabilized creep fire speed cap", + "aimErrorDeg": "Crew aim error (spread)", + "moveErrDegPerMps": "Aim error per m/s of own speed", + "turnErrDegPerDegSec": "Aim error per deg/s of hull turn", + "stabErrFactor": "Motion error factor with a stabilizer", + "targetHalfHeightM": "Half height of a fully visible target", + "fireThreshold": "Base hit probability needed to fire", + "minFireThreshold": "Lowest fire threshold", + "aimingThresholdBonus": "Threshold drop when the target aims at the bot", + "closeThresholdBonus": "Threshold drop at point blank", + "enemyReloadThresholdBonus": "Threshold drop after the target fired", + "enemyReloadSec": "How long a target counts as reloading after it fired", + "fleetingThresholdBonus": "Threshold drop for a target about to slip away", + "fleetingLateralMps": "Crossing speed of a slipping-away target", + "bigGunThresholdPenalty": "Threshold rise for big slow-loading guns", + "retreatThresholdPenalty": "Threshold rise while pulling back to cover", + "minShotIntervalSec": "Minimum main-gun shot interval", + "autocannonAimSlack": "Autocannon aim slack (times target size)", + "burstSec": "Burst length", + "burstPauseSec": "Pause between bursts", + "burstRecheckSec": "Safety re-check interval within a burst", + "autocannonReloadDetectSec": "Autocannon not-ready time that counts as a reload", + "auxWeapons": "Fire secondary and coaxial weapons", + "auxMaxRangeM": "Secondary and coaxial weapon range", + "auxFireAtArmor": "Secondary and coaxial weapons also fire at armored targets", "friendlyCorridorM": "Friendly fire corridor width", "ballisticStepMaxM": "Ballistic occlusion step length", "ballisticSweepRadiusM": "Ballistic sphere sweep radius", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index 2be4ada..223fc0f 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -555,7 +555,7 @@ "estimation": "本车目击测速、守出口时长与自然散布", "threat": "每个已发现敌人的危险程度:距离、是否瞄着本车、视线与最近是否命中本车", "turret": "没有目标时炮塔看哪里:威胁、线索与沿路线扫视", - "fireControl": "距离分档、车速门槛、稳定等待与弹道防误伤", + "fireControl": "命中概率与开火门槛、机炮点射、副武器、炮管稳定和弹道安全", "navigation": "驱动方式、原地转向与战术倒车", "navEngine": "离线地图导航包的启用与降级,以及履带 / 轮式车在各类地表上的寻路代价", "pathFollow": "重新寻路、前瞻跟路、弯道与到达前减速、窄路限速、车头射线、绕过停车和残骸、会车让路、三级脱困与临时寻路代价", @@ -699,12 +699,33 @@ "stopSpeedMaxMps": "停稳判定最高车速", "longRangeWindowSec": "远距连续射界观察窗", "baseAlignDeg": "主炮对准允许角误差", - "closeHitRadiusM": "近距命中判定半径", "barrelSettleDegSec": "近距以外瞄准误差最大变化速度", "closeSettleHoldSec": "近距稳定保持时间", "settleHoldSec": "常规稳定保持时间", - "unstabilizedStopSpeedMps": "无稳定器停稳车速上限", - "stabilizedCreepSpeedMps": "带稳定器慢速射击上限", + "aimErrorDeg": "炮手瞄准误差(散布)", + "moveErrDegPerMps": "本车每 m/s 车速增加的瞄准误差", + "turnErrDegPerDegSec": "车体每 °/s 转向增加的瞄准误差", + "stabErrFactor": "有稳定器时行进误差的倍数", + "targetHalfHeightM": "完全露出的目标半高", + "fireThreshold": "开火所需的基础命中概率", + "minFireThreshold": "开火门槛下限", + "aimingThresholdBonus": "目标瞄着本车时门槛降低", + "closeThresholdBonus": "贴脸时门槛降低(近距内按距离过渡)", + "enemyReloadThresholdBonus": "目标刚开过火时门槛降低", + "enemyReloadSec": "目标开火后视为装填中的时长", + "fleetingThresholdBonus": "目标即将离开视线时门槛降低", + "fleetingLateralMps": "视为即将离开视线的横穿速度", + "bigGunThresholdPenalty": "大口径慢装填火炮的门槛升高", + "retreatThresholdPenalty": "退入掩体途中的门槛升高", + "minShotIntervalSec": "主炮最短开火间隔", + "autocannonAimSlack": "机炮放宽倍数(目标尺寸的倍数)", + "burstSec": "点射时长", + "burstPauseSec": "点射间隔", + "burstRecheckSec": "点射中复查弹道和友军的间隔", + "autocannonReloadDetectSec": "机炮持续未就绪多久算换弹", + "auxWeapons": "使用副炮和并列武器", + "auxMaxRangeM": "副炮和并列武器的射击距离", + "auxFireAtArmor": "副炮和并列武器也打装甲目标", "friendlyCorridorM": "友军弹道禁射走廊宽度", "ballisticStepMaxM": "弹道硬遮挡检测步长", "ballisticSweepRadiusM": "弹道扫掠半径", diff --git a/apps/launcher/src/renderer/src/pages/tuning/BotTuningPanel.tsx b/apps/launcher/src/renderer/src/pages/tuning/BotTuningPanel.tsx index f6c7653..07e8ebb 100644 --- a/apps/launcher/src/renderer/src/pages/tuning/BotTuningPanel.tsx +++ b/apps/launcher/src/renderer/src/pages/tuning/BotTuningPanel.tsx @@ -54,7 +54,7 @@ function hasValidCrossFieldRules(effective: GroundAiTuningValues, patch: TuningP if (est.watchMaxSec < est.watchMinSec || est.velStableSpanSec <= est.velSampleMinSpanSec) return false; const fc = mergeSection(effective.fireControl, patch.fireControl); if (fc.midRangeM <= fc.closeRangeM || fc.longRangeM <= fc.midRangeM) return false; - return fc.pointBlankMaxSpeedKmh >= fc.closeRangeMaxSpeedKmh; + return fc.minFireThreshold <= fc.fireThreshold && fc.pointBlankMaxSpeedKmh >= fc.closeRangeMaxSpeedKmh; } export function BotTuningPanel({ data, saving, onSave }: Props) { diff --git a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts index 5fb1f94..b9972a9 100644 --- a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts +++ b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts @@ -270,12 +270,33 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ num('fireControl', 'stopSpeedMaxMps', 0.1, 2, 'm/s'), num('fireControl', 'longRangeWindowSec', 1, 15, 's'), num('fireControl', 'baseAlignDeg', 0.1, 3, '°'), - num('fireControl', 'closeHitRadiusM', 0.25, 2.2, 'm'), num('fireControl', 'barrelSettleDegSec', 0.2, 12, '°/s'), num('fireControl', 'closeSettleHoldSec', 0.02, 0.5, 's'), num('fireControl', 'settleHoldSec', 0.05, 1.5, 's'), - num('fireControl', 'unstabilizedStopSpeedMps', 0.1, 3, 'm/s'), - num('fireControl', 'stabilizedCreepSpeedMps', 1.5, 15, 'm/s'), + num('fireControl', 'aimErrorDeg', 0.01, 2, '°'), + num('fireControl', 'moveErrDegPerMps', 0, 3, '°'), + num('fireControl', 'turnErrDegPerDegSec', 0, 0.5), + num('fireControl', 'stabErrFactor', 0.02, 1), + num('fireControl', 'targetHalfHeightM', 0.3, 2, 'm'), + num('fireControl', 'fireThreshold', 0.05, 0.95), + num('fireControl', 'minFireThreshold', 0.01, 0.9), + num('fireControl', 'aimingThresholdBonus', 0, 0.5), + num('fireControl', 'closeThresholdBonus', 0, 0.5), + num('fireControl', 'enemyReloadThresholdBonus', 0, 0.5), + num('fireControl', 'enemyReloadSec', 0, 15, 's'), + num('fireControl', 'fleetingThresholdBonus', 0, 0.5), + num('fireControl', 'fleetingLateralMps', 0.5, 15, 'm/s'), + num('fireControl', 'bigGunThresholdPenalty', 0, 0.5), + num('fireControl', 'retreatThresholdPenalty', 0, 0.6), + num('fireControl', 'minShotIntervalSec', 0.1, 5, 's'), + num('fireControl', 'autocannonAimSlack', 1, 10), + num('fireControl', 'burstSec', 0.2, 6, 's'), + num('fireControl', 'burstPauseSec', 0, 5, 's'), + num('fireControl', 'burstRecheckSec', 0.05, 2, 's'), + num('fireControl', 'autocannonReloadDetectSec', 0.1, 3, 's'), + { id: 'groundAi.fireControl.auxWeapons', section: 'fireControl', field: 'auxWeapons', kind: 'bool' }, + num('fireControl', 'auxMaxRangeM', 30, 1500, 'm'), + { id: 'groundAi.fireControl.auxFireAtArmor', section: 'fireControl', field: 'auxFireAtArmor', kind: 'bool' }, num('fireControl', 'friendlyCorridorM', 1, 10, 'm'), num('fireControl', 'ballisticStepMaxM', 5, 80, 'm'), num('fireControl', 'ballisticSweepRadiusM', 0.02, 0.5, 'm'), diff --git a/apps/launcher/src/shared/schemas/tuning.ts b/apps/launcher/src/shared/schemas/tuning.ts index c900114..840ac19 100644 --- a/apps/launcher/src/shared/schemas/tuning.ts +++ b/apps/launcher/src/shared/schemas/tuning.ts @@ -257,12 +257,33 @@ const GroundAiFireControlSchema = z.object({ stopSpeedMaxMps: z.number().min(0.1).max(2), longRangeWindowSec: z.number().min(1).max(15), baseAlignDeg: z.number().min(0.1).max(3), - closeHitRadiusM: z.number().min(0.25).max(2.2), barrelSettleDegSec: z.number().min(0.2).max(12), closeSettleHoldSec: z.number().min(0.02).max(0.5), settleHoldSec: z.number().min(0.05).max(1.5), - unstabilizedStopSpeedMps: z.number().min(0.1).max(3), - stabilizedCreepSpeedMps: z.number().min(1.5).max(15), + aimErrorDeg: z.number().min(0.01).max(2), + moveErrDegPerMps: z.number().min(0).max(3), + turnErrDegPerDegSec: z.number().min(0).max(0.5), + stabErrFactor: z.number().min(0.02).max(1), + targetHalfHeightM: z.number().min(0.3).max(2), + fireThreshold: z.number().min(0.05).max(0.95), + minFireThreshold: z.number().min(0.01).max(0.9), + aimingThresholdBonus: z.number().min(0).max(0.5), + closeThresholdBonus: z.number().min(0).max(0.5), + enemyReloadThresholdBonus: z.number().min(0).max(0.5), + enemyReloadSec: z.number().min(0).max(15), + fleetingThresholdBonus: z.number().min(0).max(0.5), + fleetingLateralMps: z.number().min(0.5).max(15), + bigGunThresholdPenalty: z.number().min(0).max(0.5), + retreatThresholdPenalty: z.number().min(0).max(0.6), + minShotIntervalSec: z.number().min(0.1).max(5), + autocannonAimSlack: z.number().min(1).max(10), + burstSec: z.number().min(0.2).max(6), + burstPauseSec: z.number().min(0).max(5), + burstRecheckSec: z.number().min(0.05).max(2), + autocannonReloadDetectSec: z.number().min(0.1).max(3), + auxWeapons: z.boolean(), + auxMaxRangeM: z.number().min(30).max(1500), + auxFireAtArmor: z.boolean(), friendlyCorridorM: z.number().min(1).max(10), ballisticStepMaxM: z.number().min(5).max(80), ballisticSweepRadiusM: z.number().min(0.02).max(0.5), diff --git a/apps/server/src/tuning/ground-ai-tuning.ts b/apps/server/src/tuning/ground-ai-tuning.ts index 2865a5c..bec0b8b 100644 --- a/apps/server/src/tuning/ground-ai-tuning.ts +++ b/apps/server/src/tuning/ground-ai-tuning.ts @@ -413,6 +413,11 @@ function readFireControlSection(fc: TuningReader): GroundAiTuning['fireControl'] if (pointBlankMaxSpeedKmh < closeRangeMaxSpeedKmh) { throw new TuningError('tuning file ground-ai.jsonc: fireControl.pointBlankMaxSpeedKmh must be >= closeRangeMaxSpeedKmh'); } + const fireThreshold = fc.number('fireThreshold', { min: 0.05, max: 0.95 }); + const minFireThreshold = fc.number('minFireThreshold', { min: 0.01, max: 0.9 }); + if (minFireThreshold > fireThreshold) { + throw new TuningError('tuning file ground-ai.jsonc: fireControl.minFireThreshold must be <= fireThreshold'); + } return { maxEngageRangeM: fc.number('maxEngageRangeM', { min: 150, max: 3000 }), closeRangeM, @@ -425,12 +430,33 @@ function readFireControlSection(fc: TuningReader): GroundAiTuning['fireControl'] stopSpeedMaxMps: fc.number('stopSpeedMaxMps', { min: 0.1, max: 2.0 }), longRangeWindowSec: fc.number('longRangeWindowSec', { min: 1.0, max: 15.0 }), baseAlignDeg: fc.number('baseAlignDeg', { min: 0.1, max: 3.0 }), - closeHitRadiusM: fc.number('closeHitRadiusM', { min: 0.25, max: 2.2 }), barrelSettleDegSec: fc.number('barrelSettleDegSec', { min: 0.2, max: 12.0 }), closeSettleHoldSec: fc.number('closeSettleHoldSec', { min: 0.02, max: 0.5 }), settleHoldSec: fc.number('settleHoldSec', { min: 0.05, max: 1.5 }), - unstabilizedStopSpeedMps: fc.number('unstabilizedStopSpeedMps', { min: 0.1, max: 3.0 }), - stabilizedCreepSpeedMps: fc.number('stabilizedCreepSpeedMps', { min: 1.5, max: 15.0 }), + aimErrorDeg: fc.number('aimErrorDeg', { min: 0.01, max: 2 }), + moveErrDegPerMps: fc.number('moveErrDegPerMps', { min: 0, max: 3 }), + turnErrDegPerDegSec: fc.number('turnErrDegPerDegSec', { min: 0, max: 0.5 }), + stabErrFactor: fc.number('stabErrFactor', { min: 0.02, max: 1 }), + targetHalfHeightM: fc.number('targetHalfHeightM', { min: 0.3, max: 2 }), + fireThreshold, + minFireThreshold, + aimingThresholdBonus: fc.number('aimingThresholdBonus', { min: 0, max: 0.5 }), + closeThresholdBonus: fc.number('closeThresholdBonus', { min: 0, max: 0.5 }), + enemyReloadThresholdBonus: fc.number('enemyReloadThresholdBonus', { min: 0, max: 0.5 }), + enemyReloadSec: fc.number('enemyReloadSec', { min: 0, max: 15 }), + fleetingThresholdBonus: fc.number('fleetingThresholdBonus', { min: 0, max: 0.5 }), + fleetingLateralMps: fc.number('fleetingLateralMps', { min: 0.5, max: 15 }), + bigGunThresholdPenalty: fc.number('bigGunThresholdPenalty', { min: 0, max: 0.5 }), + retreatThresholdPenalty: fc.number('retreatThresholdPenalty', { min: 0, max: 0.6 }), + minShotIntervalSec: fc.number('minShotIntervalSec', { min: 0.1, max: 5 }), + autocannonAimSlack: fc.number('autocannonAimSlack', { min: 1, max: 10 }), + burstSec: fc.number('burstSec', { min: 0.2, max: 6 }), + burstPauseSec: fc.number('burstPauseSec', { min: 0, max: 5 }), + burstRecheckSec: fc.number('burstRecheckSec', { min: 0.05, max: 2 }), + autocannonReloadDetectSec: fc.number('autocannonReloadDetectSec', { min: 0.1, max: 3 }), + auxWeapons: fc.bool('auxWeapons'), + auxMaxRangeM: fc.number('auxMaxRangeM', { min: 30, max: 1500 }), + auxFireAtArmor: fc.bool('auxFireAtArmor'), friendlyCorridorM: fc.number('friendlyCorridorM', { min: 1.0, max: 10.0 }), ballisticStepMaxM: fc.number('ballisticStepMaxM', { min: 5.0, max: 80.0 }), ballisticSweepRadiusM: fc.number('ballisticSweepRadiusM', { min: 0.02, max: 0.5 }), diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index a001f75..55aec83 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -352,6 +352,18 @@ "scanPeriodSec": 6.0 }, + // Fire permission (decision layer design, section 6). A main-gun shot needs its estimated hit + // probability to reach the fire threshold. The hit probability compares the visible part of the + // target (its projected width, targetHalfHeightM high, shrunk when only part of it is visible) + // with the expected angular error: aimErrorDeg, plus moveErrDegPerMps per m/s of own speed and + // turnErrDegPerDegSec per deg/s of hull turn (times stabErrFactor with a stabilizer), plus the + // lead uncertainty on a crossing target, with the barrel's current offset as the mean error. + // The threshold starts at fireThreshold and drops by aimingThresholdBonus when the target aims + // at the bot, by up to closeThresholdBonus inside closeRangeM, by enemyReloadThresholdBonus for + // enemyReloadSec after the target fired, and by fleetingThresholdBonus when it crosses faster + // than fleetingLateralMps partly hidden; it rises by up to bigGunThresholdPenalty for guns above + // 75 mm and by retreatThresholdPenalty while pulling back to cover, and never goes below + // minFireThreshold. Main-gun shots are at least minShotIntervalSec apart. "fireControl": { "maxEngageRangeM": 1250.0, "closeRangeM": 100.0, @@ -359,19 +371,47 @@ "longRangeM": 800.0, "midSlowSpeedRatio": 0.45, "midSlowMaxMps": 5.5, - // Moving-fire speed rises from the mid-range limit through the close-range boundary to point blank. "closeRangeMaxSpeedKmh": 30.0, "pointBlankMaxSpeedKmh": 35.0, + // At or below this speed the bot counts as standing (also the answer "stop" to a speed request). "stopSpeedMaxMps": 0.45, "longRangeWindowSec": 4.0, + // Fixed (casemate) guns: how far off the gun may be before the hull is asked to turn. "baseAlignDeg": 0.42, - "closeHitRadiusM": 0.85, // Outside close range, the rate at which barrel alignment drifts relative to the aim direction. "barrelSettleDegSec": 1.8, "closeSettleHoldSec": 0.08, "settleHoldSec": 0.20, - "unstabilizedStopSpeedMps": 0.45, - "stabilizedCreepSpeedMps": 5.5, + "aimErrorDeg": 0.12, + "moveErrDegPerMps": 0.35, + "turnErrDegPerDegSec": 0.03, + "stabErrFactor": 0.2, + "targetHalfHeightM": 1.0, + "fireThreshold": 0.35, + "minFireThreshold": 0.1, + "aimingThresholdBonus": 0.1, + "closeThresholdBonus": 0.15, + "enemyReloadThresholdBonus": 0.08, + "enemyReloadSec": 3.0, + "fleetingThresholdBonus": 0.1, + "fleetingLateralMps": 3.0, + "bigGunThresholdPenalty": 0.08, + "retreatThresholdPenalty": 0.2, + "minShotIntervalSec": 0.65, + // Belt-fed autocannons (6.3): fire while within autocannonAimSlack times the target's angular + // half size, in bursts of burstSec with burstPauseSec between, checking barrel, trajectory and + // friendlies again every burstRecheckSec. Not ready for longer than autocannonReloadDetectSec + // counts as a reload. + "autocannonAimSlack": 3.0, + "burstSec": 1.2, + "burstPauseSec": 0.6, + "burstRecheckSec": 0.3, + "autocannonReloadDetectSec": 0.6, + // Secondary cannon and coaxial weapons (6.4) fire bursts alongside the main gun at light + // vehicles within auxMaxRangeM (at any vehicle with auxFireAtArmor). + "auxWeapons": true, + "auxMaxRangeM": 300.0, + "auxFireAtArmor": false, "friendlyCorridorM": 3.2, "ballisticStepMaxM": 25.0, "ballisticSweepRadiusM": 0.12, diff --git a/game-ai/ground/wto_ai_combat_types_common.das b/game-ai/ground/wto_ai_combat_types_common.das index a949a3f..89a9ad0 100644 --- a/game-ai/ground/wto_ai_combat_types_common.das +++ b/game-ai/ground/wto_ai_combat_types_common.das @@ -20,7 +20,8 @@ let public WTO_BLOCK_FOLIAGE = 6 let public WTO_DENY_OK = 0 let public WTO_DENY_NO_TARGET = 1 let public WTO_DENY_NOT_READY = 2 -let public WTO_DENY_SPEED = 3 +// The estimated hit probability is below the fire threshold (decision layer design, 6.1). +let public WTO_DENY_HIT_PROB = 3 let public WTO_DENY_LONG_WINDOW = 4 let public WTO_DENY_AIM_ERR = 5 let public WTO_DENY_SETTLE = 6 @@ -30,6 +31,9 @@ let public WTO_DENY_ARC_HARD = 9 let public WTO_DENY_FRIENDLY = 10 let public WTO_DENY_MULTI_GUN = 11 let public WTO_DENY_TRAVERSE = 12 +// An autocannon between two bursts (decision layer design, 6.3). +let public WTO_DENY_BURST_PAUSE = 13 +let public WTO_DENY_COUNT = 14 [safe_when_uninitialized] struct public WtoShellProfile @@ -40,6 +44,8 @@ struct public WtoShellProfile caliberM : float = 0.09 isSoftShell : bool = false isAntiArmor : bool = true + // Stock maximum penetration (calc_max_penetration), mm. + penMm : float = 0.0 [safe_when_uninitialized] struct public WtoPerceiveState @@ -80,6 +86,8 @@ struct public WtoPerceiveState expPos : float3[8] nextLookAroundAt : float = 0.0 lookAroundUntil : float = -100.0 + // When the engaged target was last seen firing (it is likely reloading for a while after). + targetShotAt : float = -100.0 // One discovered enemy in the bot's threat table (decision layer design, section 4). `seen`: seen // clearly (fireable); `seesMe`: in line of sight this tick; `aiming`: its hull points at the bot or @@ -110,6 +118,32 @@ struct public WtoTurretState lookEid : EntityId = INVALID_ENTITY_ID holdUntil : float = -100.0 +// Trigger channel (decision layer design, section 6). hitProb / threshold: the last estimate for +// the main weapon (hitProbAligned: the same with the barrel on target); aimSlackDeg: how far off +// an autocannon may be and still fire; wantSpeedMps: the highest own speed at which the shot +// would reach the threshold (99 = no limit, 0 = only standing), a request the hull channel +// weighs. biasEpoch changes the aiming bias once per shooting opportunity (per shot, or per +// autocannon burst). burst*: the autocannon's current burst and pause; coax*: the same for the +// secondary and coaxial weapons, coaxBlocked a bit per weapon group failing its last check. +[safe_when_uninitialized] +struct public WtoTriggerState + hitProb : float = 0.0 + hitProbAligned : float = 0.0 + threshold : float = 1.0 + aimSlackDeg : float = 1.0 + wantSpeedMps : float = 99.0 + wantSpeedAt : float = -100.0 + biasEpoch : int = 0 + burstUntil : float = -100.0 + burstPauseUntil : float = -100.0 + burstCheckedUntil : float = -100.0 + coaxBurstUntil : float = -100.0 + coaxPauseUntil : float = -100.0 + coaxCheckedUntil : float = -100.0 + coaxBlocked : int = 0 + coaxShots : int = 0 + lastLogAt : float = -100.0 + [safe_when_uninitialized] struct public WtoGunTraverse known : bool = false @@ -128,6 +162,7 @@ struct public WtoFireState gunReady : bool = false reloading : bool = false gunDamaged : bool = false + notReadySince : float = -100.0 loadedBulletIdx : int = -1 activeSpeedMps : float = 880.0 activeDragCx : float = 0.35 diff --git a/game-ai/ground/wto_ai_estimate_common.das b/game-ai/ground/wto_ai_estimate_common.das index 59fdb91..cc94929 100644 --- a/game-ai/ground/wto_ai_estimate_common.das +++ b/game-ai/ground/wto_ai_estimate_common.das @@ -113,7 +113,7 @@ def public wto_est_compute_biased_lead(muzzlePos, myVel, aimBase : float3; // Sample bounded natural bias ONCE per shooting opportunity (target + shot + state + 12m grid). let gx = uint(int(muzzlePos.x / 12.0) + 4096) let gz = uint(int(muzzlePos.z / 12.0) + 4096) - let key = (uint(p.targetEid) ^ (uint(slot.fire.shotCount) * 2654435761u) ^ + let key = (uint(p.targetEid) ^ (uint(slot.trigger.biasEpoch) * 2654435761u) ^ (uint(slot.tactics.state) * 40503u) ^ (gx * 73856093u) ^ (gz * 19349663u)) if !p.oppSeeded || p.oppKey != key p.oppKey = key diff --git a/game-ai/ground/wto_ai_fire_aux_common.das b/game-ai/ground/wto_ai_fire_aux_common.das new file mode 100644 index 0000000..56b48c4 --- /dev/null +++ b/game-ai/ground/wto_ai_fire_aux_common.das @@ -0,0 +1,114 @@ +// Secondary cannon and coaxial weapons (decision layer design, 6.4): each weapon group decides for +// itself, alongside the main gun, so they can fire in the same moment. They fire bursts at the +// engaged target while their own barrel is within the aim slack of it, at light vehicles (any +// vehicle with fireControl.auxFireAtArmor) within fireControl.auxMaxRangeM. Before a burst and +// every burstRecheckSec, each group's straight line from its own muzzle is checked for hard cover +// and friendlies; a group that fails is held until the next check. +options indenting = 2 +options no_global_heap = true +module wto_ai_fire_aux_common shared + +require ecs +require math +require DagorMath +require Mission +require Unit +require Weapon +require %game.utils.utils_common +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_world_common +require %appGame.wtoai.wto_ai_sight_common +require %appGame.wtoai.wto_ai_trigger_common +require %appGame.wtoai.wto_ai_fire_gate_common + +let private AUX_SECONDARY_BIT = 1 +let private AUX_COAXIAL_BIT = 2 + +// The group's first working weapon that is ready to fire: its muzzle and barrel direction. +[never_inline] +def private wto_aux_ready_barrel(unit : Unit const?; group : WeaponTriggerGroups; var outPos, outDir : float3&) : bool + var found = false + get_weapons_by_trigger_group(unit.weap.Weapons, group) <| $(weapons : array const#) + for i in range(length(weapons)) + if found + break + assume weapon = weapons[i] + if weapon == null || weapon.isDummyGun + continue + let gun = as_gun(weapon) + if gun == null || gun.isInoperable || !gun.isReadyToShoot + continue + var tm : float3x4 + weapon_calcShootTm(weapon, unit.unitTm, tm) + if length_sq(tm[0]) > 0.25 + outPos = tm[3] + outDir = normalize(tm[0]) + found = true + return found + +// Hard cover or a friendly on the straight line from the group's muzzle (or no ready weapon). +[never_inline] +def private wto_aux_blocked(world : WtoWorldSnap const&; unit : Unit const?; group : WeaponTriggerGroups; + aimPt : float3; slot : WtoBotSlot const&) : bool + var muzzle = unit.pos + var dir = unit.unitTm[0] + if !wto_aux_ready_barrel(unit, group, muzzle, dir) + return true + if wto_sight_hard_segment_blocked(world, slot.eid, slot.perceive.targetEid, muzzle, aimPt, 0.05, 0.35, 0.65) != WTO_BLOCK_NONE + return true + let flightSec = length(aimPt - muzzle) / 900.0 + return !wto_gate_friendly_segment_clear(world, slot.eid, slot.army, muzzle, aimPt, flightSec * 0.5) + +// Fires the group once when its ready barrel is within the aim slack and it passed the last check. +[never_inline] +def private wto_aux_fire_group(var unit : Unit?; group : WeaponTriggerGroups; bit : int; aimPt : float3; + var slot : WtoBotSlot&) + assume tr = slot.trigger + if (tr.coaxBlocked & bit) != 0 + return + var muzzle = unit.pos + var dir = unit.unitTm[0] + if !wto_aux_ready_barrel(unit, group, muzzle, dir) + return + let toAim = aimPt - muzzle + let dist = length(toAim) + if dist < 1.0 || dot(dir, toAim / dist) < cos(tr.aimSlackDeg * WTO_DEG_TO_RAD) + return + unit_single_shot(unit, int(group)) + tr.coaxShots++ + +def private wto_aux_target_allowed(world : WtoWorldSnap const&; slot : WtoBotSlot const&) : bool + let idx = wto_world_find_unit(world, slot.perceive.targetEid) + if idx < 0 + return false + assume tgt = world.units[idx] + return WTO_AI_FC_AUX_FIRE_AT_ARMOR || tgt.isLightTag || tgt.halfWid < 1.35 + +// Per frame while the main weapon is engaging a target in sight. +[never_inline] +def public wto_fire_aux_update(world : WtoWorldSnap const&; var unit : Unit?; now, distXZ : float; aimPt : float3; + var slot : WtoBotSlot&; var fireBudget : int&) + assume tr = slot.trigger + if !WTO_AI_FC_AUX_ENABLED || unit == null || unit.weap == null || distXZ > WTO_AI_FC_AUX_MAX_RANGE_M + return + if !wto_aux_target_allowed(world, slot) + return + var started = false + let onTarget = slot.fire.lastAimErrDeg <= tr.aimSlackDeg + if wto_trig_burst_gate(now, onTarget, tr.coaxBurstUntil, tr.coaxPauseUntil, started) != WTO_DENY_OK + return + if started || now >= tr.coaxCheckedUntil + if fireBudget <= 0 + return + fireBudget-- + tr.coaxBlocked = 0 + if wto_aux_blocked(world, unit, WeaponTriggerGroups.TRIGGER_GROUP_SECONDARY, aimPt, slot) + tr.coaxBlocked |= AUX_SECONDARY_BIT + if wto_aux_blocked(world, unit, WeaponTriggerGroups.TRIGGER_GROUP_COAXIAL_GUN, aimPt, slot) + tr.coaxBlocked |= AUX_COAXIAL_BIT + tr.coaxCheckedUntil = now + WTO_AI_FC_BURST_RECHECK_SEC + wto_aux_fire_group(unit, WeaponTriggerGroups.TRIGGER_GROUP_SECONDARY, AUX_SECONDARY_BIT, aimPt, slot) + wto_aux_fire_group(unit, WeaponTriggerGroups.TRIGGER_GROUP_COAXIAL_GUN, AUX_COAXIAL_BIT, aimPt, slot) diff --git a/game-ai/ground/wto_ai_fire_common.das b/game-ai/ground/wto_ai_fire_common.das index a2dd027..2958eba 100644 --- a/game-ai/ground/wto_ai_fire_common.das +++ b/game-ai/ground/wto_ai_fire_common.das @@ -1,5 +1,6 @@ // Turret servo, active loaded-shell inspection, and ballistic aim solver. -// All ground weapon firing goes exclusively through wto_fire_gate_try_shoot. +// Main weapon firing goes exclusively through wto_fire_gate_try_shoot, secondary and coaxial +// weapons through wto_fire_aux_update. options indenting = 2 options no_global_heap = true module wto_ai_fire_common shared @@ -24,6 +25,8 @@ require %appGame.wtoai.wto_ai_estimate_common require %appGame.wtoai.wto_ai_fire_gate_common require %appGame.wtoai.wto_ai_traverse_common require %appGame.wtoai.wto_ai_turret_common +require %appGame.wtoai.wto_ai_trigger_common +require %appGame.wtoai.wto_ai_fire_aux_common [never_inline] def private wto_sync_active_shell(gun : WTGun const?; spec : WtoVehicleSpec const&; var fc : WtoFireState&) @@ -60,6 +63,7 @@ def private wto_select_next_shell(var gun : WTGun?; spec : WtoVehicleSpec const& return var bestSoft = -1 var bestArmor = -1 + var bestArmorPen = -1.0 var firstAvail = -1 for bsIdx in range(setCount) assume bs = gun.properties.bulletSets[bsIdx] @@ -76,8 +80,9 @@ def private wto_select_next_shell(var gun : WTGun?; spec : WtoVehicleSpec const& continue if spec.shells[si].isSoftShell && bestSoft < 0 bestSoft = bsIdx - elif spec.shells[si].isAntiArmor && bestArmor < 0 + elif spec.shells[si].isAntiArmor && spec.shells[si].penMm > bestArmorPen bestArmor = bsIdx + bestArmorPen = spec.shells[si].penMm break var wantIdx = wantSoft ? (bestSoft >= 0 ? bestSoft : bestArmor) : (bestArmor >= 0 ? bestArmor : firstAvail) if wantIdx < 0 @@ -85,6 +90,16 @@ def private wto_select_next_shell(var gun : WTGun?; spec : WtoVehicleSpec const& if wantIdx >= 0 && int(gun.nextBulletType) != wantIdx gun.nextBulletType = uint8(wantIdx) +// The first working gun of the primary group becomes the weapon the fire control aims and loads. +[never_inline] +def private wto_take_primary_gun(var gun : WTGun?; turretNo, previousTurret : int; spec : WtoVehicleSpec const&; + wantSoftShell : bool; var fc : WtoFireState&) + fc.turretNo = turretNo + if fc.turretNo != previousTurret + fc.loadedBulletIdx = -1 + wto_select_next_shell(gun, spec, wantSoftShell) + wto_sync_active_shell(gun, spec, fc) + [never_inline] def private wto_inspect_primary_weapon(var unit : Unit?; now : float; spec : WtoVehicleSpec const&; wantSoftShell : bool; @@ -125,18 +140,25 @@ def private wto_inspect_primary_weapon(var unit : Unit?; now : float; anyAlive = true if selected < 0 selected = index - fc.turretNo = weapon.turretNo - if fc.turretNo != previousTurret - fc.loadedBulletIdx = -1 - wto_select_next_shell(gun, spec, wantSoftShell) - wto_sync_active_shell(gun, spec, fc) + wto_take_primary_gun(gun, int(weapon.turretNo), previousTurret, spec, wantSoftShell, fc) if gun.isReadyToShoot fc.gunReady = true totalLoaded += max(0, gun.currentLoadedAmmoCount) if gun.currentLoadedAmmoCount > 0 || gun.currentBulletSet.bulletsCount > 0 || weapon.countBullets > 0 anyReserve = true + wto_finish_weapon_state(now, spec, anyGun, anyAlive, anyReserve, totalLoaded, fc) + return selected + +// Damage, reload and shot confirmation from what wto_inspect_primary_weapon found. +[never_inline] +def private wto_finish_weapon_state(now : float; spec : WtoVehicleSpec const&; anyGun, anyAlive, anyReserve : bool; + totalLoaded : int; var fc : WtoFireState&) fc.gunDamaged = anyGun && !anyAlive - fc.reloading = anyAlive && !fc.gunReady && anyReserve + // A belt-fed autocannon is not ready between two rounds; only a longer wait is a reload. + if fc.gunReady || !anyAlive + fc.notReadySince = now + let acReload = (now - fc.notReadySince) > WTO_AI_FC_AC_RELOAD_DETECT_SEC + fc.reloading = anyAlive && !fc.gunReady && anyReserve && (!spec.isAutocannonBelt || acReload) if fc.pendingShotConfirm if (fc.prevLoadedAmmo >= 0 && totalLoaded < fc.prevLoadedAmmo) || !fc.gunReady fc.shotCount++ @@ -144,7 +166,6 @@ def private wto_inspect_primary_weapon(var unit : Unit?; now : float; elif (now - fc.pendingShotAt) > 0.35 fc.pendingShotConfirm = false fc.prevLoadedAmmo = totalLoaded - return selected [never_inline] def private wto_solve_ballistic_aim(muzzlePos, myVel : float3; var slot : WtoBotSlot&; @@ -191,20 +212,25 @@ def private wto_clear_aim_tracking(var fc : WtoFireState&) fc.lastAligned = false fc.lastDenyReason = WTO_DENY_NO_TARGET +// SPAA vs aircraft only delegates to stock air-target fire control (never ground targets). +[never_inline] +def private wto_yield_air_fire(var unit : Unit?; var slot : WtoBotSlot&) + wto_set_hull_aim(unit, false, 0.0, unit.unitTm[0], slot) + wto_clear_aim_tracking(slot.fire) + wto_trig_clear(slot.trigger) + var gm = as_gm(unit) + if gm != null + *gm |> set_check_visibility_target(true) + *gm |> set_ignore_stop_for_fire(true) + set_unit_attack_type(unit, "attack_target") + [never_inline] def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; className : string; now, dt : float; var slot : WtoBotSlot&; var fireBudget : int&) if !WTO_AI_LAYER_FIRE_CONTROL || unit == null || unit.weap == null return - // SPAA vs aircraft only delegates to stock air-target fire control (never ground targets). if slot.tactics.spaaYieldAir - wto_set_hull_aim(unit, false, 0.0, unit.unitTm[0], slot) - wto_clear_aim_tracking(slot.fire) - var gm = as_gm(unit) - if gm != null - *gm |> set_check_visibility_target(true) - *gm |> set_ignore_stop_for_fire(true) - set_unit_attack_type(unit, "attack_target") + wto_yield_air_fire(unit, slot) return set_unit_attack_type(unit, "dont_aim") var wantSoftShell = false @@ -239,6 +265,8 @@ def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; classN wto_set_hull_aim(unit, canEngage, wishYaw, liveBarrelDir, slot) if !canEngage wto_clear_aim_tracking(slot.fire) + wto_trig_clear(slot.trigger) return let distXZ = sqrt(wto_xz_dist_sq(unit.pos, slot.perceive.knownPos)) wto_fire_gate_try_shoot(world, unit, now, distXZ, muzzlePos, aimPt, liveBarrelDir, wishWorldDir, slot, fireBudget) + wto_fire_aux_update(world, unit, now, distXZ, aimPt, slot, fireBudget) diff --git a/game-ai/ground/wto_ai_fire_gate_common.das b/game-ai/ground/wto_ai_fire_gate_common.das index d39b049..6a14df3 100644 --- a/game-ai/ground/wto_ai_fire_gate_common.das +++ b/game-ai/ground/wto_ai_fire_gate_common.das @@ -1,7 +1,10 @@ -// Single fire-permission gate for every ground weapon (main cannon, launcher, SPAA self-defense). -// Every shot must pass visual confirmation, weapon readiness, distance-tier speed limits, -// 800 m continuous LOS window, aim settle, frame pre-fire budget, muzzle hard-ray, drag-integrated -// ballistic trajectory sweep, predicted friendly corridor, and multi-barrel group validation. +// Single fire-permission gate for the main weapon (cannon, launcher, SPAA self-defense). +// Every shot must pass visual confirmation, weapon readiness, the 800 m continuous LOS window, the +// trigger channel's hit probability against its fire threshold (wto_ai_trigger_common.das), aim +// settle, frame pre-fire budget, muzzle hard-ray, drag-integrated ballistic trajectory sweep, +// predicted friendly corridor, and multi-barrel group validation. A belt-fed autocannon fires in +// bursts whenever it is roughly on target and repeats the expensive checks only every +// fireControl.burstRecheckSec within a burst. options indenting = 2 options no_global_heap = true module wto_ai_fire_gate_common shared @@ -16,12 +19,12 @@ require %game.utils.utils_common require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_combat_types_common -require %appGame.wtoai.wto_ai_fire_speed_common require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_sight_common +require %appGame.wtoai.wto_ai_trigger_common [never_inline] -def private wto_gate_friendly_segment_clear(world : WtoWorldSnap const&; selfEid : EntityId; +def public wto_gate_friendly_segment_clear(world : WtoWorldSnap const&; selfEid : EntityId; army : int; p0, p1 : float3; tMid : float) : bool let delta = p1 - p0 let segLen = length(delta) @@ -43,7 +46,7 @@ def private wto_gate_friendly_segment_clear(world : WtoWorldSnap const&; selfEid def private wto_gate_check_ballistic_arc(world : WtoWorldSnap const&; selfEid, targetEid : EntityId; army : int; muzzlePos, liveDir, carrierVel, aimPt : float3; - speedMps, dragCx, massKg, caliberM : float; + speedMps, dragCx, massKg, caliberM : float; checkMiss : bool; var outBlock : int&) : int let toAim = aimPt - muzzlePos let targetDist = length(toAim) @@ -85,14 +88,14 @@ def private wto_gate_check_ballistic_arc(world : WtoWorldSnap const&; t += dt if isLast let missTol = max(3.2, targetDist * 0.012) - if length_sq(cur - aimPt) > missTol * missTol + if checkMiss && length_sq(cur - aimPt) > missTol * missTol return WTO_DENY_AIM_ERR return WTO_DENY_OK return WTO_DENY_AIM_ERR [never_inline] def private wto_gate_check_barrel(world : WtoWorldSnap const&; unit : Unit const?; - slot : WtoBotSlot const&; muzzlePos, liveDir, aimPt : float3; + slot : WtoBotSlot const&; muzzlePos, liveDir, aimPt : float3; checkMiss : bool; var outBlock : int&) : int let straightBlk = wto_sight_hard_segment_blocked(world, slot.eid, slot.perceive.targetEid, muzzlePos, aimPt, 0.05, 0.35, 0.65) if straightBlk != WTO_BLOCK_NONE @@ -100,13 +103,13 @@ def private wto_gate_check_barrel(world : WtoWorldSnap const&; unit : Unit const return WTO_DENY_MUZZLE_HARD return wto_gate_check_ballistic_arc(world, slot.eid, slot.perceive.targetEid, slot.army, muzzlePos, liveDir, unit.vel, aimPt, - slot.fire.activeSpeedMps, slot.fire.activeDragCx, slot.fire.activeMassKg, slot.fire.activeCaliberM, outBlock) + slot.fire.activeSpeedMps, slot.fire.activeDragCx, slot.fire.activeMassKg, slot.fire.activeCaliberM, checkMiss, outBlock) [never_inline] def private wto_gate_check_all_primary_guns(world : WtoWorldSnap const&; unit : Unit const?; slot : WtoBotSlot const&; primaryMuzzle, primaryDir, aimPt : float3; - var outBlock : int&) : int - let primaryRes = wto_gate_check_barrel(world, unit, slot, primaryMuzzle, primaryDir, aimPt, outBlock) + checkMiss : bool; var outBlock : int&) : int + let primaryRes = wto_gate_check_barrel(world, unit, slot, primaryMuzzle, primaryDir, aimPt, checkMiss, outBlock) if primaryRes != WTO_DENY_OK return primaryRes if unit == null || unit.weap == null @@ -121,7 +124,7 @@ def private wto_gate_check_all_primary_guns(world : WtoWorldSnap const&; unit : weapon_calcShootTm(weapon, unit.unitTm, gunTm) if length_sq(gunTm[0]) <= 0.25 continue - let secRes = wto_gate_check_barrel(world, unit, slot, gunTm[3], normalize(gunTm[0]), aimPt, outBlock) + let secRes = wto_gate_check_barrel(world, unit, slot, gunTm[3], normalize(gunTm[0]), aimPt, checkMiss, outBlock) if secRes != WTO_DENY_OK return secRes == WTO_DENY_FRIENDLY ? WTO_DENY_FRIENDLY : WTO_DENY_MULTI_GUN return WTO_DENY_OK @@ -147,20 +150,22 @@ def private wto_gate_track_aim(now : float; offset : float3; target : EntityId; fc.settleHoldSec = max(0.0, fc.settleHoldSec - age) [never_inline] -def private wto_gate_log_deny(now, distXZ, measuredSpeed, speedLimit : float; reason, blk : int; var slot : WtoBotSlot&) +def private wto_gate_log_deny(now, distXZ : float; reason, blk : int; var slot : WtoBotSlot&) assume fc = slot.fire + assume tr = slot.trigger let changed = fc.lastDenyReason != reason || fc.lastDenyBlock != blk fc.lastDenyReason = reason fc.lastDenyBlock = blk - if WTO_AI_DIAG_TELEMETRY && reason >= WTO_DENY_SPEED && (changed || (now - fc.lastDenyLogAt) >= 4.0) + let logged = reason >= WTO_DENY_HIT_PROB && reason != WTO_DENY_BURST_PAUSE + if WTO_AI_DIAG_TELEMETRY && logged && (changed || (now - fc.lastDenyLogAt) >= 4.0) fc.lastDenyLogAt = now - print("WTO_AI|DENY|eid={uint(slot.eid)}|reason={reason}|block={blk}|dist={distXZ}|spd={measuredSpeed}|limit={speedLimit}|err={fc.lastAimErrDeg}|drift={fc.aimDriftDegSec}\n") + print("WTO_AI|DENY|eid={uint(slot.eid)}|reason={reason}|block={blk}|dist={distXZ}|p={tr.hitProb}|pAligned={tr.hitProbAligned}|thr={tr.threshold}|wantV={tr.wantSpeedMps}|err={fc.lastAimErrDeg}|drift={fc.aimDriftDegSec}\n") [never_inline] -def private wto_gate_request_primary_shot(var unit : Unit?; now, distXZ, measuredSpeed, speedLimit : float; - var slot : WtoBotSlot&) +def private wto_gate_request_primary_shot(var unit : Unit?; now, distXZ : float; var slot : WtoBotSlot&) assume fc = slot.fire unit_single_shot(unit, int(WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY)) + let firstOfBurst = !slot.spec.isAutocannonBelt || (now - fc.lastShotAt) > 0.5 fc.lastShotAt = now fc.pendingShotConfirm = true fc.pendingShotAt = now @@ -170,8 +175,80 @@ def private wto_gate_request_primary_shot(var unit : Unit?; now, distXZ, measure fc.maxShotErrDeg = max(fc.maxShotErrDeg, fc.lastAimErrDeg) if !slot.spec.isAutocannonBelt fc.settleHoldSec = 0.0 - if WTO_AI_DIAG_TELEMETRY - print("WTO_AI|SHOT|eid={uint(slot.eid)}|tgt={uint(slot.perceive.targetEid)}|dist={distXZ}|spd={measuredSpeed}|limit={speedLimit}|v0={fc.activeSpeedMps}|err={fc.lastAimErrDeg}\n") + slot.trigger.biasEpoch++ + if WTO_AI_DIAG_TELEMETRY && firstOfBurst + print("WTO_AI|SHOT|eid={uint(slot.eid)}|tgt={uint(slot.perceive.targetEid)}|dist={distXZ}|spd={length(unit.vel)}|p={slot.trigger.hitProb}|thr={slot.trigger.threshold}|v0={fc.activeSpeedMps}|err={fc.lastAimErrDeg}\n") + +// Main gun: one shot per permission, once the hit probability reaches the threshold and the +// barrel has settled on the target. +[never_inline] +def private wto_gate_try_single(world : WtoWorldSnap const&; var unit : Unit?; now, distXZ : float; + muzzlePos, aimPt, liveDir, wishDir : float3; probOk, withinTraverse : bool; + var slot : WtoBotSlot&; var fireBudget : int&) + assume fc = slot.fire + let close = distXZ <= WTO_AI_FC_CLOSE_RANGE_M + wto_gate_track_aim(now, liveDir - wishDir, slot.perceive.targetEid, withinTraverse && probOk, close, fc) + let reqHold = close ? WTO_AI_FC_CLOSE_SETTLE_HOLD_SEC : WTO_AI_FC_SETTLE_HOLD_SEC + var deny = WTO_DENY_OK + if !withinTraverse + deny = WTO_DENY_TRAVERSE + elif !fc.gunReady || (now - fc.lastShotAt) < WTO_AI_FC_MIN_SHOT_INTERVAL_SEC + deny = WTO_DENY_NOT_READY + elif distXZ > WTO_AI_FC_LONG_RANGE_M && (slot.perceive.goodLosSec < WTO_AI_FC_LONG_WINDOW_SEC || slot.perceive.visiblePointCount < 2) + deny = WTO_DENY_LONG_WINDOW + elif !probOk + // Only the barrel still swinging onto the target, or the shot itself not good enough. + deny = slot.trigger.hitProbAligned >= slot.trigger.threshold ? WTO_DENY_AIM_ERR : WTO_DENY_HIT_PROB + elif !fc.lastAligned || fc.settleHoldSec < reqHold + deny = WTO_DENY_SETTLE + elif fireBudget <= 0 + deny = WTO_DENY_BUDGET + if deny != WTO_DENY_OK + wto_gate_log_deny(now, distXZ, deny, WTO_BLOCK_NONE, slot) + return + fireBudget-- + var blk = WTO_BLOCK_NONE + let gateRes = wto_gate_check_all_primary_guns(world, unit, slot, muzzlePos, liveDir, aimPt, true, blk) + if gateRes != WTO_DENY_OK + wto_gate_log_deny(now, distXZ, gateRes, blk, slot) + return + wto_gate_request_primary_shot(unit, now, distXZ, slot) + +// Belt-fed autocannon (decision layer design, 6.3): bursts while within the aim slack, without +// waiting for the barrel to settle; the barrel, trajectory and friendly checks run at the start +// of a burst and every burstRecheckSec, not for every round. +[never_inline] +def private wto_gate_try_burst(world : WtoWorldSnap const&; var unit : Unit?; now, distXZ : float; + muzzlePos, aimPt, liveDir : float3; aimErrDeg : float; withinTraverse : bool; + var slot : WtoBotSlot&; var fireBudget : int&) + assume fc = slot.fire + assume tr = slot.trigger + var deny = WTO_DENY_OK + var started = false + if !withinTraverse + deny = WTO_DENY_TRAVERSE + elif !fc.gunReady + deny = WTO_DENY_NOT_READY + elif distXZ > WTO_AI_FC_LONG_RANGE_M && slot.perceive.goodLosSec < WTO_AI_FC_LONG_WINDOW_SEC + deny = WTO_DENY_LONG_WINDOW + else + deny = wto_trig_burst_gate(now, aimErrDeg <= tr.aimSlackDeg, tr.burstUntil, tr.burstPauseUntil, started) + if started + tr.biasEpoch++ + tr.burstCheckedUntil = -100.0 + var blk = WTO_BLOCK_NONE + if deny == WTO_DENY_OK && now >= tr.burstCheckedUntil + if fireBudget <= 0 + deny = WTO_DENY_BUDGET + else + fireBudget-- + deny = wto_gate_check_all_primary_guns(world, unit, slot, muzzlePos, liveDir, aimPt, false, blk) + if deny == WTO_DENY_OK + tr.burstCheckedUntil = now + WTO_AI_FC_BURST_RECHECK_SEC + if deny != WTO_DENY_OK + wto_gate_log_deny(now, distXZ, deny, blk, slot) + return + wto_gate_request_primary_shot(unit, now, distXZ, slot) [never_inline] def public wto_fire_gate_try_shoot(world : WtoWorldSnap const&; var unit : Unit?; @@ -180,39 +257,10 @@ def public wto_fire_gate_try_shoot(world : WtoWorldSnap const&; var unit : Unit? assume fc = slot.fire let aimErrDeg = acos(clamp(dot(liveDir, wishDir), -1.0, 1.0)) * WTO_RAD_TO_DEG fc.lastAimErrDeg = aimErrDeg - let measuredSpeed = length(unit.vel) - let halting = slot.drive.routeBOwned && slot.tactics.state == WTO_STATE_SHORT_HALT - let speedLimit = halting ? WTO_AI_FC_STOP_SPEED_MAX_MPS : wto_fire_speed_limit_mps(distXZ, slot.spec.vMaxFwd) - let speedOk = measuredSpeed <= speedLimit - let close = distXZ <= WTO_AI_FC_CLOSE_RANGE_M - let allowErrDeg = clamp(atan2(WTO_AI_FC_CLOSE_HIT_RADIUS_M, max(distXZ, 6.0)) * WTO_RAD_TO_DEG, WTO_AI_FC_BASE_ALIGN_DEG, 2.4) + let turnDegSec = abs(slot.drive.omegaYawRad) * WTO_RAD_TO_DEG + let probOk = wto_trig_evaluate(world, now, unit.pos, length(unit.vel), turnDegSec, distXZ, aimErrDeg, slot) let withinTraverse = fc.hullAimTarget == INVALID_ENTITY_ID - wto_gate_track_aim(now, liveDir - wishDir, slot.perceive.targetEid, withinTraverse && aimErrDeg <= allowErrDeg && speedOk, close, fc) - - let minCadence = slot.spec.isAutocannonBelt ? 0.12 : 0.65 - let reqHold = close ? WTO_AI_FC_CLOSE_SETTLE_HOLD_SEC : WTO_AI_FC_SETTLE_HOLD_SEC - var deny = WTO_DENY_OK - if !withinTraverse - deny = WTO_DENY_TRAVERSE - elif !fc.gunReady || (now - fc.lastShotAt) < minCadence - deny = WTO_DENY_NOT_READY - elif !speedOk - deny = WTO_DENY_SPEED - elif distXZ > WTO_AI_FC_LONG_RANGE_M && (slot.perceive.goodLosSec < WTO_AI_FC_LONG_WINDOW_SEC || slot.perceive.visiblePointCount < 2) - deny = WTO_DENY_LONG_WINDOW - elif aimErrDeg > allowErrDeg - deny = WTO_DENY_AIM_ERR - elif !fc.lastAligned || fc.settleHoldSec < reqHold - deny = WTO_DENY_SETTLE - elif fireBudget <= 0 - deny = WTO_DENY_BUDGET - if deny != WTO_DENY_OK - wto_gate_log_deny(now, distXZ, measuredSpeed, speedLimit, deny, WTO_BLOCK_NONE, slot) - return - fireBudget-- - var blk = WTO_BLOCK_NONE - let gateRes = wto_gate_check_all_primary_guns(world, unit, slot, muzzlePos, liveDir, aimPt, blk) - if gateRes != WTO_DENY_OK - wto_gate_log_deny(now, distXZ, measuredSpeed, speedLimit, gateRes, blk, slot) - return - wto_gate_request_primary_shot(unit, now, distXZ, measuredSpeed, speedLimit, slot) + if slot.spec.isAutocannonBelt + wto_gate_try_burst(world, unit, now, distXZ, muzzlePos, aimPt, liveDir, aimErrDeg, withinTraverse, slot, fireBudget) + else + wto_gate_try_single(world, unit, now, distXZ, muzzlePos, aimPt, liveDir, wishDir, probOk, withinTraverse, slot, fireBudget) diff --git a/game-ai/ground/wto_ai_perceive_common.das b/game-ai/ground/wto_ai_perceive_common.das index c46018d..e2bdb17 100644 --- a/game-ai/ground/wto_ai_perceive_common.das +++ b/game-ai/ground/wto_ai_perceive_common.das @@ -216,6 +216,8 @@ def public wto_perceive_update(var world : WtoWorldSnap&; now, dt : float; wto_scan_visual_exposure(world, now, dt, myEye, lookDir, hullDir, lookAround, slot, bestIdx, visCount, goodLosSec, aimPt) if bestIdx >= 0 assume tgt = world.units[bestIdx] + if tgt.isShooting || p.targetEid != tgt.eid + p.targetShotAt = tgt.isShooting ? now : -100.0 p.targetEid = tgt.eid p.targetIsAir = tgt.isAir p.hasClearLos = true diff --git a/game-ai/ground/wto_ai_sight_common.das b/game-ai/ground/wto_ai_sight_common.das index efa53bd..0d4374a 100644 --- a/game-ai/ground/wto_ai_sight_common.das +++ b/game-ai/ground/wto_ai_sight_common.das @@ -116,11 +116,13 @@ def public wto_sight_check_target_samples(world : WtoWorldSnap const&; pts[3] = tgt.pos - left * sideOff + float3(0.0, 1.25, 0.0) let count = clamp(maxSamples, 1, 4) var vis = 0 - var picked = false + var sum = float3(0.0, 0.0, 0.0) for s in range(count) if wto_sight_visual_clear(world, selfEid, tgt.eid, eyePos, pts[s]) == WTO_BLOCK_NONE - if !picked - outBestPt = pts[s] - picked = true + sum += pts[s] vis++ + // Aim at the middle of what is visible (decision layer design, 6.2), not at the first visible + // point, which with the hull hidden is the gun mantlet every time. + if vis > 0 + outBestPt = sum / float(vis) return vis diff --git a/game-ai/ground/wto_ai_specs_common.das b/game-ai/ground/wto_ai_specs_common.das index f132497..60ebdfb 100644 --- a/game-ai/ground/wto_ai_specs_common.das +++ b/game-ai/ground/wto_ai_specs_common.das @@ -1,6 +1,6 @@ // Authoritative per-vehicle specification loader: reads unit & weapon DataBlocks once per // spawned bot (`gamedata/units/.blk`) to extract role, gun stabilizer, -// turret slew rates, shell muzzle velocity, and chassis capabilities. +// turret slew rates, shell muzzle velocity and stock maximum penetration, and chassis capabilities. options indenting = 2 options no_global_heap = true module wto_ai_specs_common shared @@ -15,6 +15,7 @@ require Unit require IGroundModel require HeavyVehicleModel require Weapon +require WTBallistics require %game.utils.utils_common require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_combat_types_common @@ -65,6 +66,7 @@ def private wto_record_shell_block(bBlk : DataBlock const&; var spec : WtoVehicl spec.shells[idx].caliberM = cal spec.shells[idx].isSoftShell = isSoft spec.shells[idx].isAntiArmor = !isSoft && !isNonCombat + spec.shells[idx].penMm = float(calc_max_penetration(bBlk)) spec.shellCount = idx + 1 [never_inline] diff --git a/game-ai/ground/wto_ai_stats_common.das b/game-ai/ground/wto_ai_stats_common.das index 83fce0c..ed37fc1 100644 --- a/game-ai/ground/wto_ai_stats_common.das +++ b/game-ai/ground/wto_ai_stats_common.das @@ -37,9 +37,10 @@ struct public WtoBattleStats movingShots : int[5] bandShots : int[3] bandMoving : int[3] - denySec : float[13] + denySec : float[14] acWindowSec : float = 0.0 acShots : int = 0 + auxShots : int = 0 def private wto_stats_role(slot : WtoBotSlot const&) : int return clamp(slot.spec.role, 0, 4) @@ -90,6 +91,8 @@ def private wto_stats_spot(now : float; groundTgt : bool; var slot : WtoBotSlot& [never_inline] def private wto_stats_shots(myPos : float3; var slot : WtoBotSlot&; var bs : WtoBattleStats&) assume st = slot.stats + bs.auxShots += slot.trigger.coaxShots - st.lastAuxShots + st.lastAuxShots = slot.trigger.coaxShots let fired = slot.fire.shotCount - st.lastShots st.lastShots = slot.fire.shotCount if fired <= 0 @@ -108,12 +111,14 @@ def private wto_stats_shots(myPos : float3; var slot : WtoBotSlot&; var bs : Wto [never_inline] def private wto_stats_window(dt : float; myPos : float3; groundTgt : bool; slot : WtoBotSlot const&; var bs : WtoBattleStats&) - if !groundTgt || !slot.fire.gunReady || slot.fire.reloading + // A belt-fed autocannon is briefly not ready between rounds; that still counts as a window. + let ready = slot.fire.gunReady || slot.spec.isAutocannonBelt + if !groundTgt || !ready || slot.fire.reloading return if wto_xz_dist_sq(myPos, slot.perceive.knownPos) > WTO_AI_FC_MAX_RANGE_M * WTO_AI_FC_MAX_RANGE_M return bs.windowSec[wto_stats_role(slot)] += dt - bs.denySec[clamp(slot.fire.lastDenyReason, 0, 12)] += dt + bs.denySec[clamp(slot.fire.lastDenyReason, 0, WTO_DENY_COUNT - 1)] += dt if slot.spec.isAutocannonBelt bs.acWindowSec += dt @@ -195,7 +200,7 @@ def private wto_stats_log(now : float; why : string; bs : WtoBattleStats const&) if bs.spotted[role] + bs.samples[role] + bs.shots[role] > 0 wto_stats_log_role(now, why, role, bs) assume d = bs.denySec - print("WTO_AI|BATTLE_STATS_FIRE|why={why}|t={now}|shotsBand={bs.bandShots[0]}/{bs.bandShots[1]}/{bs.bandShots[2]}|movingBand={bs.bandMoving[0]}/{bs.bandMoving[1]}/{bs.bandMoving[2]}|denySec=ok:{d[0]},noTarget:{d[1]},notReady:{d[2]},speed:{d[3]},longWindow:{d[4]},aimErr:{d[5]},settle:{d[6]},budget:{d[7]},muzzle:{d[8]},arc:{d[9]},friendly:{d[10]},multiGun:{d[11]},traverse:{d[12]}|acWindowSec={bs.acWindowSec}|acShots={bs.acShots}\n") + print("WTO_AI|BATTLE_STATS_FIRE|why={why}|t={now}|shotsBand={bs.bandShots[0]}/{bs.bandShots[1]}/{bs.bandShots[2]}|movingBand={bs.bandMoving[0]}/{bs.bandMoving[1]}/{bs.bandMoving[2]}|denySec=ok:{d[0]},noTarget:{d[1]},notReady:{d[2]},hitProb:{d[3]},longWindow:{d[4]},aimErr:{d[5]},settle:{d[6]},budget:{d[7]},muzzle:{d[8]},arc:{d[9]},friendly:{d[10]},multiGun:{d[11]},traverse:{d[12]},burstPause:{d[13]}|acWindowSec={bs.acWindowSec}|acShots={bs.acShots}|auxShots={bs.auxShots}\n") // Per world tick: the cumulative statistics every statsLogIntervalSec. [never_inline] diff --git a/game-ai/ground/wto_ai_tactics_common.das b/game-ai/ground/wto_ai_tactics_common.das index 53db140..b69591d 100644 --- a/game-ai/ground/wto_ai_tactics_common.das +++ b/game-ai/ground/wto_ai_tactics_common.das @@ -120,7 +120,7 @@ def private wto_sm_march_speed(slot : WtoBotSlot const&; distGoal : float) : flo def private wto_sm_waited_for_moving_shot(now : float; aimReady : bool; var slot : WtoBotSlot&) : bool assume tac = slot.tactics let deny = slot.fire.lastDenyReason - let blocked = deny == WTO_DENY_SPEED || deny == WTO_DENY_AIM_ERR || deny == WTO_DENY_SETTLE + let blocked = deny == WTO_DENY_HIT_PROB || deny == WTO_DENY_AIM_ERR || deny == WTO_DENY_SETTLE if tac.state != WTO_STATE_RUN_AND_GUN || !aimReady || !blocked tac.movingShotBlockedSince = -100.0 return false diff --git a/game-ai/ground/wto_ai_trigger_common.das b/game-ai/ground/wto_ai_trigger_common.das new file mode 100644 index 0000000..f63b4c6 --- /dev/null +++ b/game-ai/ground/wto_ai_trigger_common.das @@ -0,0 +1,151 @@ +// Trigger channel (decision layer design, section 6): instead of a speed limit per distance band, +// a shot is taken when its estimated hit probability reaches a fire threshold that moves with the +// situation. The hit probability comes from the angular size of the target's visible part against +// the expected angular error of the shot: the crew's aim, the bot's own motion (much less with a +// stabilizer), the uncertainty of the lead on a crossing target, and where the barrel points now. +// It also asks the hull channel for the highest speed at which the shot would be good enough. +options indenting = 2 +options no_global_heap = true +module wto_ai_trigger_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_world_common +require %appGame.wtoai.wto_ai_threat_common + +// Error function, Abramowitz and Stegun 7.1.26 (absolute error below 1.5e-7). +def private wto_trig_erf(x : float) : float + let ax = abs(x) + let t = 1.0 / (1.0 + 0.3275911 * ax) + let poly = ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t + let y = 1.0 - poly * exp(-ax * ax) + return x >= 0.0 ? y : -y + +// Chance that a shot with mean error `offset` and normal spread `sigma` lands within +-half. +def private wto_trig_window(half, offset, sigma : float) : float + let s = max(1.0e-5, sigma) * 1.41421356 + return clamp(0.5 * (wto_trig_erf((half - offset) / s) + wto_trig_erf((half + offset) / s)), 0.0, 1.0) + +// Hit probability against a target `halfW` x `halfH` metres at `dist` (angles in radians). +def private wto_trig_prob(halfW, halfH, dist, offsetRad, sigmaRad : float) : float + let o = offsetRad * 0.7071 + let d = max(dist, 5.0) + return wto_trig_window(atan2(halfW, d), o, sigmaRad) * wto_trig_window(atan2(halfH, d), o, sigmaRad) + +// Expected angular spread of a shot (radians) at own speed and hull turn rate. +def private wto_trig_sigma(spec : WtoVehicleSpec const&; speedMps, turnDegSec, leadErrM, dist : float) : float + let stab = spec.hasVertStab ? WTO_AI_FC_STAB_ERR_FACTOR : 1.0 + let moveDeg = (speedMps * WTO_AI_FC_MOVE_ERR_DEG_PER_MPS + turnDegSec * WTO_AI_FC_TURN_ERR_DEG_PER_DEG_SEC) * stab + let base = WTO_AI_FC_AIM_ERROR_DEG * WTO_DEG_TO_RAD + let move = moveDeg * WTO_DEG_TO_RAD + let lead = leadErrM / max(dist, 10.0) + return sqrt(base * base + move * move + lead * lead) + +// Half width and half height (m) of the visible part of the target as seen from `myPos`. +def private wto_trig_target_half(myPos : float3; tgt : WtoUnitSnap const&; dist : float; visCount : int; + var halfW, halfH : float&) + let los = wto_xz_normalize(tgt.pos - myPos, float3(1.0, 0.0, 0.0)) + let perp = float3(-los.z, 0.0, los.x) + let fwd = wto_xz_normalize(tgt.hullFwd, los) + let left = float3(-fwd.z, 0.0, fwd.x) + let sampled = dist > WTO_AI_FC_LONG_RANGE_M ? 2.0 : 4.0 + let part = 0.35 + 0.65 * clamp(float(visCount) / sampled, 0.0, 1.0) + halfW = (abs(dot(fwd, perp)) * tgt.halfLen + abs(dot(left, perp)) * tgt.halfWid) * part + halfH = WTO_AI_FC_TARGET_HALF_HEIGHT_M * part + +// Fire threshold (decision layer design, 6.1): lower when the target aims at the bot, is close, +// has just fired (reloading) or is about to slip out of sight; higher for big slow-loading guns +// and while pulling back to cover. +[never_inline] +def private wto_trig_threshold(now, dist : float; fleeting : bool; slot : WtoBotSlot const&) : float + assume p = slot.perceive + var thr = WTO_AI_FC_FIRE_THRESHOLD + for i in range(slot.threat.count) + if slot.threat.entries[i].eid == p.targetEid && slot.threat.entries[i].aiming + thr -= WTO_AI_FC_AIMING_BONUS + if dist < WTO_AI_FC_CLOSE_RANGE_M + thr -= WTO_AI_FC_CLOSE_BONUS * (1.0 - dist / WTO_AI_FC_CLOSE_RANGE_M) + if now - p.targetShotAt <= WTO_AI_FC_ENEMY_RELOAD_SEC + thr -= WTO_AI_FC_ENEMY_RELOAD_BONUS + if fleeting + thr -= WTO_AI_FC_FLEETING_BONUS + thr += WTO_AI_FC_BIG_GUN_PENALTY * clamp((slot.fire.activeCaliberM - 0.075) / 0.05, 0.0, 1.0) + if slot.tactics.state == WTO_STATE_RETREAT_COVER + thr += WTO_AI_FC_RETREAT_PENALTY + return clamp(thr, WTO_AI_FC_MIN_THRESHOLD, 0.95) + +// Highest own speed (driving straight, barrel on target) at which the shot still reaches the +// threshold: 99 when the current speed is fine or when even standing would not help. +[never_inline] +def private wto_trig_speed_request(spec : WtoVehicleSpec const&; halfW, halfH, dist, leadErrM, speedNow, thr : float) : float + if wto_trig_prob(halfW, halfH, dist, 0.0, wto_trig_sigma(spec, speedNow, 0.0, leadErrM, dist)) >= thr + return 99.0 + if wto_trig_prob(halfW, halfH, dist, 0.0, wto_trig_sigma(spec, 0.0, 0.0, leadErrM, dist)) < thr + return 99.0 + var lo = 0.0 + var hi = speedNow + for _i in range(6) + let mid = 0.5 * (lo + hi) + if wto_trig_prob(halfW, halfH, dist, 0.0, wto_trig_sigma(spec, mid, 0.0, leadErrM, dist)) >= thr + lo = mid + else + hi = mid + return lo <= WTO_AI_FC_STOP_SPEED_MAX_MPS ? 0.0 : lo + +// Evaluates the main weapon's shot at the engaged target this frame and fills slot.trigger: +// hitProb (with the barrel where it points now), hitProbAligned (barrel on target), threshold, +// the autocannon aim slack and the speed request. True when the shot is good enough. +[never_inline] +def public wto_trig_evaluate(world : WtoWorldSnap const&; now : float; myPos : float3; speedNow, turnDegSec, + dist, aimErrDeg : float; var slot : WtoBotSlot&) : bool + assume tr = slot.trigger + assume p = slot.perceive + let tgtIdx = wto_world_find_unit(world, p.targetEid) + if tgtIdx < 0 + tr.hitProb = 0.0 + tr.hitProbAligned = 0.0 + tr.wantSpeedMps = 99.0 + return false + assume tgt = world.units[tgtIdx] + var halfW = 1.5 + var halfH = 1.0 + wto_trig_target_half(myPos, tgt, dist, p.visiblePointCount, halfW, halfH) + let los = wto_xz_normalize(tgt.pos - myPos, float3(1.0, 0.0, 0.0)) + let latSpeed = abs(dot(p.estVel, float3(-los.z, 0.0, los.x))) + let tof = dist / max(120.0, slot.fire.activeSpeedMps) + let leadErrM = latSpeed * tof * WTO_AI_EST_LEAD_ERR_FRAC * (1.0 - 0.72 * p.velQuality) + let sigma = wto_trig_sigma(slot.spec, speedNow, turnDegSec, leadErrM, dist) + let fleeting = latSpeed >= WTO_AI_FC_FLEETING_LAT_MPS && p.visiblePointCount < 3 + tr.threshold = wto_trig_threshold(now, dist, fleeting, slot) + tr.hitProb = wto_trig_prob(halfW, halfH, dist, aimErrDeg * WTO_DEG_TO_RAD, sigma) + tr.hitProbAligned = wto_trig_prob(halfW, halfH, dist, 0.0, sigma) + tr.aimSlackDeg = max(WTO_AI_FC_BASE_ALIGN_DEG, WTO_AI_FC_AC_AIM_SLACK * atan2(0.5 * (halfW + halfH), max(dist, 5.0)) * WTO_RAD_TO_DEG) + tr.wantSpeedMps = wto_trig_speed_request(slot.spec, halfW, halfH, dist, leadErrM, speedNow, tr.threshold) + tr.wantSpeedAt = now + return tr.hitProb >= tr.threshold + +// Autocannon and coaxial bursts (decision layer design, 6.3): fire for burstSec, pause for +// burstPauseSec. Within a burst the weapon fires whenever it is roughly on target and stops while +// it is not; a new burst starts only when it is. `started` is set when this call opened a burst. +def public wto_trig_burst_gate(now : float; aimOk : bool; var burstUntil, pauseUntil : float&; var started : bool&) : int + started = false + if now < burstUntil + return aimOk ? WTO_DENY_OK : WTO_DENY_AIM_ERR + if now < pauseUntil + return WTO_DENY_BURST_PAUSE + if !aimOk + return WTO_DENY_AIM_ERR + burstUntil = now + WTO_AI_FC_BURST_SEC + pauseUntil = burstUntil + WTO_AI_FC_BURST_PAUSE_SEC + started = true + return WTO_DENY_OK + +// No engaged target: nothing is requested from the hull. +def public wto_trig_clear(var tr : WtoTriggerState&) + tr.hitProb = 0.0 + tr.hitProbAligned = 0.0 + tr.wantSpeedMps = 99.0 diff --git a/game-ai/ground/wto_ai_types_common.das b/game-ai/ground/wto_ai_types_common.das index ae643b9..b35c219 100644 --- a/game-ai/ground/wto_ai_types_common.das +++ b/game-ai/ground/wto_ai_types_common.das @@ -166,7 +166,6 @@ struct public WtoTacticsState stateEnteredAt : float = -100.0 moveGoal : float3 = float3(0.0, 0.0, 0.0) desiredSpeedMps : float = 10.0 - movingShotBlockedSince : float = -100.0 haltEnterAt : float = -100.0 haltStartShots : int = 0 shortHaltCooldownUntil : float = -100.0 @@ -229,6 +228,7 @@ struct public WtoBotStats spotShots : int = 0 spotPending : bool = false lastShots : int = 0 + lastAuxShots : int = 0 nextSampleAt : float = 0.0 [safe_when_uninitialized] @@ -253,3 +253,4 @@ struct public WtoBotSlot stats : WtoBotStats = WtoBotStats() threat : WtoThreatTable = WtoThreatTable() turret : WtoTurretState = WtoTurretState() + trigger : WtoTriggerState = WtoTriggerState() diff --git a/packages/patcher/src/ground-ai/ground-ai-config.ts b/packages/patcher/src/ground-ai/ground-ai-config.ts index e06c03f..5872122 100644 --- a/packages/patcher/src/ground-ai/ground-ai-config.ts +++ b/packages/patcher/src/ground-ai/ground-ai-config.ts @@ -269,12 +269,33 @@ export interface GroundAiConfig { readonly stopSpeedMaxMps: number; readonly longRangeWindowSec: number; readonly baseAlignDeg: number; - readonly closeHitRadiusM: number; readonly barrelSettleDegSec: number; readonly closeSettleHoldSec: number; readonly settleHoldSec: number; - readonly unstabilizedStopSpeedMps: number; - readonly stabilizedCreepSpeedMps: number; + readonly aimErrorDeg: number; + readonly moveErrDegPerMps: number; + readonly turnErrDegPerDegSec: number; + readonly stabErrFactor: number; + readonly targetHalfHeightM: number; + readonly fireThreshold: number; + readonly minFireThreshold: number; + readonly aimingThresholdBonus: number; + readonly closeThresholdBonus: number; + readonly enemyReloadThresholdBonus: number; + readonly enemyReloadSec: number; + readonly fleetingThresholdBonus: number; + readonly fleetingLateralMps: number; + readonly bigGunThresholdPenalty: number; + readonly retreatThresholdPenalty: number; + readonly minShotIntervalSec: number; + readonly autocannonAimSlack: number; + readonly burstSec: number; + readonly burstPauseSec: number; + readonly burstRecheckSec: number; + readonly autocannonReloadDetectSec: number; + readonly auxWeapons: boolean; + readonly auxMaxRangeM: number; + readonly auxFireAtArmor: boolean; readonly friendlyCorridorM: number; readonly ballisticStepMaxM: number; readonly ballisticSweepRadiusM: number; @@ -473,12 +494,33 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['WTO_AI_FC_STOP_SPEED_MAX_MPS', 'float', c.fireControl.stopSpeedMaxMps], ['WTO_AI_FC_LONG_WINDOW_SEC', 'float', c.fireControl.longRangeWindowSec], ['WTO_AI_FC_BASE_ALIGN_DEG', 'float', c.fireControl.baseAlignDeg], - ['WTO_AI_FC_CLOSE_HIT_RADIUS_M', 'float', c.fireControl.closeHitRadiusM], ['WTO_AI_FC_BARREL_SETTLE_DEG_SEC', 'float', c.fireControl.barrelSettleDegSec], ['WTO_AI_FC_CLOSE_SETTLE_HOLD_SEC', 'float', c.fireControl.closeSettleHoldSec], ['WTO_AI_FC_SETTLE_HOLD_SEC', 'float', c.fireControl.settleHoldSec], - ['WTO_AI_FC_UNSTAB_STOP_MPS', 'float', c.fireControl.unstabilizedStopSpeedMps], - ['WTO_AI_FC_STAB_CREEP_MPS', 'float', c.fireControl.stabilizedCreepSpeedMps], + ['WTO_AI_FC_AIM_ERROR_DEG', 'float', c.fireControl.aimErrorDeg], + ['WTO_AI_FC_MOVE_ERR_DEG_PER_MPS', 'float', c.fireControl.moveErrDegPerMps], + ['WTO_AI_FC_TURN_ERR_DEG_PER_DEG_SEC', 'float', c.fireControl.turnErrDegPerDegSec], + ['WTO_AI_FC_STAB_ERR_FACTOR', 'float', c.fireControl.stabErrFactor], + ['WTO_AI_FC_TARGET_HALF_HEIGHT_M', 'float', c.fireControl.targetHalfHeightM], + ['WTO_AI_FC_FIRE_THRESHOLD', 'float', c.fireControl.fireThreshold], + ['WTO_AI_FC_MIN_THRESHOLD', 'float', c.fireControl.minFireThreshold], + ['WTO_AI_FC_AIMING_BONUS', 'float', c.fireControl.aimingThresholdBonus], + ['WTO_AI_FC_CLOSE_BONUS', 'float', c.fireControl.closeThresholdBonus], + ['WTO_AI_FC_ENEMY_RELOAD_BONUS', 'float', c.fireControl.enemyReloadThresholdBonus], + ['WTO_AI_FC_ENEMY_RELOAD_SEC', 'float', c.fireControl.enemyReloadSec], + ['WTO_AI_FC_FLEETING_BONUS', 'float', c.fireControl.fleetingThresholdBonus], + ['WTO_AI_FC_FLEETING_LAT_MPS', 'float', c.fireControl.fleetingLateralMps], + ['WTO_AI_FC_BIG_GUN_PENALTY', 'float', c.fireControl.bigGunThresholdPenalty], + ['WTO_AI_FC_RETREAT_PENALTY', 'float', c.fireControl.retreatThresholdPenalty], + ['WTO_AI_FC_MIN_SHOT_INTERVAL_SEC', 'float', c.fireControl.minShotIntervalSec], + ['WTO_AI_FC_AC_AIM_SLACK', 'float', c.fireControl.autocannonAimSlack], + ['WTO_AI_FC_BURST_SEC', 'float', c.fireControl.burstSec], + ['WTO_AI_FC_BURST_PAUSE_SEC', 'float', c.fireControl.burstPauseSec], + ['WTO_AI_FC_BURST_RECHECK_SEC', 'float', c.fireControl.burstRecheckSec], + ['WTO_AI_FC_AC_RELOAD_DETECT_SEC', 'float', c.fireControl.autocannonReloadDetectSec], + ['WTO_AI_FC_AUX_ENABLED', 'bool', c.fireControl.auxWeapons], + ['WTO_AI_FC_AUX_MAX_RANGE_M', 'float', c.fireControl.auxMaxRangeM], + ['WTO_AI_FC_AUX_FIRE_AT_ARMOR', 'bool', c.fireControl.auxFireAtArmor], ['WTO_AI_FC_FRIENDLY_CORRIDOR_M', 'float', c.fireControl.friendlyCorridorM], ['WTO_AI_FC_BALLISTIC_STEP_M', 'float', c.fireControl.ballisticStepMaxM], ['WTO_AI_FC_BALLISTIC_SWEEP_R_M', 'float', c.fireControl.ballisticSweepRadiusM], From ee360a50428365ac55b7548e8946dc4b8d985308 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sun, 6 Dec 2026 01:11:55 +0800 Subject: [PATCH 13/19] feat(ground-ai): add the hull decision channel Score driving behaviors and reuse the existing action handlers. Face the main threat and support reverse travel on the navigation corridor. --- .../src/renderer/src/i18n/locales/en.json | 41 +++- .../src/renderer/src/i18n/locales/zh-CN.json | 41 +++- .../src/pages/tuning/BotTuningPanel.tsx | 2 +- .../src/pages/tuning/bot-tuning-fields.ts | 40 +++- apps/launcher/src/shared/schemas/tuning.ts | 38 +++- apps/server/src/tuning/ground-ai-tuning.ts | 44 ++-- apps/server/tuning/ground-ai.jsonc | 54 ++++- game-ai/ground/wto_ai_behavior_common.das | 203 +++++++++++++++++ game-ai/ground/wto_ai_facing_common.das | 83 +++++++ game-ai/ground/wto_ai_fire_speed_common.das | 19 -- game-ai/ground/wto_ai_follow_common.das | 17 +- game-ai/ground/wto_ai_nav_common.das | 45 +++- .../ground/wto_ai_tactics_actions_common.das | 69 +++--- game-ai/ground/wto_ai_tactics_common.das | 209 ++++++++---------- game-ai/ground/wto_ai_types_common.das | 33 +++ .../patcher/src/ground-ai/ground-ai-config.ts | 68 ++++-- 16 files changed, 737 insertions(+), 269 deletions(-) create mode 100644 game-ai/ground/wto_ai_behavior_common.das create mode 100644 game-ai/ground/wto_ai_facing_common.das delete mode 100644 game-ai/ground/wto_ai_fire_speed_common.das diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index c86cb1a..d7ec166 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -529,12 +529,13 @@ "loadout": "Ground AI spawn ammunition", "commander": "Commander & role quotas", "macro": "Macro capture & SPAA", - "stateMachine": "Hull state machine & repair", + "stateMachine": "Hull actions & repair", "perception": "Visual perception & exposure", "tactics": "Situational awareness & memory", "estimation": "Lead estimation & aim bias", "threat": "Threat assessment", "turret": "Turret attention", + "behavior": "Hull behavior", "fireControl": "Fire control & fire gate", "navigation": "Driving & navigation", "navEngine": "Map navigation mesh & path costs", @@ -549,12 +550,13 @@ "loadout": "Ready-rack carry count and primary/secondary shell split", "commander": "Role percentages by game mode, flank lanes, rally and recall", "macro": "Opening split, cap occupancy, death zones and SPAA positioning", - "stateMachine": "Short halts, reload cover retreat, angling, repositioning and repair", + "stateMachine": "Short halts, reload cover retreat, repositioning and repair", "perception": "Foliage transparency, exposure accumulation and decay", "tactics": "Vision range, audio detection, radio sharing and target memory", "estimation": "Sample-based velocity lead, exit watch and natural shot spread", "threat": "How dangerous each discovered enemy is: distance, aim, line of sight and recent hits", "turret": "Where the turret looks without a target: threats, cues and scanning along the route", + "behavior": "Scores of the hull behaviors, commitment, facing the main threat and driving backwards", "fireControl": "Hit probability and fire threshold, autocannon bursts, secondary weapons, barrel settle and ballistic safety", "navigation": "Drive backend, pivot turns and tactical reverse", "navEngine": "Baked map navigation packs, their fallback, and path costs per surface for tracked and wheeled vehicles", @@ -617,17 +619,12 @@ "enemySpawnAvoidM": "Enemy spawn avoidance distance" }, "stateMachine": { - "preaimAngleDeg": "Moving pre-aim angle threshold", - "movingShotWaitSec": "Time to attempt a moving shot before halting", "shortHaltMaxSec": "Short halt max duration", "shortHaltCooldownSec": "Short halt cooldown", "turnLaunchSpeedMps": "Turn launch target speed", "coverMinDistM": "Cover search min distance", "coverMaxDistM": "Cover search max distance", "coverRetreatBudgetSec": "Reload cover retreat max duration", - "reloadAdvanceAngleDeg": "Reload zigzag advance angle", - "hullAngleTriggerDeg": "Hull angling trigger angle", - "hullAngleTargetDeg": "Target hull angling offset", "maxTotalHaltSec": "Max cumulative halt before reposition", "stalemateMissShots": "Ineffective shots before reposition", "stalemateNoShotHalts": "No-shot halts before reposition", @@ -687,15 +684,37 @@ "scanArcDeg": "Scan arc either side of the route", "scanPeriodSec": "Scan sweep period" }, + "behavior": { + "scoreIntervalSec": "Behavior scoring interval", + "minHoldSec": "Minimum time a behavior is kept", + "switchMargin": "Extra score needed to switch behavior", + "advanceScore": "Score: advance along the order route", + "engageScore": "Score: engage on the move", + "urgencyWeight": "Score shift by order urgency", + "haltScore": "Score: short halt for a shot", + "crossfirePenalty": "Short-halt penalty per extra enemy aiming at the bot", + "coverScore": "Score: pull back to cover to reload", + "coverDangerWeight": "Cover score added by threat danger", + "coverOffensivePenalty": "Cover penalty on an urgent attack", + "coverRetrySec": "Wait before searching for cover again after none was found", + "repositionScore": "Score: change firing position when the engagement is stuck", + "holdScore": "Score: hold the post, watch the last exit or wait at the rally point", + "disperseScore": "Score: spread out of a crowd", + "urgentSpeedKeep": "Share of march speed an urgent bot keeps when slowing for a shot", + "hullAngleDeg": "Hull angle to the main threat", + "faceToleranceDeg": "Facing tolerance while standing", + "faceMinDanger": "Threat danger needed to face it", + "faceHaltLimitDeg": "Facing error that turns the hull during a short halt", + "reverseTravelAngleDeg": "Threat angle off the travel direction for driving backwards", + "reverseMaxGoalDistM": "Drive backwards only toward a goal within", + "reverseMinSpeedMps": "Lowest top reverse speed for driving backwards", + "reverseHoldSec": "Minimum time between switching forwards and backwards" + }, "fireControl": { "maxEngageRangeM": "Max engagement range", "closeRangeM": "Close range band threshold", "midRangeM": "Mid range band threshold", "longRangeM": "Long range band threshold", - "midSlowSpeedRatio": "Mid-range fire-on-move speed ratio", - "midSlowMaxMps": "Mid-range fire-on-move speed cap", - "closeRangeMaxSpeedKmh": "Moving-fire speed cap at the close-range boundary", - "pointBlankMaxSpeedKmh": "Moving-fire speed cap at point blank", "stopSpeedMaxMps": "Stopped speed threshold", "longRangeWindowSec": "Long-range clear LOS window", "baseAlignDeg": "Base gun alignment tolerance", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index 223fc0f..cf6d61b 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -529,12 +529,13 @@ "loadout": "陆战 AI 出生携弹", "commander": "指挥层与分路配额", "macro": "宏观占点与防空", - "stateMachine": "单车状态机与掩体维修", + "stateMachine": "车体动作与掩体维修", "perception": "视觉感知与曝光", "tactics": "态势感知与目标记忆", "estimation": "目击测速与瞄准偏差", "threat": "威胁评估", "turret": "炮塔关注方向", + "behavior": "车体行为", "fireControl": "火控与开火许可", "navigation": "机动与寻路控制", "navEngine": "地图导航网格与通行代价", @@ -549,12 +550,13 @@ "loadout": "待发架携弹量与主/副弹种分配", "commander": "各模式进攻 / 侧翼 / 架枪比例、集结与回防", "macro": "开局分兵、占点人数、死亡区规避与防空站位", - "stateMachine": "短停预算、装填回缩、摆角、换位与受损维修", + "stateMachine": "短停预算、装填回缩、换位与受损维修", "perception": "植被透光、曝光累计速度与衰减", "tactics": "视距、听觉发现范围、电台共享与记忆时长", "estimation": "本车目击测速、守出口时长与自然散布", "threat": "每个已发现敌人的危险程度:距离、是否瞄着本车、视线与最近是否命中本车", "turret": "没有目标时炮塔看哪里:威胁、线索与沿路线扫视", + "behavior": "车体各行为的得分、承诺时间、车头对主威胁与倒车跟路", "fireControl": "命中概率与开火门槛、机炮点射、副武器、炮管稳定和弹道安全", "navigation": "驱动方式、原地转向与战术倒车", "navEngine": "离线地图导航包的启用与降级,以及履带 / 轮式车在各类地表上的寻路代价", @@ -617,17 +619,12 @@ "enemySpawnAvoidM": "敌方出生点规避距离" }, "stateMachine": { - "preaimAngleDeg": "行进预瞄角度阈值", - "movingShotWaitSec": "转入短停前尝试行进射击的时间", "shortHaltMaxSec": "单次短停最长时间", "shortHaltCooldownSec": "短停冷却时间", "turnLaunchSpeedMps": "甩弯起步目标车速", "coverMinDistM": "掩体搜索最小距离", "coverMaxDistM": "掩体搜索最大距离", "coverRetreatBudgetSec": "装填回缩掩体最长用时", - "reloadAdvanceAngleDeg": "装填折线跃进偏角", - "hullAngleTriggerDeg": "触发车体摆角阈值", - "hullAngleTargetDeg": "车体目标摆角", "maxTotalHaltSec": "累计停留强制换位上限", "stalemateMissShots": "无伤害连射触发换位发数", "stalemateNoShotHalts": "未开火短停触发换位次数", @@ -687,15 +684,37 @@ "scanArcDeg": "沿路线向两侧扫视的角度", "scanPeriodSec": "扫视一个来回的时长" }, + "behavior": { + "scoreIntervalSec": "行为打分间隔", + "minHoldSec": "行为最短保持时间", + "switchMargin": "切换行为所需高出的分数", + "advanceScore": "得分:沿任务路线推进", + "engageScore": "得分:交战推进", + "urgencyWeight": "任务紧迫度对得分的影响", + "haltScore": "得分:短停射击", + "crossfirePenalty": "每多一个瞄着本车的敌人,短停扣分", + "coverScore": "得分:退入掩体装填", + "coverDangerWeight": "威胁危险度对掩体得分的加成", + "coverOffensivePenalty": "紧急进攻时掩体扣分", + "coverRetrySec": "找不到掩体后再次搜索的间隔", + "repositionScore": "得分:交战僵持时换位", + "holdScore": "得分:守位、盯出口或在集结点等待", + "disperseScore": "得分:拥挤疏散", + "urgentSpeedKeep": "紧急任务为射击减速时保留的行军速度比例", + "hullAngleDeg": "车头对主威胁的倾角", + "faceToleranceDeg": "停车时朝向容差", + "faceMinDanger": "需要车头对准的威胁危险度下限", + "faceHaltLimitDeg": "短停时朝向偏差超过多少才转车体", + "reverseTravelAngleDeg": "威胁偏离行进方向多少度时倒车跟路", + "reverseMaxGoalDistM": "仅在离目的地这么近时倒车跟路", + "reverseMinSpeedMps": "倒车跟路所需的最低倒车极速", + "reverseHoldSec": "前进与倒车切换的最短间隔" + }, "fireControl": { "maxEngageRangeM": "最大交战开火距离", "closeRangeM": "近距交战分界距离", "midRangeM": "中距交战分界距离", "longRangeM": "远距交战分界距离", - "midSlowSpeedRatio": "中距行进射击最高车速比", - "midSlowMaxMps": "中距行进射击最高车速", - "closeRangeMaxSpeedKmh": "近距分界处行进射击最高车速", - "pointBlankMaxSpeedKmh": "贴身时行进射击最高车速", "stopSpeedMaxMps": "停稳判定最高车速", "longRangeWindowSec": "远距连续射界观察窗", "baseAlignDeg": "主炮对准允许角误差", diff --git a/apps/launcher/src/renderer/src/pages/tuning/BotTuningPanel.tsx b/apps/launcher/src/renderer/src/pages/tuning/BotTuningPanel.tsx index 07e8ebb..62ede43 100644 --- a/apps/launcher/src/renderer/src/pages/tuning/BotTuningPanel.tsx +++ b/apps/launcher/src/renderer/src/pages/tuning/BotTuningPanel.tsx @@ -54,7 +54,7 @@ function hasValidCrossFieldRules(effective: GroundAiTuningValues, patch: TuningP if (est.watchMaxSec < est.watchMinSec || est.velStableSpanSec <= est.velSampleMinSpanSec) return false; const fc = mergeSection(effective.fireControl, patch.fireControl); if (fc.midRangeM <= fc.closeRangeM || fc.longRangeM <= fc.midRangeM) return false; - return fc.minFireThreshold <= fc.fireThreshold && fc.pointBlankMaxSpeedKmh >= fc.closeRangeMaxSpeedKmh; + return fc.minFireThreshold <= fc.fireThreshold; } export function BotTuningPanel({ data, saving, onSave }: Props) { diff --git a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts index b9972a9..56428c6 100644 --- a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts +++ b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts @@ -158,17 +158,12 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ defaultOpen: false, customOnly: true, fields: [ - num('stateMachine', 'preaimAngleDeg', 1, 30, '°'), - num('stateMachine', 'movingShotWaitSec', 0.25, 5, 's'), num('stateMachine', 'shortHaltMaxSec', 0.5, 12, 's'), num('stateMachine', 'shortHaltCooldownSec', 0.5, 20, 's'), num('stateMachine', 'turnLaunchSpeedMps', 0.5, 6, 'm/s'), num('stateMachine', 'coverMinDistM', 2, 30, 'm'), num('stateMachine', 'coverMaxDistM', 6, 80, 'm'), num('stateMachine', 'coverRetreatBudgetSec', 1.5, 20, 's'), - num('stateMachine', 'reloadAdvanceAngleDeg', 0, 45, '°'), - num('stateMachine', 'hullAngleTriggerDeg', 15, 75, '°'), - num('stateMachine', 'hullAngleTargetDeg', 0, 35, '°'), num('stateMachine', 'maxTotalHaltSec', 3, 40, 's'), int('stateMachine', 'stalemateMissShots', 1, 8), int('stateMachine', 'stalemateNoShotHalts', 1, 6), @@ -254,6 +249,37 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ num('turret', 'scanPeriodSec', 1, 30, 's'), ], }, + { + id: 'behavior', + defaultOpen: false, + customOnly: true, + fields: [ + num('behavior', 'scoreIntervalSec', 0.1, 3, 's'), + num('behavior', 'minHoldSec', 0, 10, 's'), + num('behavior', 'switchMargin', 0, 1), + num('behavior', 'advanceScore', 0, 1), + num('behavior', 'engageScore', 0, 1), + num('behavior', 'urgencyWeight', 0, 1), + num('behavior', 'haltScore', 0, 1), + num('behavior', 'crossfirePenalty', 0, 1), + num('behavior', 'coverScore', 0, 1), + num('behavior', 'coverDangerWeight', 0, 1), + num('behavior', 'coverOffensivePenalty', 0, 1), + num('behavior', 'coverRetrySec', 0.5, 30, 's'), + num('behavior', 'repositionScore', 0, 1), + num('behavior', 'holdScore', 0, 1), + num('behavior', 'disperseScore', 0, 1), + num('behavior', 'urgentSpeedKeep', 0, 1), + num('behavior', 'hullAngleDeg', 0, 45, '°'), + num('behavior', 'faceToleranceDeg', 3, 60, '°'), + num('behavior', 'faceMinDanger', 0, 2), + num('behavior', 'faceHaltLimitDeg', 10, 180, '°'), + num('behavior', 'reverseTravelAngleDeg', 60, 180, '°'), + num('behavior', 'reverseMaxGoalDistM', 0, 2000, 'm'), + num('behavior', 'reverseMinSpeedMps', 0.5, 10, 'm/s'), + num('behavior', 'reverseHoldSec', 0, 20, 's'), + ], + }, { id: 'fireControl', defaultOpen: false, @@ -263,10 +289,6 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ num('fireControl', 'closeRangeM', 30, 250, 'm'), num('fireControl', 'midRangeM', 100, 600, 'm'), num('fireControl', 'longRangeM', 300, 1500, 'm'), - num('fireControl', 'midSlowSpeedRatio', 0.1, 1), - num('fireControl', 'midSlowMaxMps', 1, 15, 'm/s'), - num('fireControl', 'closeRangeMaxSpeedKmh', 3.6, 100, 'km/h'), - num('fireControl', 'pointBlankMaxSpeedKmh', 3.6, 100, 'km/h'), num('fireControl', 'stopSpeedMaxMps', 0.1, 2, 'm/s'), num('fireControl', 'longRangeWindowSec', 1, 15, 's'), num('fireControl', 'baseAlignDeg', 0.1, 3, '°'), diff --git a/apps/launcher/src/shared/schemas/tuning.ts b/apps/launcher/src/shared/schemas/tuning.ts index 840ac19..d1caa79 100644 --- a/apps/launcher/src/shared/schemas/tuning.ts +++ b/apps/launcher/src/shared/schemas/tuning.ts @@ -188,17 +188,12 @@ const GroundAiPerceptionSchema = z.object({ }); const GroundAiStateMachineSchema = z.object({ - preaimAngleDeg: z.number().min(1).max(30), - movingShotWaitSec: z.number().min(0.25).max(5), shortHaltMaxSec: z.number().min(0.5).max(12), shortHaltCooldownSec: z.number().min(0.5).max(20), turnLaunchSpeedMps: z.number().min(0.5).max(6), coverMinDistM: z.number().min(2).max(30), coverMaxDistM: z.number().min(6).max(80), coverRetreatBudgetSec: z.number().min(1.5).max(20), - reloadAdvanceAngleDeg: z.number().min(0).max(45), - hullAngleTriggerDeg: z.number().min(15).max(75), - hullAngleTargetDeg: z.number().min(0).max(35), maxTotalHaltSec: z.number().min(3).max(40), stalemateMissShots: z.number().int().min(1).max(8), stalemateNoShotHalts: z.number().int().min(1).max(6), @@ -234,6 +229,33 @@ const GroundAiTurretSchema = z.object({ scanPeriodSec: z.number().min(1).max(30), }); +const GroundAiBehaviorSchema = z.object({ + scoreIntervalSec: z.number().min(0.1).max(3), + minHoldSec: z.number().min(0).max(10), + switchMargin: z.number().min(0).max(1), + advanceScore: z.number().min(0).max(1), + engageScore: z.number().min(0).max(1), + urgencyWeight: z.number().min(0).max(1), + haltScore: z.number().min(0).max(1), + crossfirePenalty: z.number().min(0).max(1), + coverScore: z.number().min(0).max(1), + coverDangerWeight: z.number().min(0).max(1), + coverOffensivePenalty: z.number().min(0).max(1), + coverRetrySec: z.number().min(0.5).max(30), + repositionScore: z.number().min(0).max(1), + holdScore: z.number().min(0).max(1), + disperseScore: z.number().min(0).max(1), + urgentSpeedKeep: z.number().min(0).max(1), + hullAngleDeg: z.number().min(0).max(45), + faceToleranceDeg: z.number().min(3).max(60), + faceMinDanger: z.number().min(0).max(2), + faceHaltLimitDeg: z.number().min(10).max(180), + reverseTravelAngleDeg: z.number().min(60).max(180), + reverseMaxGoalDistM: z.number().min(0).max(2000), + reverseMinSpeedMps: z.number().min(0.5).max(10), + reverseHoldSec: z.number().min(0).max(20), +}); + const GroundAiEstimationSchema = z.object({ watchMinSec: z.number().min(0.5).max(10), watchMaxSec: z.number().min(1).max(15), @@ -250,10 +272,6 @@ const GroundAiFireControlSchema = z.object({ closeRangeM: z.number().min(30).max(250), midRangeM: z.number().min(100).max(600), longRangeM: z.number().min(300).max(1500), - midSlowSpeedRatio: z.number().min(0.1).max(1), - midSlowMaxMps: z.number().min(1).max(15), - closeRangeMaxSpeedKmh: z.number().min(3.6).max(100), - pointBlankMaxSpeedKmh: z.number().min(3.6).max(100), stopSpeedMaxMps: z.number().min(0.1).max(2), longRangeWindowSec: z.number().min(1).max(15), baseAlignDeg: z.number().min(0.1).max(3), @@ -320,6 +338,7 @@ export const GroundAiTuningSchema = z.object({ estimation: GroundAiEstimationSchema, threat: GroundAiThreatSchema, turret: GroundAiTurretSchema, + behavior: GroundAiBehaviorSchema, fireControl: GroundAiFireControlSchema, diagnostics: GroundAiDiagnosticsSchema, }); @@ -344,6 +363,7 @@ export const GroundAiTuningPatchSchema = z.object({ estimation: GroundAiEstimationSchema.partial().optional(), threat: GroundAiThreatSchema.partial().optional(), turret: GroundAiTurretSchema.partial().optional(), + behavior: GroundAiBehaviorSchema.partial().optional(), fireControl: GroundAiFireControlSchema.partial().optional(), diagnostics: GroundAiDiagnosticsSchema.partial().optional(), }); diff --git a/apps/server/src/tuning/ground-ai-tuning.ts b/apps/server/src/tuning/ground-ai-tuning.ts index bec0b8b..411391b 100644 --- a/apps/server/src/tuning/ground-ai-tuning.ts +++ b/apps/server/src/tuning/ground-ai-tuning.ts @@ -59,6 +59,7 @@ export function readGroundAiTuning(reader: TuningReader): GroundAiTuning { estimation: readEstimationSection(reader.object('estimation')), threat: readThreatSection(reader.object('threat')), turret: readTurretSection(reader.object('turret')), + behavior: readBehaviorSection(reader.object('behavior')), fireControl: readFireControlSection(reader.object('fireControl')), diagnostics: { telemetry: diag.bool('telemetry'), @@ -325,17 +326,12 @@ function readStateMachineSection(sm: TuningReader): GroundAiTuning['stateMachine throw new TuningError('tuning file ground-ai.jsonc: stateMachine.coverMaxDistM must be > coverMinDistM'); } return { - preaimAngleDeg: sm.number('preaimAngleDeg', { min: 1.0, max: 30.0 }), - movingShotWaitSec: sm.number('movingShotWaitSec', { min: 0.25, max: 5.0 }), shortHaltMaxSec: sm.number('shortHaltMaxSec', { min: 0.5, max: 12.0 }), shortHaltCooldownSec: sm.number('shortHaltCooldownSec', { min: 0.5, max: 20.0 }), turnLaunchSpeedMps: sm.number('turnLaunchSpeedMps', { min: 0.5, max: 6.0 }), coverMinDistM, coverMaxDistM, coverRetreatBudgetSec: sm.number('coverRetreatBudgetSec', { min: 1.5, max: 20.0 }), - reloadAdvanceAngleDeg: sm.number('reloadAdvanceAngleDeg', { min: 0.0, max: 45.0 }), - hullAngleTriggerDeg: sm.number('hullAngleTriggerDeg', { min: 15.0, max: 75.0 }), - hullAngleTargetDeg: sm.number('hullAngleTargetDeg', { min: 0.0, max: 35.0 }), maxTotalHaltSec: sm.number('maxTotalHaltSec', { min: 3.0, max: 40.0 }), stalemateMissShots: sm.int('stalemateMissShots', { min: 1, max: 8 }), stalemateNoShotHalts: sm.int('stalemateNoShotHalts', { min: 1, max: 6 }), @@ -378,6 +374,35 @@ function readTurretSection(turret: TuningReader): GroundAiTuning['turret'] { }; } +function readBehaviorSection(bhv: TuningReader): GroundAiTuning['behavior'] { + return { + scoreIntervalSec: bhv.number('scoreIntervalSec', { min: 0.1, max: 3 }), + minHoldSec: bhv.number('minHoldSec', { min: 0, max: 10 }), + switchMargin: bhv.number('switchMargin', { min: 0, max: 1 }), + advanceScore: bhv.number('advanceScore', { min: 0, max: 1 }), + engageScore: bhv.number('engageScore', { min: 0, max: 1 }), + urgencyWeight: bhv.number('urgencyWeight', { min: 0, max: 1 }), + haltScore: bhv.number('haltScore', { min: 0, max: 1 }), + crossfirePenalty: bhv.number('crossfirePenalty', { min: 0, max: 1 }), + coverScore: bhv.number('coverScore', { min: 0, max: 1 }), + coverDangerWeight: bhv.number('coverDangerWeight', { min: 0, max: 1 }), + coverOffensivePenalty: bhv.number('coverOffensivePenalty', { min: 0, max: 1 }), + coverRetrySec: bhv.number('coverRetrySec', { min: 0.5, max: 30 }), + repositionScore: bhv.number('repositionScore', { min: 0, max: 1 }), + holdScore: bhv.number('holdScore', { min: 0, max: 1 }), + disperseScore: bhv.number('disperseScore', { min: 0, max: 1 }), + urgentSpeedKeep: bhv.number('urgentSpeedKeep', { min: 0, max: 1 }), + hullAngleDeg: bhv.number('hullAngleDeg', { min: 0, max: 45 }), + faceToleranceDeg: bhv.number('faceToleranceDeg', { min: 3, max: 60 }), + faceMinDanger: bhv.number('faceMinDanger', { min: 0, max: 2 }), + faceHaltLimitDeg: bhv.number('faceHaltLimitDeg', { min: 10, max: 180 }), + reverseTravelAngleDeg: bhv.number('reverseTravelAngleDeg', { min: 60, max: 180 }), + reverseMaxGoalDistM: bhv.number('reverseMaxGoalDistM', { min: 0, max: 2000 }), + reverseMinSpeedMps: bhv.number('reverseMinSpeedMps', { min: 0.5, max: 10 }), + reverseHoldSec: bhv.number('reverseHoldSec', { min: 0, max: 20 }), + }; +} + function readEstimationSection(est: TuningReader): GroundAiTuning['estimation'] { const watchMinSec = est.number('watchMinSec', { min: 0.5, max: 10.0 }); const watchMaxSec = est.number('watchMaxSec', { min: 1.0, max: 15.0 }); @@ -408,11 +433,6 @@ function readFireControlSection(fc: TuningReader): GroundAiTuning['fireControl'] if (midRangeM <= closeRangeM || longRangeM <= midRangeM) { throw new TuningError('tuning file ground-ai.jsonc: fireControl ranges must satisfy closeRangeM < midRangeM < longRangeM'); } - const closeRangeMaxSpeedKmh = fc.number('closeRangeMaxSpeedKmh', { min: 3.6, max: 100 }); - const pointBlankMaxSpeedKmh = fc.number('pointBlankMaxSpeedKmh', { min: 3.6, max: 100 }); - if (pointBlankMaxSpeedKmh < closeRangeMaxSpeedKmh) { - throw new TuningError('tuning file ground-ai.jsonc: fireControl.pointBlankMaxSpeedKmh must be >= closeRangeMaxSpeedKmh'); - } const fireThreshold = fc.number('fireThreshold', { min: 0.05, max: 0.95 }); const minFireThreshold = fc.number('minFireThreshold', { min: 0.01, max: 0.9 }); if (minFireThreshold > fireThreshold) { @@ -423,10 +443,6 @@ function readFireControlSection(fc: TuningReader): GroundAiTuning['fireControl'] closeRangeM, midRangeM, longRangeM, - midSlowSpeedRatio: fc.number('midSlowSpeedRatio', { min: 0.1, max: 1.0 }), - midSlowMaxMps: fc.number('midSlowMaxMps', { min: 1.0, max: 15.0 }), - closeRangeMaxSpeedKmh, - pointBlankMaxSpeedKmh, stopSpeedMaxMps: fc.number('stopSpeedMaxMps', { min: 0.1, max: 2.0 }), longRangeWindowSec: fc.number('longRangeWindowSec', { min: 1.0, max: 15.0 }), baseAlignDeg: fc.number('baseAlignDeg', { min: 0.1, max: 3.0 }), diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index 55aec83..7e498e9 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -282,20 +282,14 @@ "discoverScore": 0.35 }, - // Per-bot hull state machine timings and thresholds (offline values). + // Timings and thresholds of the hull actions (short halt, cover pull-back, reposition, repair). "stateMachine": { - "preaimAngleDeg": 8.0, - // Time a ready gun can be held up by speed or aim before attempting a short halt. - "movingShotWaitSec": 1.0, "shortHaltMaxSec": 3.0, "shortHaltCooldownSec": 4.0, "turnLaunchSpeedMps": 2.1, "coverMinDistM": 6.0, "coverMaxDistM": 24.0, "coverRetreatBudgetSec": 6.0, - "reloadAdvanceAngleDeg": 18.0, - "hullAngleTriggerDeg": 20.0, - "hullAngleTargetDeg": 10.0, "maxTotalHaltSec": 12.0, "stalemateMissShots": 2, "stalemateNoShotHalts": 2, @@ -352,6 +346,48 @@ "scanPeriodSec": 6.0 }, + // Hull channel (decision layer design, section 7). Every scoreIntervalSec (at once when a target + // appears or is lost, a reload starts or ends, or the bot is hit) each behavior gets a score and + // the best runs; a running one is kept for minHoldSec, then until another scores switchMargin + // more. Scores: advance (no target in sight), engage (target in sight; +urgencyWeight when the + // order is urgent), halt (the trigger asks to stand for its shot; +urgencyWeight when not urgent, + // -crossfirePenalty per extra enemy aiming at the bot), cover (reloading with a known threat; + // +coverDangerWeight x danger, -coverOffensivePenalty on an urgent attack, not again for + // coverRetrySec after no cover was found), reposition (engagement stuck), hold (at the post, + // watching the last exit, waiting at the rally point) and disperse (crowded). Engaging on the + // move slows to the speed the trigger asks for; an urgent order keeps urgentSpeedKeep of the + // march speed. Medium and heavy tanks and tank destroyers face the most dangerous threat (danger + // at least faceMinDanger) angled by hullAngleDeg: holding within faceToleranceDeg, on a short halt + // only when more than faceHaltLimitDeg off. With that threat more than reverseTravelAngleDeg off + // the direction of travel and the goal within reverseMaxGoalDistM, a vehicle reversing at least + // reverseMinSpeedMps drives its route backwards; it switches at most every reverseHoldSec. + "behavior": { + "scoreIntervalSec": 0.5, + "minHoldSec": 1.5, + "switchMargin": 0.15, + "advanceScore": 0.5, + "engageScore": 0.55, + "urgencyWeight": 0.15, + "haltScore": 0.55, + "crossfirePenalty": 0.15, + "coverScore": 0.45, + "coverDangerWeight": 0.25, + "coverOffensivePenalty": 0.2, + "coverRetrySec": 4.0, + "repositionScore": 0.7, + "holdScore": 0.6, + "disperseScore": 0.62, + "urgentSpeedKeep": 0.5, + "hullAngleDeg": 20.0, + "faceToleranceDeg": 15.0, + "faceMinDanger": 0.15, + "faceHaltLimitDeg": 60.0, + "reverseTravelAngleDeg": 110.0, + "reverseMaxGoalDistM": 200.0, + "reverseMinSpeedMps": 2.5, + "reverseHoldSec": 3.0 + }, + // Fire permission (decision layer design, section 6). A main-gun shot needs its estimated hit // probability to reach the fire threshold. The hit probability compares the visible part of the // target (its projected width, targetHalfHeightM high, shrunk when only part of it is visible) @@ -369,10 +405,6 @@ "closeRangeM": 100.0, "midRangeM": 300.0, "longRangeM": 800.0, - "midSlowSpeedRatio": 0.45, - "midSlowMaxMps": 5.5, - "closeRangeMaxSpeedKmh": 30.0, - "pointBlankMaxSpeedKmh": 35.0, // At or below this speed the bot counts as standing (also the answer "stop" to a speed request). "stopSpeedMaxMps": 0.45, "longRangeWindowSec": 4.0, diff --git a/game-ai/ground/wto_ai_behavior_common.das b/game-ai/ground/wto_ai_behavior_common.das new file mode 100644 index 0000000..a145a57 --- /dev/null +++ b/game-ai/ground/wto_ai_behavior_common.das @@ -0,0 +1,203 @@ +// Hull channel behavior choice (decision layer design, 7.2): every behavior gets a 0-1 score from +// the order, the threat table, the bot's own state and the other channels' requests; the best one +// runs. A chosen behavior is kept for at least behavior.minHoldSec and afterwards until another +// scores behavior.switchMargin higher, unless it ends by itself or can no longer run. Scoring +// happens every behavior.scoreIntervalSec and at once when a target comes into sight or is lost, +// a reload starts or ends, or the bot is hit (a hit also lifts the minimum hold). +options indenting = 2 +options no_global_heap = true +module wto_ai_behavior_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_order_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common + +// What one tactics tick knows, built once (wto_ai_tactics_common.das) and read by the scores and +// the behaviors. threatPos: the most dangerous known threat, else the remembered target, else the +// order goal. haltWanted: the trigger channel asks to stand for its shot. +[safe_when_uninitialized] +struct public WtoBhvCtx + hasTarget : bool = false + distTarget : float = 9999.0 + remembered : bool = false + threatPos : float3 = float3(0.0, 0.0, 0.0) + threatDir : float3 = float3(1.0, 0.0, 0.0) + topDanger : float = 0.0 + aimingCount : int = 0 + baseGoal : float3 = float3(0.0, 0.0, 0.0) + distGoal : float = 0.0 + atGoal : bool = false + urgent : bool = false + offensive : bool = false + haltWanted : bool = false + stopRangeOk : bool = false + stale : bool = false + crowded : bool = false + holdReason : int = 0 + +// Why HOLD applies (holdReason): at the order's post, watching where the target vanished, or +// waiting at the rally point for the group. +let public WTO_HOLD_NONE = 0 +let public WTO_HOLD_POST = 1 +let public WTO_HOLD_WATCH = 2 +let public WTO_HOLD_RALLY = 3 + +// The order allows standing for a shot at this distance (beyond longRangeM only after a long +// enough clear look at a target showing at least two sample points). +def private wto_bhv_stop_range_ok(distXZ : float; slot : WtoBotSlot const&) : bool + let maxStop = slot.order.valid ? slot.order.maxStopRangeM : WTO_AI_FC_MAX_RANGE_M + if distXZ > min(maxStop, WTO_AI_FC_MAX_RANGE_M) + return false + return (distXZ <= WTO_AI_FC_LONG_RANGE_M || + (slot.perceive.goodLosSec >= WTO_AI_FC_LONG_WINDOW_SEC && slot.perceive.visiblePointCount >= 2)) + +def private wto_bhv_hold_reason(now : float; myPos : float3; c : WtoBhvCtx const&; slot : WtoBotSlot const&) : int + if c.atGoal + return WTO_HOLD_POST + // A defending or watching bot near its post keeps watching the target's last exit for a while. + if !c.hasTarget && now < slot.perceive.watchUntil && slot.order.urgency != WTO_URGENCY_HIGH && c.distGoal <= 35.0 + return WTO_HOLD_WATCH + // Wait at the rally point until the group sets off, unless a target is in sight within midRangeM. + if slot.order.rallyHold && slot.order.routeRelayValid && c.distTarget > WTO_AI_FC_MID_RANGE_M + let rallyHoldRad = max(18.0, WTO_AI_CMD_RALLY_RADIUS_M * 0.55) + if wto_xz_dist_sq(myPos, slot.order.routeRelayPos) <= rallyHoldRad * rallyHoldRad + return WTO_HOLD_RALLY + return WTO_HOLD_NONE + +// Builds the tick's context. `stale` comes from the action layer (engagement stuck). +[never_inline] +def public wto_bhv_context(world : WtoWorldSnap const&; now : float; myPos, hullFwd : float3; stale : bool; + slot : WtoBotSlot const&; var c : WtoBhvCtx&) + assume p = slot.perceive + c.baseGoal = slot.order.valid ? slot.order.goalPos : world.battleCenter + c.distGoal = sqrt(wto_xz_dist_sq(myPos, c.baseGoal)) + c.atGoal = c.distGoal <= 8.0 + c.hasTarget = p.hasClearLos && !!p.targetEid && !p.targetIsAir + c.distTarget = c.hasTarget ? sqrt(wto_xz_dist_sq(myPos, p.knownPos)) : 9999.0 + c.remembered = !!p.targetEid && (now - p.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC + c.threatPos = c.remembered ? p.knownPos : c.baseGoal + let top = slot.threat.topIdx + if top >= 0 + c.threatPos = slot.threat.entries[top].pos + c.topDanger = slot.threat.entries[top].danger + c.threatDir = wto_xz_normalize(c.threatPos - myPos, hullFwd) + for i in range(slot.threat.count) + if slot.threat.entries[i].aiming && slot.threat.entries[i].seesMe + c.aimingCount++ + c.urgent = slot.order.urgency == WTO_URGENCY_HIGH || c.distGoal > 130.0 + c.offensive = wto_order_is_offensive(slot.order.role) + assume tr = slot.trigger + c.haltWanted = (now - tr.wantSpeedAt) <= WTO_AI_TACTICS_TICK_SEC * 3.0 && tr.wantSpeedMps <= WTO_AI_FC_STOP_SPEED_MAX_MPS + c.stopRangeOk = c.hasTarget && wto_bhv_stop_range_ok(c.distTarget, slot) + c.stale = stale + c.crowded = slot.crowd.isCrowded + c.holdReason = wto_bhv_hold_reason(now, myPos, c, slot) + +def private wto_bhv_name(bhv : int) : string + if bhv == WTO_BHV_ADVANCE + return "advance" + if bhv == WTO_BHV_ENGAGE + return "engage" + if bhv == WTO_BHV_HALT + return "halt" + if bhv == WTO_BHV_COVER + return "cover" + if bhv == WTO_BHV_REPOSITION + return "reposition" + if bhv == WTO_BHV_HOLD + return "hold" + if bhv == WTO_BHV_DISPERSE + return "disperse" + if bhv == WTO_BHV_WITHDRAW + return "withdraw" + return "repair" + +[never_inline] +def private wto_bhv_scores(now : float; c : WtoBhvCtx const&; slot : WtoBotSlot const&; var s : float[9]&) + for i in range(WTO_BHV_COUNT) + s[i] = 0.0 + let urgentF = c.urgent ? 1.0 : 0.0 + if !c.atGoal + s[WTO_BHV_ADVANCE] = c.hasTarget ? 0.0 : WTO_AI_BHV_ADVANCE + s[WTO_BHV_ENGAGE] = c.hasTarget ? (WTO_AI_BHV_ENGAGE + WTO_AI_BHV_URGENCY_W * urgentF) : 0.0 + if c.hasTarget && c.haltWanted && c.stopRangeOk && !c.atGoal && now >= slot.tactics.shortHaltCooldownUntil + let crossfire = float(max(0, c.aimingCount - 1)) + s[WTO_BHV_HALT] = WTO_AI_BHV_HALT + WTO_AI_BHV_URGENCY_W * (1.0 - urgentF) - WTO_AI_BHV_CROSSFIRE * crossfire + let coverRetry = now - slot.tactics.coverFailedAt >= WTO_AI_BHV_COVER_RETRY_SEC + if slot.fire.reloading && (c.hasTarget || c.remembered) && !slot.spec.isAutocannonBelt && coverRetry + let pushing = c.offensive && c.urgent ? 1.0 : 0.0 + s[WTO_BHV_COVER] = WTO_AI_BHV_COVER + WTO_AI_BHV_COVER_DANGER_W * min(1.0, c.topDanger) - WTO_AI_BHV_COVER_OFFENSIVE * pushing + if c.stale || slot.tactics.repositionActive + s[WTO_BHV_REPOSITION] = WTO_AI_BHV_REPOSITION + if c.holdReason != WTO_HOLD_NONE + s[WTO_BHV_HOLD] = WTO_AI_BHV_HOLD + if (c.crowded || now < slot.tactics.disperseUntil) && c.distTarget > WTO_AI_FC_CLOSE_RANGE_M + s[WTO_BHV_DISPERSE] = WTO_AI_BHV_DISPERSE + +def private wto_bhv_best(s : float[9] const&; skip : int; var bestScore, secondScore : float&; var second : int&) : int + var best = WTO_BHV_ADVANCE + bestScore = -1.0 + secondScore = -1.0 + second = -1 + for i in range(WTO_BHV_COUNT) + if i == skip + continue + if s[i] > bestScore + secondScore = bestScore + second = best + bestScore = s[i] + best = i + elif s[i] > secondScore + secondScore = s[i] + second = i + return best + +// Scores now if due (or `force`, after the running behavior ended itself: it is then left out), +// and switches when the commitment allows it. +[never_inline] +def public wto_bhv_choose(now : float; c : WtoBhvCtx const&; force : bool; var slot : WtoBotSlot&) + assume tac = slot.tactics + let hit = slot.perceive.lastDamagedAt > tac.scoredDamageAt + let due = (force || hit || now >= tac.nextScoreAt || c.hasTarget != tac.scoredHasTarget || + slot.fire.reloading != tac.scoredReloading) + if !due + return + tac.nextScoreAt = now + WTO_AI_BHV_SCORE_SEC + tac.scoredHasTarget = c.hasTarget + tac.scoredReloading = slot.fire.reloading + tac.scoredDamageAt = slot.perceive.lastDamagedAt + var s : float[9] + wto_bhv_scores(now, c, slot, s) + var bestScore = 0.0 + var secondScore = 0.0 + var second = -1 + let best = wto_bhv_best(s, force ? tac.behavior : -1, bestScore, secondScore, second) + let cur = tac.behavior + let curScore = (cur >= 0 && cur < WTO_BHV_COUNT) ? s[cur] : 0.0 + tac.behaviorScore = curScore + if best == cur || bestScore <= 0.0 + return + let held = (now - tac.behaviorSince) < WTO_AI_BHV_MIN_HOLD_SEC && !hit + if !force && curScore > 0.0 && (held || bestScore < curScore + WTO_AI_BHV_SWITCH_MARGIN) + return + if WTO_AI_DIAG_TELEMETRY + let secondName = second >= 0 ? wto_bhv_name(second) : "-" + print("WTO_AI|BEHAVIOR|t={now}|eid={uint(slot.eid)}|from={wto_bhv_name(cur)}|to={wto_bhv_name(best)}|score={bestScore}|cur={curScore}|second={secondName}:{secondScore}|force={force}\n") + tac.behavior = best + tac.behaviorScore = bestScore + tac.behaviorSince = now + +// A behavior that is not scored (repair, ridge withdrawal) took over this tick. +def public wto_bhv_take_over(now : float; bhv : int; var slot : WtoBotSlot&) + assume tac = slot.tactics + if tac.behavior != bhv + if WTO_AI_DIAG_TELEMETRY + print("WTO_AI|BEHAVIOR|t={now}|eid={uint(slot.eid)}|from={wto_bhv_name(tac.behavior)}|to={wto_bhv_name(bhv)}|score=1|cur=0|second=-:0|force=true\n") + tac.behavior = bhv + tac.behaviorSince = now + tac.behaviorScore = 1.0 + tac.nextScoreAt = now diff --git a/game-ai/ground/wto_ai_facing_common.das b/game-ai/ground/wto_ai_facing_common.das new file mode 100644 index 0000000..95f34ab --- /dev/null +++ b/game-ai/ground/wto_ai_facing_common.das @@ -0,0 +1,83 @@ +// Facing constraint of the hull channel (decision layer design, 7.3). Until penetration can be +// estimated, medium tanks, heavy tanks and tank destroyers turn the front toward the most dangerous +// known threat, angled by behavior.hullAngleDeg to the side nearer the current heading; light +// vehicles and SPAA are not bound. A target outside the gun's traverse overrides this for every +// vehicle (the hull turns the gun onto it). While advancing toward a nearby goal with the threat +// behind the direction of travel, the bot drives the route backwards instead of showing its rear. +options indenting = 2 +options no_global_heap = true +module wto_ai_facing_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_nav_types_common + +def private wto_face_bound_role(role : int) : bool + return role == WTO_ROLE_MEDIUM || role == WTO_ROLE_HEAVY || role == WTO_ROLE_TD + +def private wto_face_rotate(dir : float3; rad : float) : float3 + return float3(dir.x * cos(rad) - dir.z * sin(rad), 0.0, dir.x * sin(rad) + dir.z * cos(rad)) + +// `toThreat` turned by hullAngleDeg toward whichever side is nearer the current hull heading. +def private wto_face_angled(toThreat, hullFwd : float3) : float3 + let rad = WTO_AI_BHV_HULL_ANGLE_DEG * WTO_DEG_TO_RAD + let a = wto_face_rotate(toThreat, rad) + let b = wto_face_rotate(toThreat, -rad) + return dot(a, hullFwd) >= dot(b, hullFwd) ? a : b + +// Where the threat to face is: the most dangerous entry of the threat table above +// behavior.faceMinDanger, else the engaged target while remembered. +def private wto_face_threat_pos(now : float; slot : WtoBotSlot const&; var outPos : float3&) : bool + let top = slot.threat.topIdx + if top >= 0 && slot.threat.entries[top].danger >= WTO_AI_BHV_FACE_MIN_DANGER + outPos = slot.threat.entries[top].pos + return true + assume p = slot.perceive + if !!p.targetEid && !p.targetIsAir && (now - p.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC + outPos = p.knownPos + return true + return false + +// Per tactics tick, before the behaviors run. +[never_inline] +def public wto_face_update(now : float; myPos, hullFwd : float3; var slot : WtoBotSlot&) + assume tac = slot.tactics + tac.faceActive = false + tac.faceFromThreat = false + if !!slot.fire.hullAimTarget && slot.fire.hullAimTarget == slot.perceive.targetEid + tac.faceDir = wto_xz_normalize(slot.fire.hullAimDir, hullFwd) + tac.faceActive = true + return + var threatPos = myPos + if !wto_face_bound_role(slot.spec.role) || !wto_face_threat_pos(now, slot, threatPos) + return + tac.faceThreatDir = wto_xz_normalize(threatPos - myPos, hullFwd) + tac.faceDir = wto_face_angled(tac.faceThreatDir, hullFwd) + tac.faceActive = true + tac.faceFromThreat = true + +// Whether to drive the route backwards this tick (advancing or engaging toward a goal within +// behavior.reverseMaxGoalDistM with the faced threat more than reverseTravelAngleDeg off the +// direction of travel). A decision is kept for at least behavior.reverseHoldSec. +[never_inline] +def public wto_face_reverse_update(now, distGoal : float; var slot : WtoBotSlot&) + assume tac = slot.tactics + let moving = tac.behavior == WTO_BHV_ADVANCE || tac.behavior == WTO_BHV_ENGAGE + let able = slot.spec.vMaxRev >= WTO_AI_BHV_REVERSE_MIN_MPS && !slot.tactics.immobilized + var want = moving && able && tac.faceFromThreat && distGoal <= WTO_AI_BHV_REVERSE_MAX_GOAL_M + if want + let travel = wto_xz_normalize(slot.nav.steerDir, tac.faceThreatDir) + let offDeg = acos(clamp(dot(travel, tac.faceThreatDir), -1.0, 1.0)) * WTO_RAD_TO_DEG + want = offDeg >= WTO_AI_BHV_REVERSE_ANGLE_DEG + if want == tac.reverseTravel + return + if (now - tac.reverseSince) < WTO_AI_BHV_REVERSE_HOLD_SEC && moving + return + tac.reverseTravel = want + tac.reverseSince = now + if WTO_AI_DIAG_TELEMETRY + print("WTO_AI|REVERSE_TRAVEL|t={now}|eid={uint(slot.eid)}|on={want}|goal={distGoal}\n") diff --git a/game-ai/ground/wto_ai_fire_speed_common.das b/game-ai/ground/wto_ai_fire_speed_common.das deleted file mode 100644 index 92f822f..0000000 --- a/game-ai/ground/wto_ai_fire_speed_common.das +++ /dev/null @@ -1,19 +0,0 @@ -// Shared speed limit for the movement command and the shot permission check. -options indenting = 2 -options no_global_heap = true -module wto_ai_fire_speed_common shared - -require math -require %appGame.wtoai.wto_ai_config_common - -def public wto_fire_speed_limit_mps(distXZ, maxFwdMps : float) : float - let stop = WTO_AI_FC_STOP_SPEED_MAX_MPS - if distXZ > WTO_AI_FC_MID_RANGE_M - return stop - let close = max(stop, min(maxFwdMps, WTO_AI_FC_CLOSE_MAX_MPS)) - let mid = clamp(min(maxFwdMps * WTO_AI_FC_MID_SLOW_RATIO, WTO_AI_FC_MID_SLOW_MAX_MPS), stop, close) - if distXZ <= WTO_AI_FC_CLOSE_RANGE_M - let pointBlank = max(close, min(maxFwdMps, WTO_AI_FC_POINT_BLANK_MAX_MPS)) - return lerp(pointBlank, close, distXZ / WTO_AI_FC_CLOSE_RANGE_M) - let frac = (distXZ - WTO_AI_FC_CLOSE_RANGE_M) / (WTO_AI_FC_MID_RANGE_M - WTO_AI_FC_CLOSE_RANGE_M) - return lerp(close, mid, frac) diff --git a/game-ai/ground/wto_ai_follow_common.das b/game-ai/ground/wto_ai_follow_common.das index 1505fdd..7d8dacc 100644 --- a/game-ai/ground/wto_ai_follow_common.das +++ b/game-ai/ground/wto_ai_follow_common.das @@ -1,6 +1,6 @@ // Pure-pursuit path following on a bot's corridor: where the bot is along it, the lookahead point -// it steers at, and how fast it may go so it slows down before sharp corners and its destination -// instead of braking at the wall. +// it steers at, how fast it may go so it slows down before sharp corners and its destination +// instead of braking at the wall, and whether it drives forwards or backwards along it. options indenting = 2 options no_global_heap = true module wto_ai_follow_common shared @@ -23,6 +23,19 @@ def public wto_drive_cmd_set(var cmd : WtoDriveCmd&; mode : int; targetPos, desi cmd.frontClearM = frontClr cmd.rearClearM = rearClr +// Drive mode for travelling along `dir` (decision layer design, 7.3). Forward: cruise, or pivot +// for a sharp turn. Reverse route following: the rear leads along `dir` and the front stays +// toward the threat; for a sharp turn the hull first pivots until its rear points along `dir`. +def public wto_follow_drive_mode(dir, hullFwd : float3; reverse : bool; var outDir : float3&) : int + let lead = reverse ? -hullFwd : hullFwd + let turnDeg = acos(clamp(dot(dir, lead), -1.0, 1.0)) * WTO_RAD_TO_DEG + outDir = dir + if turnDeg >= WTO_AI_NAV_PIVOT_ANGLE_DEG + if reverse + outDir = -dir + return WTO_DRIVE_PIVOT + return reverse ? WTO_DRIVE_REVERSE : WTO_DRIVE_CRUISE + // Moves the bot's place on its corridor forward and records its XZ distance from the corridor. [never_inline] def public wto_follow_track(myPos : float3; var rt : WtoRouteState&) diff --git a/game-ai/ground/wto_ai_nav_common.das b/game-ai/ground/wto_ai_nav_common.das index 4320754..6a71a29 100644 --- a/game-ai/ground/wto_ai_nav_common.das +++ b/game-ai/ground/wto_ai_nav_common.das @@ -1,6 +1,7 @@ // Navigation layer of one bot per nav tick: turns the tactics goal into a drive command. -// Stationary and hull-angle states hold or pivot in place; tactical withdrawals and unstick -// manoeuvres back up along checked ground; otherwise the bot follows its corridor (route) with a +// Stationary states hold, or pivot in place toward the facing direction of the hull channel; +// tactical withdrawals and unstick manoeuvres back up along checked ground; a bot keeping its front +// toward a threat drives its corridor backwards; otherwise the bot follows its corridor (route) with a // lookahead point it can reach in a straight line (follow), passes or follows vehicles and wrecks // (traffic), slows for corners, narrow passages and fresh obstacles (avoid), backs off at once // when pressed against a vehicle, and escalates when it stops making progress (unstick). @@ -36,7 +37,9 @@ def private wto_nav_halt(myPos, hullFwd : float3; var slot : WtoBotSlot&) [never_inline] def private wto_try_hull_aim(myPos, hullFwd : float3; var slot : WtoBotSlot&) : bool let state = slot.tactics.state - if state != WTO_STATE_MARCH && state != WTO_STATE_RUN_AND_GUN && state != WTO_STATE_PREAIM && state != WTO_STATE_SHORT_HALT + let allowed = (state == WTO_STATE_MARCH || state == WTO_STATE_RUN_AND_GUN || state == WTO_STATE_PREAIM || + state == WTO_STATE_SHORT_HALT || state == WTO_STATE_HULL_ANGLE) + if !allowed return false if !slot.fire.hullAimTarget || slot.fire.hullAimTarget != slot.perceive.targetEid || slot.tactics.immobilized return false @@ -51,12 +54,23 @@ def private wto_try_hull_aim(myPos, hullFwd : float3; var slot : WtoBotSlot&) : def private wto_nav_hull_angle(myPos, hullFwd : float3; var slot : WtoBotSlot&) let wishAngle = wto_xz_normalize(slot.tactics.hullAngleDir, hullFwd) let angErr = acos(clamp(dot(wishAngle, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG - if angErr > 8.0 + if angErr > WTO_AI_BHV_FACE_TOL_DEG slot.nav.stuckCheckAt = -100.0 wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_PIVOT, myPos + wishAngle * 14.0, wishAngle, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) else wto_nav_halt(myPos, hullFwd, slot) +// Standing for a shot or in cover: turn toward the facing direction (decision layer design, 7.3) +// only when the hull is more than limitDeg off it, else hold still. +[never_inline] +def private wto_nav_stand(myPos, hullFwd : float3; limitDeg : float; var slot : WtoBotSlot&) + assume tac = slot.tactics + if tac.faceActive && acos(clamp(dot(tac.faceDir, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG > limitDeg + slot.nav.stuckCheckAt = -100.0 + wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_PIVOT, myPos + tac.faceDir * 14.0, tac.faceDir, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) + return + wto_nav_halt(myPos, hullFwd, slot) + // Ridge withdrawal and backing into cover: reverse straight to the goal when the way is free. [never_inline] def private wto_nav_tactical_reverse(navState : int; myPos, hullFwd : float3; var slot : WtoBotSlot&) : bool @@ -154,10 +168,12 @@ def private wto_nav_follow(var world : WtoWorldSnap&; navState : int; now : floa wto_nav_halt(myPos, hullFwd, slot) return wto_follow_track(myPos, rt) + let reverse = slot.tactics.reverseTravel + let lead = reverse ? -hullFwd : hullFwd let speedNow = abs(slot.drive.lastVFwd) let lookM = wto_follow_lookahead(slot.spec, speedNow) let pathTarget = wto_nav_visible_target(navState, myPos, lookM, slot) - let pathDir = wto_xz_normalize(pathTarget - myPos, hullFwd) + let pathDir = wto_xz_normalize(pathTarget - myPos, lead) let narrow = slot.nav.wallDistM < WTO_AI_PF_NARROW_WALL_M || slot.nav.chokepoint wto_traffic_update(world, navState, now, myPos, pathDir, speedNow, narrow, slot) if wto_traffic_in_contact(now, slot.nav) @@ -166,12 +182,14 @@ def private wto_nav_follow(var world : WtoWorldSnap&; navState : int; now : floa wto_nav_halt(myPos, hullFwd, slot) return let target = slot.nav.avoidActive ? slot.nav.avoidTarget : pathTarget - let dir = wto_xz_normalize(target - myPos, hullFwd) - let speed = wto_nav_speed(navState, now, myPos, dir, lookM, narrow, slot) + let dir = wto_xz_normalize(target - myPos, lead) + var speed = wto_nav_speed(navState, now, myPos, dir, lookM, narrow, slot) + if reverse + speed = min(speed, slot.spec.vMaxRev) slot.nav.steerDir = dir - let turnDeg = acos(clamp(dot(dir, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG - let mode = turnDeg >= WTO_AI_NAV_PIVOT_ANGLE_DEG ? WTO_DRIVE_PIVOT : WTO_DRIVE_CRUISE - wto_drive_cmd_set(slot.driveCmd, mode, target, dir, speed, slot.nav.frontClearM, slot.nav.rearClearM) + var cmdDir = dir + let mode = wto_follow_drive_mode(dir, hullFwd, reverse, cmdDir) + wto_drive_cmd_set(slot.driveCmd, mode, target, cmdDir, speed, slot.nav.frontClearM, slot.nav.rearClearM) let movingIntent = slot.tactics.desiredSpeedMps > 1.2 && now >= slot.nav.yieldUntil wto_unstick_watch(world, navState, now, myPos, hullFwd, myPos + dir * 6.0, movingIntent, slot) @@ -186,12 +204,15 @@ def public wto_nav_update(var world : WtoWorldSnap&; navState, slotIdx : int; no slot.nav.frontClearM = wto_terrain_hard_ray(probeBase, hullFwd, 24.0) slot.nav.rearClearM = wto_terrain_hard_ray(probeBase, -hullFwd, 18.0) let st = slot.tactics.state + if wto_try_hull_aim(myPos, hullFwd, slot) + return if st == WTO_STATE_HULL_ANGLE wto_nav_hull_angle(myPos, hullFwd, slot) return - if wto_try_hull_aim(myPos, hullFwd, slot) + if st == WTO_STATE_SHORT_HALT || st == WTO_STATE_COVER_RELOAD + wto_nav_stand(myPos, hullFwd, st == WTO_STATE_SHORT_HALT ? WTO_AI_BHV_FACE_HALT_LIMIT_DEG : WTO_AI_BHV_FACE_TOL_DEG, slot) return - if st == WTO_STATE_SHORT_HALT || st == WTO_STATE_COVER_RELOAD || slot.tactics.desiredSpeedMps <= 0.05 + if slot.tactics.desiredSpeedMps <= 0.05 wto_nav_halt(myPos, hullFwd, slot) return if wto_nav_tactical_reverse(navState, myPos, hullFwd, slot) || wto_unstick_reversing(now, myPos, slot) diff --git a/game-ai/ground/wto_ai_tactics_actions_common.das b/game-ai/ground/wto_ai_tactics_actions_common.das index 14c4f52..46b16cd 100644 --- a/game-ai/ground/wto_ai_tactics_actions_common.das +++ b/game-ai/ground/wto_ai_tactics_actions_common.das @@ -1,5 +1,6 @@ -// Tactics action handlers: damage retreat & repair (plan 6.1), cover retreat & 3-way reload -// actions, and stalemate detection / reposition unlock. +// Hull channel actions (decision layer design, 7.1): damage retreat & repair (rebuild plan 6.1), +// cover pull-back while reloading, and stalemate detection / reposition. The behaviors in +// wto_ai_tactics_common.das run them. options indenting = 2 options no_global_heap = true module wto_ai_tactics_actions_common shared @@ -116,42 +117,32 @@ def public wto_sm_continue_cover_retreat(world : WtoWorldSnap const&; now : floa return false return false +// Reloading under threat: pull back into remembered or nearby cover (6..24 m), backwards when the +// cover lies behind the hull. False when no cover is found. [never_inline] -def public wto_sm_start_reload_action(world : WtoWorldSnap const&; now : float; - myPos, hullFwd, threatPos, baseGoal : float3; - distXZ, distGoal : float; var slot : WtoBotSlot&) : bool +def public wto_sm_start_cover_retreat(world : WtoWorldSnap const&; now : float; + myPos, hullFwd, threatPos : float3; distXZ : float; + var slot : WtoBotSlot&) : bool assume tac = slot.tactics - // Option 1: pull back into remembered or nearby cover (6..24m). var cov = myPos - if wto_cover_pick_candidate(world, now, myPos, threatPos, false, slot, cov) - let toCov = wto_xz_normalize(cov - myPos, -hullFwd) - let behindHull = dot(toCov, hullFwd) < -0.15 - tac.retreatTarget = cov - tac.retreatUntil = now + WTO_AI_SM_COVER_RETREAT_SEC - tac.retreatReverse = behindHull && slot.nav.rearClearM > 3.2 && slot.spec.vMaxRev >= 2.0 - let spd = tac.retreatReverse ? max(2.2, slot.spec.vMaxRev) : (slot.spec.vMaxFwd * 0.92) - wto_sm_set_state(now, WTO_STATE_RETREAT_COVER, cov, spd, "reload_pullback", distXZ, slot) - return true - // Option 2: no near cover and offensive/advancing -> zigzag push toward objective. - if wto_order_is_offensive(slot.order.role) || distGoal > 35.0 - let toGoal = wto_xz_normalize(baseGoal - myPos, hullFwd) - let zigSign = (uint(slot.eid) & 1u) == 0u ? 1.0 : -1.0 - let ang = zigSign * WTO_AI_SM_RELOAD_ADV_DEG * WTO_DEG_TO_RAD - let zigDir = float3(toGoal.x * cos(ang) - toGoal.z * sin(ang), 0.0, toGoal.x * sin(ang) + toGoal.z * cos(ang)) - let zigGoal = wto_clamp_battle_xz(myPos + zigDir * min(distGoal, 48.0), world.battleCenter, world.battleRadius, 35.0) - wto_sm_set_state(now, WTO_STATE_RELOAD_ADVANCE, zigGoal, slot.spec.vMaxFwd * 0.92, "reload_advance", distXZ, slot) - return true - // Option 3: defensive hold with side/rear exposed > 30 deg -> angle hull front +/-15 deg toward threat. - let toThreat = wto_xz_normalize(threatPos - myPos, hullFwd) - let exposureDeg = acos(clamp(dot(hullFwd, toThreat), -1.0, 1.0)) * WTO_RAD_TO_DEG - let hasPivotRoom = slot.nav.frontClearM >= slot.spec.halfLen + 1.5 && slot.nav.rearClearM >= slot.spec.halfLen + 1.2 - if exposureDeg > WTO_AI_SM_HULL_ANGLE_TRIG_DEG && hasPivotRoom - let angSign = (uint(slot.eid) & 1u) == 0u ? 1.0 : -1.0 - let ang = angSign * WTO_AI_SM_HULL_ANGLE_TGT_DEG * WTO_DEG_TO_RAD - tac.hullAngleDir = float3(toThreat.x * cos(ang) - toThreat.z * sin(ang), 0.0, toThreat.x * sin(ang) + toThreat.z * cos(ang)) - wto_sm_set_state(now, WTO_STATE_HULL_ANGLE, myPos, 0.0, "reload_angle_hull", distXZ, slot) - return true - return false + if !wto_cover_pick_candidate(world, now, myPos, threatPos, false, slot, cov) + return false + let toCov = wto_xz_normalize(cov - myPos, -hullFwd) + let behindHull = dot(toCov, hullFwd) < -0.15 + tac.retreatTarget = cov + tac.retreatUntil = now + WTO_AI_SM_COVER_RETREAT_SEC + tac.retreatReverse = behindHull && slot.nav.rearClearM > 3.2 && slot.spec.vMaxRev >= 2.0 + let spd = tac.retreatReverse ? max(2.2, slot.spec.vMaxRev) : (slot.spec.vMaxFwd * 0.92) + wto_sm_set_state(now, WTO_STATE_RETREAT_COVER, cov, spd, "reload_pullback", distXZ, slot) + return true + +// The engagement is stuck: shots without effect, halts without a shot, or too long halted. +def public wto_sm_reposition_stale(now : float; slot : WtoBotSlot const&) : bool + assume tac = slot.tactics + let shotTimeoutOk = (now - slot.fire.lastShotAt) >= 1.2 + let staleShots = tac.engageShotsNoEffect >= WTO_AI_SM_STALE_MISS_SHOTS && shotTimeoutOk + let staleHalts = tac.engageNoShotHalts >= WTO_AI_SM_STALE_NOSHOT_HALTS + return staleShots || staleHalts || tac.engageTotalHaltSec >= WTO_AI_SM_MAX_TOTAL_HALT_SEC [never_inline] def public wto_sm_handle_reposition(world : WtoWorldSnap const&; now : float; @@ -170,11 +161,7 @@ def public wto_sm_handle_reposition(world : WtoWorldSnap const&; now : float; wto_sm_set_state(now, WTO_STATE_REPOSITION, tac.repositionGoal, slot.spec.vMaxFwd * 0.92, "reposition_move", distXZ, slot) return true - let shotTimeoutOk = (now - slot.fire.lastShotAt) >= 1.2 - let staleShots = tac.engageShotsNoEffect >= WTO_AI_SM_STALE_MISS_SHOTS && shotTimeoutOk - let staleHalts = tac.engageNoShotHalts >= WTO_AI_SM_STALE_NOSHOT_HALTS - let staleTime = tac.engageTotalHaltSec >= WTO_AI_SM_MAX_TOTAL_HALT_SEC - if !staleShots && !staleHalts && !staleTime + if !wto_sm_reposition_stale(now, slot) return false let lat = float3(-threatDir.z, 0.0, threatDir.x) let side = (uint(slot.eid) & 1u) == 0u ? 1.0 : -1.0 @@ -191,5 +178,5 @@ def public wto_sm_handle_reposition(world : WtoWorldSnap const&; now : float; tac.engageShotsNoEffect = 0 tac.engageNoShotHalts = 0 tac.engageTotalHaltSec = 0.0 - wto_sm_set_state(now, WTO_STATE_REPOSITION, goal, slot.spec.vMaxFwd * 0.92, staleShots ? "stale_no_effect" : (staleHalts ? "stale_no_shot" : "stale_halt_time"), distXZ, slot) + wto_sm_set_state(now, WTO_STATE_REPOSITION, goal, slot.spec.vMaxFwd * 0.92, "stale_engagement", distXZ, slot) return true diff --git a/game-ai/ground/wto_ai_tactics_common.das b/game-ai/ground/wto_ai_tactics_common.das index b69591d..5b51546 100644 --- a/game-ai/ground/wto_ai_tactics_common.das +++ b/game-ai/ground/wto_ai_tactics_common.das @@ -1,6 +1,9 @@ -// Per-bot hull state machine orchestrator: strict priority arbitration across safety/repair, -// active cover retreat, ridge withdrawal, stalemate reposition, short-halt budget, dispersion, -// 3-way reload actions, and distance-tier x task-order movement/shooting. +// Hull channel (decision layer design, section 7), once per tactics tick: damage/repair and ridge +// withdrawal take over at once; otherwise the behavior chosen by score (wto_ai_behavior_common.das) +// runs as a small action that sets the goal, speed and WTO_STATE_* for navigation. The facing +// constraint and the reverse-travel decision (wto_ai_facing_common.das) are updated every tick. +// A behavior that ends by itself (shot taken, cover reached and reloaded, no cover found) is +// replaced in the same tick. options indenting = 2 options no_global_heap = true module wto_ai_tactics_common shared @@ -11,13 +14,14 @@ require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_order_common require %appGame.wtoai.wto_ai_combat_types_common -require %appGame.wtoai.wto_ai_fire_speed_common require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_nav_types_common require %appGame.wtoai.wto_ai_terrain_common require %appGame.wtoai.wto_ai_crowd_common require %appGame.wtoai.wto_ai_cover_common require %appGame.wtoai.wto_ai_tactics_actions_common +require %appGame.wtoai.wto_ai_behavior_common +require %appGame.wtoai.wto_ai_facing_common [never_inline] def private wto_sm_sync_engagement_counters(dt : float; var slot : WtoBotSlot&) @@ -25,7 +29,6 @@ def private wto_sm_sync_engagement_counters(dt : float; var slot : WtoBotSlot&) assume p = slot.perceive if p.hasClearLos && !!p.targetEid && !p.targetIsAir && tac.engageTargetEid != p.targetEid tac.engageTargetEid = p.targetEid - tac.movingShotBlockedSince = -100.0 tac.engageShotsNoEffect = 0 tac.engageNoShotHalts = 0 tac.engageTotalHaltSec = 0.0 @@ -64,49 +67,18 @@ def private wto_sm_handle_ridge(world : WtoWorldSnap const&; now : float; return false [never_inline] -def private wto_sm_stop_range_allowed(distXZ : float; slot : WtoBotSlot const&) : bool - let maxStop = slot.order.valid ? slot.order.maxStopRangeM : WTO_AI_FC_MAX_RANGE_M - if distXZ > min(maxStop, WTO_AI_FC_MAX_RANGE_M) - return false - return (distXZ <= WTO_AI_FC_LONG_RANGE_M || - (slot.perceive.goodLosSec >= WTO_AI_FC_LONG_WINDOW_SEC && slot.perceive.visiblePointCount >= 2)) - -[never_inline] -def private wto_sm_continue_short_halt(now : float; myPos : float3; hasGroundTgt : bool; - distXZ : float; var slot : WtoBotSlot&) : bool +def private wto_tac_disperse(world : WtoWorldSnap const&; now : float; myPos : float3; c : WtoBhvCtx const&; + var slot : WtoBotSlot&; var crowdSummary : WtoCrowdSummary&) : bool assume tac = slot.tactics - if tac.state != WTO_STATE_SHORT_HALT - return false - if slot.fire.shotCount > tac.haltStartShots || slot.fire.reloading - if slot.fire.shotCount > tac.haltStartShots - tac.engageShotsNoEffect += slot.fire.shotCount - tac.haltStartShots - tac.haltStartShots = slot.fire.shotCount - return false - if !hasGroundTgt || !wto_sm_stop_range_allowed(distXZ, slot) - return false - if (now - tac.haltEnterAt) >= WTO_AI_SM_SHORT_HALT_MAX_SEC - tac.engageNoShotHalts++ - tac.shortHaltCooldownUntil = now + WTO_AI_SM_SHORT_HALT_COOLDOWN_SEC - return false - wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "halt_continue", distXZ, slot) - return true - -[never_inline] -def private wto_sm_handle_dispersion(world : WtoWorldSnap const&; now : float; - myPos, threatDir : float3; distXZ : float; - var slot : WtoBotSlot&; var crowdSummary : WtoCrowdSummary&) : bool - assume tac = slot.tactics - if distXZ <= WTO_AI_FC_CLOSE_RANGE_M - return false if now < tac.disperseUntil && wto_xz_dist_sq(myPos, tac.disperseGoal) > 25.0 - wto_sm_set_state(now, WTO_STATE_DISPERSE, tac.disperseGoal, slot.spec.vMaxFwd * 0.85, "disperse_hold", distXZ, slot) + wto_sm_set_state(now, WTO_STATE_DISPERSE, tac.disperseGoal, slot.spec.vMaxFwd * 0.85, "disperse_hold", c.distTarget, slot) return true if !slot.crowd.isCrowded return false - tac.disperseGoal = wto_crowd_pick_disperse_pos(world, slot.army, slot.eid, myPos, threatDir, slot.crowd) + tac.disperseGoal = wto_crowd_pick_disperse_pos(world, slot.army, slot.eid, myPos, c.threatDir, slot.crowd) tac.disperseUntil = now + WTO_AI_CROWD_DISPERSE_HOLD_SEC crowdSummary.disperseEvents++ - wto_sm_set_state(now, WTO_STATE_DISPERSE, tac.disperseGoal, slot.spec.vMaxFwd * 0.85, "disperse_start", distXZ, slot) + wto_sm_set_state(now, WTO_STATE_DISPERSE, tac.disperseGoal, slot.spec.vMaxFwd * 0.85, "disperse_start", c.distTarget, slot) return true [never_inline] @@ -116,93 +88,108 @@ def private wto_sm_march_speed(slot : WtoBotSlot const&; distGoal : float) : flo let capScale = slot.order.cautious ? 0.78 : 0.98 return distGoal < 24.0 ? min(slot.spec.vMaxFwd * 0.55, 6.0) : (slot.spec.vMaxFwd * capScale) +// Short halt (7.1): stand until the shot leaves, the reload starts, the target is gone or +// stateMachine.shortHaltMaxSec runs out; then a cooldown of shortHaltCooldownSec. [never_inline] -def private wto_sm_waited_for_moving_shot(now : float; aimReady : bool; var slot : WtoBotSlot&) : bool +def private wto_tac_halt(now : float; myPos : float3; c : WtoBhvCtx const&; var slot : WtoBotSlot&) : bool assume tac = slot.tactics - let deny = slot.fire.lastDenyReason - let blocked = deny == WTO_DENY_HIT_PROB || deny == WTO_DENY_AIM_ERR || deny == WTO_DENY_SETTLE - if tac.state != WTO_STATE_RUN_AND_GUN || !aimReady || !blocked - tac.movingShotBlockedSince = -100.0 + if tac.state != WTO_STATE_SHORT_HALT + wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "halt_for_shot", c.distTarget, slot) + return true + let shots = slot.fire.shotCount - tac.haltStartShots + if shots > 0 + tac.engageShotsNoEffect += shots + tac.haltStartShots = slot.fire.shotCount + let timeout = (now - tac.haltEnterAt) >= WTO_AI_SM_SHORT_HALT_MAX_SEC + if timeout && shots <= 0 + tac.engageNoShotHalts++ + if shots > 0 || timeout || slot.fire.reloading || !c.hasTarget || !c.stopRangeOk + tac.shortHaltCooldownUntil = now + WTO_AI_SM_SHORT_HALT_COOLDOWN_SEC return false - if tac.movingShotBlockedSince < tac.stateEnteredAt - tac.movingShotBlockedSince = now - return now - tac.movingShotBlockedSince >= WTO_AI_SM_MOVING_SHOT_WAIT_SEC + wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "halt_hold", c.distTarget, slot) + return true + +// Engaging on the move (7.1): along the route, as fast as the trigger channel's speed request +// allows; an urgent order keeps behavior.urgentSpeedKeep of the march speed regardless. +[never_inline] +def private wto_tac_engage(now : float; c : WtoBhvCtx const&; var slot : WtoBotSlot&) : bool + let march = wto_sm_march_speed(slot, c.distGoal) + var speed = march + assume tr = slot.trigger + let fresh = (now - tr.wantSpeedAt) <= WTO_AI_TACTICS_TICK_SEC * 3.0 + if fresh && tr.wantSpeedMps > WTO_AI_FC_STOP_SPEED_MAX_MPS && tr.wantSpeedMps < march + speed = lerp(tr.wantSpeedMps, march, c.urgent ? WTO_AI_BHV_URGENT_SPEED_KEEP : 0.0) + wto_sm_set_state(now, WTO_STATE_RUN_AND_GUN, c.baseGoal, speed, "engage", c.distTarget, slot) + return true [never_inline] -def private wto_sm_handle_combat(world : WtoWorldSnap const&; now : float; - myPos, hullFwd, threatPos, baseGoal : float3; - distXZ, distGoal : float; var slot : WtoBotSlot&) : bool +def private wto_tac_hold(now : float; myPos, hullFwd : float3; c : WtoBhvCtx const&; var slot : WtoBotSlot&) : bool assume tac = slot.tactics - assume fc = slot.fire - let marchSpd = wto_sm_march_speed(slot, distGoal) - if fc.reloading - return wto_sm_start_reload_action(world, now, myPos, hullFwd, threatPos, baseGoal, distXZ, distGoal, slot) - let close = distXZ <= WTO_AI_FC_CLOSE_RANGE_M - let urgentPush = slot.order.urgency == WTO_URGENCY_HIGH || distGoal > 130.0 - let canHalt = now >= tac.shortHaltCooldownUntil && !tac.repositionActive && wto_sm_stop_range_allowed(distXZ, slot) - let aimReady = (fc.gunReady && fc.aimTargetEid == slot.perceive.targetEid && fc.lastAimErrDeg <= WTO_AI_SM_PREAIM_DEG) - if marchSpd > 0.0 && (close || (distXZ <= WTO_AI_FC_MID_RANGE_M && urgentPush)) - if wto_sm_waited_for_moving_shot(now, aimReady, slot) && canHalt - wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "moving_shot_halt", distXZ, slot) - else - let speed = min(marchSpd, wto_fire_speed_limit_mps(distXZ, slot.spec.vMaxFwd)) - wto_sm_set_state(now, WTO_STATE_RUN_AND_GUN, baseGoal, speed, close ? "close_run_gun" : "mid_slow_fire", distXZ, slot) + tac.hullAngleDir = tac.faceActive ? tac.faceDir : hullFwd + let why = c.holdReason == WTO_HOLD_WATCH ? "watch_last_exit" : (c.holdReason == WTO_HOLD_RALLY ? "rally_wait" : "hold_post") + wto_sm_set_state(now, WTO_STATE_HULL_ANGLE, myPos, 0.0, why, c.distTarget, slot) + return c.holdReason != WTO_HOLD_NONE + +[never_inline] +def private wto_tac_cover(world : WtoWorldSnap const&; now : float; myPos, hullFwd : float3; c : WtoBhvCtx const&; + var slot : WtoBotSlot&) : bool + assume tac = slot.tactics + if tac.state == WTO_STATE_RETREAT_COVER || tac.state == WTO_STATE_COVER_RELOAD + return wto_sm_continue_cover_retreat(world, now, myPos, c.threatPos, c.distTarget, slot) + if wto_sm_start_cover_retreat(world, now, myPos, hullFwd, c.threatPos, c.distTarget, slot) return true - if !canHalt - return false - if !aimReady - wto_sm_set_state(now, WTO_STATE_PREAIM, baseGoal, marchSpd, "preaim_move", distXZ, slot) - return true - wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "short_halt_ready", distXZ, slot) + tac.coverFailedAt = now + return false + +[never_inline] +def private wto_tac_advance(now : float; myPos : float3; c : WtoBhvCtx const&; var slot : WtoBotSlot&) : bool + let speed = wto_sm_march_speed(slot, c.distGoal) + wto_sm_set_state(now, WTO_STATE_MARCH, c.atGoal ? myPos : c.baseGoal, speed, "advance", c.distTarget, slot) return true +// Runs the chosen behavior; false when it has ended or cannot run. +[never_inline] +def private wto_tac_run(world : WtoWorldSnap const&; now : float; myPos, hullFwd : float3; c : WtoBhvCtx const&; + var slot : WtoBotSlot&; var crowdSummary : WtoCrowdSummary&) : bool + let bhv = slot.tactics.behavior + if bhv == WTO_BHV_ENGAGE + return c.hasTarget && wto_tac_engage(now, c, slot) + if bhv == WTO_BHV_HALT + return wto_tac_halt(now, myPos, c, slot) + if bhv == WTO_BHV_COVER + return wto_tac_cover(world, now, myPos, hullFwd, c, slot) + if bhv == WTO_BHV_REPOSITION + return wto_sm_handle_reposition(world, now, myPos, c.threatDir, c.baseGoal, c.distTarget, slot) + if bhv == WTO_BHV_HOLD + return wto_tac_hold(now, myPos, hullFwd, c, slot) + if bhv == WTO_BHV_DISPERSE + return wto_tac_disperse(world, now, myPos, c, slot, crowdSummary) + if bhv == WTO_BHV_ADVANCE + return wto_tac_advance(now, myPos, c, slot) + return false + [never_inline] def public wto_tactics_update(world : WtoWorldSnap const&; now, dt : float; myPos, rawHullFwd : float3; isBurn : bool; repairRemainingSec : float; var slot : WtoBotSlot&; var crowdSummary : WtoCrowdSummary&) let hullFwd = wto_xz_normalize(rawHullFwd, float3(1.0, 0.0, 0.0)) - let baseGoal = slot.order.valid ? slot.order.goalPos : world.battleCenter - let distGoal = sqrt(wto_xz_dist_sq(myPos, baseGoal)) if !WTO_AI_LAYER_TACTICS wto_sm_set_state(now, WTO_STATE_MARCH, slot.order.valid ? slot.order.goalPos : myPos, slot.spec.vMaxFwd * 0.9, "layer_off", 9999.0, slot) return - assume p = slot.perceive - let hasGroundTgt = p.hasClearLos && !!p.targetEid && !p.targetIsAir - let distXZ = hasGroundTgt ? sqrt(wto_xz_dist_sq(myPos, p.knownPos)) : 9999.0 - let threatPos = !!p.targetEid ? p.knownPos : baseGoal - let threatDir = wto_xz_normalize(threatPos - myPos, hullFwd) - + var c = WtoBhvCtx() + wto_bhv_context(world, now, myPos, hullFwd, wto_sm_reposition_stale(now, slot), slot, c) wto_sm_sync_engagement_counters(dt, slot) wto_cover_update_memory(world, now, myPos, slot) - if wto_sm_handle_disabled_and_repair(world, now, myPos, threatPos, threatDir, isBurn, repairRemainingSec, distXZ, slot) - return - if wto_sm_continue_cover_retreat(world, now, myPos, threatPos, distXZ, slot) - return - if wto_sm_handle_ridge(world, now, myPos, threatDir, distXZ, slot) - return - if wto_sm_handle_reposition(world, now, myPos, threatDir, baseGoal, distXZ, slot) - return - if wto_sm_continue_short_halt(now, myPos, hasGroundTgt, distXZ, slot) - return - if wto_sm_handle_dispersion(world, now, myPos, threatDir, distXZ, slot, crowdSummary) - return - if hasGroundTgt && wto_sm_handle_combat(world, now, myPos, hullFwd, threatPos, baseGoal, distXZ, distGoal, slot) - return - if slot.fire.reloading && !!p.targetEid && (now - p.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC - if wto_sm_start_reload_action(world, now, myPos, hullFwd, threatPos, baseGoal, distXZ, distGoal, slot) - return - // Stationary overwatch/defend bots hold their firing post briefly to watch the enemy's last exit point; - // marching/pushing bots keep advancing while the turret watches. - if !hasGroundTgt && now < p.watchUntil && slot.order.urgency != WTO_URGENCY_HIGH && distGoal <= 35.0 - wto_sm_set_state(now, WTO_STATE_MARCH, myPos, 0.0, "watch_last_exit", distXZ, slot) - return - // Hold at the 40% rally staging point until the group launches (unless threatened inside 300 m). - if slot.order.rallyHold && slot.order.routeRelayValid && distXZ > WTO_AI_FC_MID_RANGE_M - let rallyHoldRad = max(18.0, WTO_AI_CMD_RALLY_RADIUS_M * 0.55) - if wto_xz_dist_sq(myPos, slot.order.routeRelayPos) <= rallyHoldRad * rallyHoldRad - wto_sm_set_state(now, WTO_STATE_MARCH, myPos, 0.0, "rally_wait", distXZ, slot) - return - let marchSpd = wto_sm_march_speed(slot, distGoal) - let marchGoal = distGoal <= 8.0 ? myPos : baseGoal - wto_sm_set_state(now, WTO_STATE_MARCH, marchGoal, marchSpd, "march_task", distXZ, slot) + wto_face_update(now, myPos, hullFwd, slot) + if wto_sm_handle_disabled_and_repair(world, now, myPos, c.threatPos, c.threatDir, isBurn, repairRemainingSec, c.distTarget, slot) + wto_bhv_take_over(now, WTO_BHV_REPAIR, slot) + elif wto_sm_handle_ridge(world, now, myPos, c.threatDir, c.distTarget, slot) + wto_bhv_take_over(now, WTO_BHV_WITHDRAW, slot) + else + wto_bhv_choose(now, c, false, slot) + if !wto_tac_run(world, now, myPos, hullFwd, c, slot, crowdSummary) + wto_bhv_choose(now, c, true, slot) + if !wto_tac_run(world, now, myPos, hullFwd, c, slot, crowdSummary) + wto_tac_advance(now, myPos, c, slot) + wto_face_reverse_update(now, c.distGoal, slot) diff --git a/game-ai/ground/wto_ai_types_common.das b/game-ai/ground/wto_ai_types_common.das index b35c219..79877f8 100644 --- a/game-ai/ground/wto_ai_types_common.das +++ b/game-ai/ground/wto_ai_types_common.das @@ -35,6 +35,20 @@ let public WTO_STATE_DISABLED = 9 let public WTO_STATE_DISPERSE = 10 let public WTO_STATE_RIDGE_WITHDRAW = 11 +// Hull channel behaviors (decision layer design, 7.1), chosen by score in +// wto_ai_behavior_common.das; each runs as one or more WTO_STATE_* actions. REPAIR and WITHDRAW +// are not scored: they take over at once. +let public WTO_BHV_ADVANCE = 0 +let public WTO_BHV_ENGAGE = 1 +let public WTO_BHV_HALT = 2 +let public WTO_BHV_COVER = 3 +let public WTO_BHV_REPOSITION = 4 +let public WTO_BHV_HOLD = 5 +let public WTO_BHV_DISPERSE = 6 +let public WTO_BHV_WITHDRAW = 7 +let public WTO_BHV_REPAIR = 8 +let public WTO_BHV_COUNT = 9 + let public WTO_DRIVE_HALT = 0 let public WTO_DRIVE_CRUISE = 1 let public WTO_DRIVE_PIVOT = 2 @@ -195,6 +209,25 @@ struct public WtoTacticsState withdrawUntil : float = -100.0 disperseGoal : float3 = float3(0.0, 0.0, 0.0) disperseUntil : float = -100.0 + // Hull channel (decision layer design, section 7): the chosen behavior, its score, since when + // it runs, when to score again, and what the last scoring saw (a change scores at once). + behavior : int = 0 + behaviorScore : float = 0.0 + behaviorSince : float = -100.0 + nextScoreAt : float = 0.0 + scoredHasTarget : bool = false + scoredReloading : bool = false + scoredDamageAt : float = -100.0 + coverFailedAt : float = -100.0 + // Facing constraint (7.3): the hull should point along faceDir (within the facing tolerance) + // when it stands; threatDir is the threat it faces. reverseTravel: drive the route backwards + // to keep the front toward that threat, decided at reverseSince. + faceActive : bool = false + faceDir : float3 = float3(1.0, 0.0, 0.0) + faceThreatDir : float3 = float3(1.0, 0.0, 0.0) + faceFromThreat : bool = false + reverseTravel : bool = false + reverseSince : float = -100.0 [safe_when_uninitialized] struct public WtoDriveCmd diff --git a/packages/patcher/src/ground-ai/ground-ai-config.ts b/packages/patcher/src/ground-ai/ground-ai-config.ts index 5872122..6f88c9b 100644 --- a/packages/patcher/src/ground-ai/ground-ai-config.ts +++ b/packages/patcher/src/ground-ai/ground-ai-config.ts @@ -205,17 +205,12 @@ export interface GroundAiConfig { readonly discoverScore: number; }; readonly stateMachine: { - readonly preaimAngleDeg: number; - readonly movingShotWaitSec: number; readonly shortHaltMaxSec: number; readonly shortHaltCooldownSec: number; readonly turnLaunchSpeedMps: number; readonly coverMinDistM: number; readonly coverMaxDistM: number; readonly coverRetreatBudgetSec: number; - readonly reloadAdvanceAngleDeg: number; - readonly hullAngleTriggerDeg: number; - readonly hullAngleTargetDeg: number; readonly maxTotalHaltSec: number; readonly stalemateMissShots: number; readonly stalemateNoShotHalts: number; @@ -257,15 +252,37 @@ export interface GroundAiConfig { readonly scanArcDeg: number; readonly scanPeriodSec: number; }; + readonly behavior: { + readonly scoreIntervalSec: number; + readonly minHoldSec: number; + readonly switchMargin: number; + readonly advanceScore: number; + readonly engageScore: number; + readonly urgencyWeight: number; + readonly haltScore: number; + readonly crossfirePenalty: number; + readonly coverScore: number; + readonly coverDangerWeight: number; + readonly coverOffensivePenalty: number; + readonly coverRetrySec: number; + readonly repositionScore: number; + readonly holdScore: number; + readonly disperseScore: number; + readonly urgentSpeedKeep: number; + readonly hullAngleDeg: number; + readonly faceToleranceDeg: number; + readonly faceMinDanger: number; + readonly faceHaltLimitDeg: number; + readonly reverseTravelAngleDeg: number; + readonly reverseMaxGoalDistM: number; + readonly reverseMinSpeedMps: number; + readonly reverseHoldSec: number; + }; readonly fireControl: { readonly maxEngageRangeM: number; readonly closeRangeM: number; readonly midRangeM: number; readonly longRangeM: number; - readonly midSlowSpeedRatio: number; - readonly midSlowMaxMps: number; - readonly closeRangeMaxSpeedKmh: number; - readonly pointBlankMaxSpeedKmh: number; readonly stopSpeedMaxMps: number; readonly longRangeWindowSec: number; readonly baseAlignDeg: number; @@ -440,17 +457,12 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['WTO_AI_PERC_LOOK_AROUND_SEC', 'float', c.perception.lookAroundSec], ['WTO_AI_PERC_LOOK_AROUND_HOLD_SEC', 'float', c.perception.lookAroundHoldSec], ['WTO_AI_PERC_DISCOVER_SCORE', 'float', c.perception.discoverScore], - ['WTO_AI_SM_PREAIM_DEG', 'float', c.stateMachine.preaimAngleDeg], - ['WTO_AI_SM_MOVING_SHOT_WAIT_SEC', 'float', c.stateMachine.movingShotWaitSec], ['WTO_AI_SM_SHORT_HALT_MAX_SEC', 'float', c.stateMachine.shortHaltMaxSec], ['WTO_AI_SM_SHORT_HALT_COOLDOWN_SEC', 'float', c.stateMachine.shortHaltCooldownSec], ['WTO_AI_SM_TURN_LAUNCH_MPS', 'float', c.stateMachine.turnLaunchSpeedMps], ['WTO_AI_SM_COVER_MIN_DIST_M', 'float', c.stateMachine.coverMinDistM], ['WTO_AI_SM_COVER_MAX_DIST_M', 'float', c.stateMachine.coverMaxDistM], ['WTO_AI_SM_COVER_RETREAT_SEC', 'float', c.stateMachine.coverRetreatBudgetSec], - ['WTO_AI_SM_RELOAD_ADV_DEG', 'float', c.stateMachine.reloadAdvanceAngleDeg], - ['WTO_AI_SM_HULL_ANGLE_TRIG_DEG', 'float', c.stateMachine.hullAngleTriggerDeg], - ['WTO_AI_SM_HULL_ANGLE_TGT_DEG', 'float', c.stateMachine.hullAngleTargetDeg], ['WTO_AI_SM_MAX_TOTAL_HALT_SEC', 'float', c.stateMachine.maxTotalHaltSec], ['WTO_AI_SM_STALE_MISS_SHOTS', 'int', c.stateMachine.stalemateMissShots], ['WTO_AI_SM_STALE_NOSHOT_HALTS', 'int', c.stateMachine.stalemateNoShotHalts], @@ -483,14 +495,34 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['WTO_AI_TURRET_SWITCH_MARGIN', 'float', c.turret.switchMargin], ['WTO_AI_TURRET_SCAN_ARC_DEG', 'float', c.turret.scanArcDeg], ['WTO_AI_TURRET_SCAN_PERIOD_SEC', 'float', c.turret.scanPeriodSec], + ['WTO_AI_BHV_SCORE_SEC', 'float', c.behavior.scoreIntervalSec], + ['WTO_AI_BHV_MIN_HOLD_SEC', 'float', c.behavior.minHoldSec], + ['WTO_AI_BHV_SWITCH_MARGIN', 'float', c.behavior.switchMargin], + ['WTO_AI_BHV_ADVANCE', 'float', c.behavior.advanceScore], + ['WTO_AI_BHV_ENGAGE', 'float', c.behavior.engageScore], + ['WTO_AI_BHV_URGENCY_W', 'float', c.behavior.urgencyWeight], + ['WTO_AI_BHV_HALT', 'float', c.behavior.haltScore], + ['WTO_AI_BHV_CROSSFIRE', 'float', c.behavior.crossfirePenalty], + ['WTO_AI_BHV_COVER', 'float', c.behavior.coverScore], + ['WTO_AI_BHV_COVER_DANGER_W', 'float', c.behavior.coverDangerWeight], + ['WTO_AI_BHV_COVER_OFFENSIVE', 'float', c.behavior.coverOffensivePenalty], + ['WTO_AI_BHV_COVER_RETRY_SEC', 'float', c.behavior.coverRetrySec], + ['WTO_AI_BHV_REPOSITION', 'float', c.behavior.repositionScore], + ['WTO_AI_BHV_HOLD', 'float', c.behavior.holdScore], + ['WTO_AI_BHV_DISPERSE', 'float', c.behavior.disperseScore], + ['WTO_AI_BHV_URGENT_SPEED_KEEP', 'float', c.behavior.urgentSpeedKeep], + ['WTO_AI_BHV_HULL_ANGLE_DEG', 'float', c.behavior.hullAngleDeg], + ['WTO_AI_BHV_FACE_TOL_DEG', 'float', c.behavior.faceToleranceDeg], + ['WTO_AI_BHV_FACE_MIN_DANGER', 'float', c.behavior.faceMinDanger], + ['WTO_AI_BHV_FACE_HALT_LIMIT_DEG', 'float', c.behavior.faceHaltLimitDeg], + ['WTO_AI_BHV_REVERSE_ANGLE_DEG', 'float', c.behavior.reverseTravelAngleDeg], + ['WTO_AI_BHV_REVERSE_MAX_GOAL_M', 'float', c.behavior.reverseMaxGoalDistM], + ['WTO_AI_BHV_REVERSE_MIN_MPS', 'float', c.behavior.reverseMinSpeedMps], + ['WTO_AI_BHV_REVERSE_HOLD_SEC', 'float', c.behavior.reverseHoldSec], ['WTO_AI_FC_MAX_RANGE_M', 'float', c.fireControl.maxEngageRangeM], ['WTO_AI_FC_CLOSE_RANGE_M', 'float', c.fireControl.closeRangeM], ['WTO_AI_FC_MID_RANGE_M', 'float', c.fireControl.midRangeM], ['WTO_AI_FC_LONG_RANGE_M', 'float', c.fireControl.longRangeM], - ['WTO_AI_FC_MID_SLOW_RATIO', 'float', c.fireControl.midSlowSpeedRatio], - ['WTO_AI_FC_MID_SLOW_MAX_MPS', 'float', c.fireControl.midSlowMaxMps], - ['WTO_AI_FC_CLOSE_MAX_MPS', 'float', c.fireControl.closeRangeMaxSpeedKmh / 3.6], - ['WTO_AI_FC_POINT_BLANK_MAX_MPS', 'float', c.fireControl.pointBlankMaxSpeedKmh / 3.6], ['WTO_AI_FC_STOP_SPEED_MAX_MPS', 'float', c.fireControl.stopSpeedMaxMps], ['WTO_AI_FC_LONG_WINDOW_SEC', 'float', c.fireControl.longRangeWindowSec], ['WTO_AI_FC_BASE_ALIGN_DEG', 'float', c.fireControl.baseAlignDeg], From ee7bb120928b8e49eec23f3481930b599e56eeb4 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sun, 6 Dec 2026 01:51:00 +0800 Subject: [PATCH 14/19] fix(ground-ai): finish single-vehicle combat decisions Check the live barrel trajectory against the exposed target and shorten fire delays. Resolve automatic and secondary guns using stock weapon data. Keep short halts and withdrawals coherent, follow the order while engaged, and reverse on the route with direction-aware obstacle recovery. Verified daScript loading and native AI script readiness in the guarded 2.61.0.64 lab client. Battle behavior requires manual acceptance. --- .../src/renderer/src/i18n/locales/en.json | 24 ++- .../src/renderer/src/i18n/locales/zh-CN.json | 22 +- .../src/pages/tuning/bot-tuning-fields.ts | 22 +- apps/launcher/src/shared/schemas/tuning.ts | 22 +- apps/server/src/tuning/ground-ai-tuning.ts | 22 +- apps/server/tuning/ground-ai.jsonc | 69 ++++--- game-ai/ground/wto_ai_ammo_common.das | 52 +++++ game-ai/ground/wto_ai_behavior_common.das | 73 +++++-- game-ai/ground/wto_ai_combat_types_common.das | 40 ++-- game-ai/ground/wto_ai_drive_common.das | 9 +- game-ai/ground/wto_ai_estimate_common.das | 58 ++++-- game-ai/ground/wto_ai_facing_common.das | 75 ++++--- game-ai/ground/wto_ai_fire_aux_common.das | 192 +++++++++++------- game-ai/ground/wto_ai_fire_checks_common.das | 110 ++++++++++ game-ai/ground/wto_ai_fire_common.das | 101 +++++---- game-ai/ground/wto_ai_fire_gate_common.das | 166 ++++----------- game-ai/ground/wto_ai_follow_common.das | 16 ++ game-ai/ground/wto_ai_nav_common.das | 49 +---- game-ai/ground/wto_ai_nav_types_common.das | 1 + game-ai/ground/wto_ai_perceive_common.das | 15 +- game-ai/ground/wto_ai_route_common.das | 2 +- game-ai/ground/wto_ai_runtime.das | 15 ++ game-ai/ground/wto_ai_sight_common.das | 14 +- game-ai/ground/wto_ai_slots_common.das | 10 +- game-ai/ground/wto_ai_specs_common.das | 42 ++-- game-ai/ground/wto_ai_stats_common.das | 12 +- .../ground/wto_ai_tactics_actions_common.das | 34 ++-- game-ai/ground/wto_ai_tactics_common.das | 43 ++-- game-ai/ground/wto_ai_traverse_common.das | 36 +++- game-ai/ground/wto_ai_trigger_common.das | 76 +++++-- game-ai/ground/wto_ai_types_common.das | 12 +- game-ai/ground/wto_ai_unstick_common.das | 25 ++- .../ground/wto_ai_weapon_profile_common.das | 76 +++++++ .../patcher/src/ground-ai/ground-ai-config.ts | 44 +++- 34 files changed, 1030 insertions(+), 549 deletions(-) create mode 100644 game-ai/ground/wto_ai_ammo_common.das create mode 100644 game-ai/ground/wto_ai_fire_checks_common.das create mode 100644 game-ai/ground/wto_ai_weapon_profile_common.das diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index d7ec166..a763e0a 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -686,7 +686,15 @@ }, "behavior": { "scoreIntervalSec": "Behavior scoring interval", - "minHoldSec": "Minimum time a behavior is kept", + "advanceHoldSec": "Advance commitment", + "engageHoldSec": "Engage while moving commitment", + "haltHoldSec": "Short halt commitment", + "coverHoldSec": "Take cover commitment", + "repositionHoldSec": "Reposition commitment", + "postHoldSec": "Hold position commitment", + "disperseHoldSec": "Disperse commitment", + "targetValueWeight": "Weight of a viable shot while moving", + "nearThreatHaltBonus": "Short-halt bonus under a close threat", "switchMargin": "Extra score needed to switch behavior", "advanceScore": "Score: advance along the order route", "engageScore": "Score: engage on the move", @@ -704,9 +712,8 @@ "hullAngleDeg": "Hull angle to the main threat", "faceToleranceDeg": "Facing tolerance while standing", "faceMinDanger": "Threat danger needed to face it", - "faceHaltLimitDeg": "Facing error that turns the hull during a short halt", "reverseTravelAngleDeg": "Threat angle off the travel direction for driving backwards", - "reverseMaxGoalDistM": "Drive backwards only toward a goal within", + "reverseMaxTurnDistM": "Max distance to the next turn or route end when reversing", "reverseMinSpeedMps": "Lowest top reverse speed for driving backwards", "reverseHoldSec": "Minimum time between switching forwards and backwards" }, @@ -734,17 +741,22 @@ "enemyReloadSec": "How long a target counts as reloading after it fired", "fleetingThresholdBonus": "Threshold drop for a target about to slip away", "fleetingLateralMps": "Crossing speed of a slipping-away target", - "bigGunThresholdPenalty": "Threshold rise for big slow-loading guns", + "fleetingLookAheadSec": "Look-ahead for losing line of sight", + "reloadThresholdPenalty": "Fire-threshold increase for long reloads", + "longReloadSec": "Reload time for the full threshold penalty", + "lowAmmoRounds": "Ammunition count below which shots are conserved", + "lowAmmoThresholdPenalty": "Fire-threshold increase with little ammunition", + "aimSkill": "Crew skill for aiming spread", + "autocannonMinShotsPerSec": "Minimum firing rate for automatic cannons (rounds/s)", "retreatThresholdPenalty": "Threshold rise while pulling back to cover", "minShotIntervalSec": "Minimum main-gun shot interval", "autocannonAimSlack": "Autocannon aim slack (times target size)", "burstSec": "Burst length", "burstPauseSec": "Pause between bursts", - "burstRecheckSec": "Safety re-check interval within a burst", "autocannonReloadDetectSec": "Autocannon not-ready time that counts as a reload", "auxWeapons": "Fire secondary and coaxial weapons", "auxMaxRangeM": "Secondary and coaxial weapon range", - "auxFireAtArmor": "Secondary and coaxial weapons also fire at armored targets", + "auxFireAtArmor": "Coaxial weapons also fire at non-light vehicles", "friendlyCorridorM": "Friendly fire corridor width", "ballisticStepMaxM": "Ballistic occlusion step length", "ballisticSweepRadiusM": "Ballistic sphere sweep radius", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index cf6d61b..77958af 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -686,7 +686,15 @@ }, "behavior": { "scoreIntervalSec": "行为打分间隔", - "minHoldSec": "行为最短保持时间", + "advanceHoldSec": "??????", + "engageHoldSec": "????????", + "haltHoldSec": "????????", + "coverHoldSec": "????????", + "repositionHoldSec": "??????", + "postHoldSec": "??????", + "disperseHoldSec": "??????", + "targetValueWeight": "???????????", + "nearThreatHaltBonus": "??????????", "switchMargin": "切换行为所需高出的分数", "advanceScore": "得分:沿任务路线推进", "engageScore": "得分:交战推进", @@ -704,9 +712,8 @@ "hullAngleDeg": "车头对主威胁的倾角", "faceToleranceDeg": "停车时朝向容差", "faceMinDanger": "需要车头对准的威胁危险度下限", - "faceHaltLimitDeg": "短停时朝向偏差超过多少才转车体", "reverseTravelAngleDeg": "威胁偏离行进方向多少度时倒车跟路", - "reverseMaxGoalDistM": "仅在离目的地这么近时倒车跟路", + "reverseMaxTurnDistM": "????????????????????", "reverseMinSpeedMps": "倒车跟路所需的最低倒车极速", "reverseHoldSec": "前进与倒车切换的最短间隔" }, @@ -734,13 +741,18 @@ "enemyReloadSec": "目标开火后视为装填中的时长", "fleetingThresholdBonus": "目标即将离开视线时门槛降低", "fleetingLateralMps": "视为即将离开视线的横穿速度", - "bigGunThresholdPenalty": "大口径慢装填火炮的门槛升高", + "fleetingLookAheadSec": "?????????", + "reloadThresholdPenalty": "????????????", + "longReloadSec": "????????????", + "lowAmmoRounds": "???????????", + "lowAmmoThresholdPenalty": "????????????", + "aimSkill": "???????????", + "autocannonMinShotsPerSec": "???????????/??", "retreatThresholdPenalty": "退入掩体途中的门槛升高", "minShotIntervalSec": "主炮最短开火间隔", "autocannonAimSlack": "机炮放宽倍数(目标尺寸的倍数)", "burstSec": "点射时长", "burstPauseSec": "点射间隔", - "burstRecheckSec": "点射中复查弹道和友军的间隔", "autocannonReloadDetectSec": "机炮持续未就绪多久算换弹", "auxWeapons": "使用副炮和并列武器", "auxMaxRangeM": "副炮和并列武器的射击距离", diff --git a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts index 56428c6..a2a531a 100644 --- a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts +++ b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts @@ -255,7 +255,15 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ customOnly: true, fields: [ num('behavior', 'scoreIntervalSec', 0.1, 3, 's'), - num('behavior', 'minHoldSec', 0, 10, 's'), + num('behavior', 'advanceHoldSec', 0, 10, 's'), + num('behavior', 'engageHoldSec', 0, 10, 's'), + num('behavior', 'haltHoldSec', 0, 10, 's'), + num('behavior', 'coverHoldSec', 0, 10, 's'), + num('behavior', 'repositionHoldSec', 0, 10, 's'), + num('behavior', 'postHoldSec', 0, 10, 's'), + num('behavior', 'disperseHoldSec', 0, 10, 's'), + num('behavior', 'targetValueWeight', 0, 1), + num('behavior', 'nearThreatHaltBonus', 0, 1), num('behavior', 'switchMargin', 0, 1), num('behavior', 'advanceScore', 0, 1), num('behavior', 'engageScore', 0, 1), @@ -273,9 +281,8 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ num('behavior', 'hullAngleDeg', 0, 45, '°'), num('behavior', 'faceToleranceDeg', 3, 60, '°'), num('behavior', 'faceMinDanger', 0, 2), - num('behavior', 'faceHaltLimitDeg', 10, 180, '°'), num('behavior', 'reverseTravelAngleDeg', 60, 180, '°'), - num('behavior', 'reverseMaxGoalDistM', 0, 2000, 'm'), + num('behavior', 'reverseMaxTurnDistM', 0, 200, 'm'), num('behavior', 'reverseMinSpeedMps', 0.5, 10, 'm/s'), num('behavior', 'reverseHoldSec', 0, 20, 's'), ], @@ -308,13 +315,18 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ num('fireControl', 'enemyReloadSec', 0, 15, 's'), num('fireControl', 'fleetingThresholdBonus', 0, 0.5), num('fireControl', 'fleetingLateralMps', 0.5, 15, 'm/s'), - num('fireControl', 'bigGunThresholdPenalty', 0, 0.5), + num('fireControl', 'fleetingLookAheadSec', 0.1, 2, 's'), + num('fireControl', 'reloadThresholdPenalty', 0, 0.5), + num('fireControl', 'longReloadSec', 1, 60, 's'), + int('fireControl', 'lowAmmoRounds', 1, 60), + num('fireControl', 'lowAmmoThresholdPenalty', 0, 0.5), + num('fireControl', 'aimSkill', 0, 1), + num('fireControl', 'autocannonMinShotsPerSec', 0.5, 30), num('fireControl', 'retreatThresholdPenalty', 0, 0.6), num('fireControl', 'minShotIntervalSec', 0.1, 5, 's'), num('fireControl', 'autocannonAimSlack', 1, 10), num('fireControl', 'burstSec', 0.2, 6, 's'), num('fireControl', 'burstPauseSec', 0, 5, 's'), - num('fireControl', 'burstRecheckSec', 0.05, 2, 's'), num('fireControl', 'autocannonReloadDetectSec', 0.1, 3, 's'), { id: 'groundAi.fireControl.auxWeapons', section: 'fireControl', field: 'auxWeapons', kind: 'bool' }, num('fireControl', 'auxMaxRangeM', 30, 1500, 'm'), diff --git a/apps/launcher/src/shared/schemas/tuning.ts b/apps/launcher/src/shared/schemas/tuning.ts index d1caa79..1076abc 100644 --- a/apps/launcher/src/shared/schemas/tuning.ts +++ b/apps/launcher/src/shared/schemas/tuning.ts @@ -231,7 +231,15 @@ const GroundAiTurretSchema = z.object({ const GroundAiBehaviorSchema = z.object({ scoreIntervalSec: z.number().min(0.1).max(3), - minHoldSec: z.number().min(0).max(10), + advanceHoldSec: z.number().min(0).max(10), + engageHoldSec: z.number().min(0).max(10), + haltHoldSec: z.number().min(0).max(10), + coverHoldSec: z.number().min(0).max(10), + repositionHoldSec: z.number().min(0).max(10), + postHoldSec: z.number().min(0).max(10), + disperseHoldSec: z.number().min(0).max(10), + targetValueWeight: z.number().min(0).max(1), + nearThreatHaltBonus: z.number().min(0).max(1), switchMargin: z.number().min(0).max(1), advanceScore: z.number().min(0).max(1), engageScore: z.number().min(0).max(1), @@ -249,9 +257,8 @@ const GroundAiBehaviorSchema = z.object({ hullAngleDeg: z.number().min(0).max(45), faceToleranceDeg: z.number().min(3).max(60), faceMinDanger: z.number().min(0).max(2), - faceHaltLimitDeg: z.number().min(10).max(180), reverseTravelAngleDeg: z.number().min(60).max(180), - reverseMaxGoalDistM: z.number().min(0).max(2000), + reverseMaxTurnDistM: z.number().min(0).max(200), reverseMinSpeedMps: z.number().min(0.5).max(10), reverseHoldSec: z.number().min(0).max(20), }); @@ -291,13 +298,18 @@ const GroundAiFireControlSchema = z.object({ enemyReloadSec: z.number().min(0).max(15), fleetingThresholdBonus: z.number().min(0).max(0.5), fleetingLateralMps: z.number().min(0.5).max(15), - bigGunThresholdPenalty: z.number().min(0).max(0.5), + fleetingLookAheadSec: z.number().min(0.1).max(2), + reloadThresholdPenalty: z.number().min(0).max(0.5), + longReloadSec: z.number().min(1).max(60), + lowAmmoRounds: z.number().int().min(1).max(60), + lowAmmoThresholdPenalty: z.number().min(0).max(0.5), + aimSkill: z.number().min(0).max(1), + autocannonMinShotsPerSec: z.number().min(0.5).max(30), retreatThresholdPenalty: z.number().min(0).max(0.6), minShotIntervalSec: z.number().min(0.1).max(5), autocannonAimSlack: z.number().min(1).max(10), burstSec: z.number().min(0.2).max(6), burstPauseSec: z.number().min(0).max(5), - burstRecheckSec: z.number().min(0.05).max(2), autocannonReloadDetectSec: z.number().min(0.1).max(3), auxWeapons: z.boolean(), auxMaxRangeM: z.number().min(30).max(1500), diff --git a/apps/server/src/tuning/ground-ai-tuning.ts b/apps/server/src/tuning/ground-ai-tuning.ts index 411391b..399ab50 100644 --- a/apps/server/src/tuning/ground-ai-tuning.ts +++ b/apps/server/src/tuning/ground-ai-tuning.ts @@ -377,7 +377,15 @@ function readTurretSection(turret: TuningReader): GroundAiTuning['turret'] { function readBehaviorSection(bhv: TuningReader): GroundAiTuning['behavior'] { return { scoreIntervalSec: bhv.number('scoreIntervalSec', { min: 0.1, max: 3 }), - minHoldSec: bhv.number('minHoldSec', { min: 0, max: 10 }), + advanceHoldSec: bhv.number('advanceHoldSec', { min: 0, max: 10 }), + engageHoldSec: bhv.number('engageHoldSec', { min: 0, max: 10 }), + haltHoldSec: bhv.number('haltHoldSec', { min: 0, max: 10 }), + coverHoldSec: bhv.number('coverHoldSec', { min: 0, max: 10 }), + repositionHoldSec: bhv.number('repositionHoldSec', { min: 0, max: 10 }), + postHoldSec: bhv.number('postHoldSec', { min: 0, max: 10 }), + disperseHoldSec: bhv.number('disperseHoldSec', { min: 0, max: 10 }), + targetValueWeight: bhv.number('targetValueWeight', { min: 0, max: 1 }), + nearThreatHaltBonus: bhv.number('nearThreatHaltBonus', { min: 0, max: 1 }), switchMargin: bhv.number('switchMargin', { min: 0, max: 1 }), advanceScore: bhv.number('advanceScore', { min: 0, max: 1 }), engageScore: bhv.number('engageScore', { min: 0, max: 1 }), @@ -395,9 +403,8 @@ function readBehaviorSection(bhv: TuningReader): GroundAiTuning['behavior'] { hullAngleDeg: bhv.number('hullAngleDeg', { min: 0, max: 45 }), faceToleranceDeg: bhv.number('faceToleranceDeg', { min: 3, max: 60 }), faceMinDanger: bhv.number('faceMinDanger', { min: 0, max: 2 }), - faceHaltLimitDeg: bhv.number('faceHaltLimitDeg', { min: 10, max: 180 }), reverseTravelAngleDeg: bhv.number('reverseTravelAngleDeg', { min: 60, max: 180 }), - reverseMaxGoalDistM: bhv.number('reverseMaxGoalDistM', { min: 0, max: 2000 }), + reverseMaxTurnDistM: bhv.number('reverseMaxTurnDistM', { min: 0, max: 200 }), reverseMinSpeedMps: bhv.number('reverseMinSpeedMps', { min: 0.5, max: 10 }), reverseHoldSec: bhv.number('reverseHoldSec', { min: 0, max: 20 }), }; @@ -462,13 +469,18 @@ function readFireControlSection(fc: TuningReader): GroundAiTuning['fireControl'] enemyReloadSec: fc.number('enemyReloadSec', { min: 0, max: 15 }), fleetingThresholdBonus: fc.number('fleetingThresholdBonus', { min: 0, max: 0.5 }), fleetingLateralMps: fc.number('fleetingLateralMps', { min: 0.5, max: 15 }), - bigGunThresholdPenalty: fc.number('bigGunThresholdPenalty', { min: 0, max: 0.5 }), + fleetingLookAheadSec: fc.number('fleetingLookAheadSec', { min: 0.1, max: 2 }), + reloadThresholdPenalty: fc.number('reloadThresholdPenalty', { min: 0, max: 0.5 }), + longReloadSec: fc.number('longReloadSec', { min: 1, max: 60 }), + lowAmmoRounds: fc.int('lowAmmoRounds', { min: 1, max: 60 }), + lowAmmoThresholdPenalty: fc.number('lowAmmoThresholdPenalty', { min: 0, max: 0.5 }), + aimSkill: fc.number('aimSkill', { min: 0, max: 1 }), + autocannonMinShotsPerSec: fc.number('autocannonMinShotsPerSec', { min: 0.5, max: 30 }), retreatThresholdPenalty: fc.number('retreatThresholdPenalty', { min: 0, max: 0.6 }), minShotIntervalSec: fc.number('minShotIntervalSec', { min: 0.1, max: 5 }), autocannonAimSlack: fc.number('autocannonAimSlack', { min: 1, max: 10 }), burstSec: fc.number('burstSec', { min: 0.2, max: 6 }), burstPauseSec: fc.number('burstPauseSec', { min: 0, max: 5 }), - burstRecheckSec: fc.number('burstRecheckSec', { min: 0.05, max: 2 }), autocannonReloadDetectSec: fc.number('autocannonReloadDetectSec', { min: 0.1, max: 3 }), auxWeapons: fc.bool('auxWeapons'), auxMaxRangeM: fc.number('auxMaxRangeM', { min: 30, max: 1500 }), diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index 7e498e9..1e8f6b4 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -346,24 +346,22 @@ "scanPeriodSec": 6.0 }, - // Hull channel (decision layer design, section 7). Every scoreIntervalSec (at once when a target - // appears or is lost, a reload starts or ends, or the bot is hit) each behavior gets a score and - // the best runs; a running one is kept for minHoldSec, then until another scores switchMargin - // more. Scores: advance (no target in sight), engage (target in sight; +urgencyWeight when the - // order is urgent), halt (the trigger asks to stand for its shot; +urgencyWeight when not urgent, - // -crossfirePenalty per extra enemy aiming at the bot), cover (reloading with a known threat; - // +coverDangerWeight x danger, -coverOffensivePenalty on an urgent attack, not again for - // coverRetrySec after no cover was found), reposition (engagement stuck), hold (at the post, - // watching the last exit, waiting at the rally point) and disperse (crowded). Engaging on the - // move slows to the speed the trigger asks for; an urgent order keeps urgentSpeedKeep of the - // march speed. Medium and heavy tanks and tank destroyers face the most dangerous threat (danger - // at least faceMinDanger) angled by hullAngleDeg: holding within faceToleranceDeg, on a short halt - // only when more than faceHaltLimitDeg off. With that threat more than reverseTravelAngleDeg off - // the direction of travel and the goal within reverseMaxGoalDistM, a vehicle reversing at least - // reverseMinSpeedMps drives its route backwards; it switches at most every reverseHoldSec. + // Hull channel: choose a behavior by score, holding each for its configured commitment time + // unless an emergency or a large score difference interrupts it. A cover withdrawal runs + // through its arrival or timeout. A short halt lasts through the weapon's shooting window. + // Tracked tanks and tank destroyers face the main threat at the post or during a halt. + // They can reverse along a short route segment to keep their front toward that threat. "behavior": { "scoreIntervalSec": 0.5, - "minHoldSec": 1.5, + "advanceHoldSec": 1.5, + "engageHoldSec": 1.5, + "haltHoldSec": 3.0, + "coverHoldSec": 2.0, + "repositionHoldSec": 2.0, + "postHoldSec": 1.5, + "disperseHoldSec": 1.5, + "targetValueWeight": 0.1, + "nearThreatHaltBonus": 0.28, "switchMargin": 0.15, "advanceScore": 0.5, "engageScore": 0.55, @@ -381,9 +379,8 @@ "hullAngleDeg": 20.0, "faceToleranceDeg": 15.0, "faceMinDanger": 0.15, - "faceHaltLimitDeg": 60.0, "reverseTravelAngleDeg": 110.0, - "reverseMaxGoalDistM": 200.0, + "reverseMaxTurnDistM": 45.0, "reverseMinSpeedMps": 2.5, "reverseHoldSec": 3.0 }, @@ -396,10 +393,9 @@ // lead uncertainty on a crossing target, with the barrel's current offset as the mean error. // The threshold starts at fireThreshold and drops by aimingThresholdBonus when the target aims // at the bot, by up to closeThresholdBonus inside closeRangeM, by enemyReloadThresholdBonus for - // enemyReloadSec after the target fired, and by fleetingThresholdBonus when it crosses faster - // than fleetingLateralMps partly hidden; it rises by up to bigGunThresholdPenalty for guns above - // 75 mm and by retreatThresholdPenalty while pulling back to cover, and never goes below - // minFireThreshold. Main-gun shots are at least minShotIntervalSec apart. + // enemyReloadSec after the target fired, and by fleetingThresholdBonus if its estimated motion + // will take it out of sight. Longer reloads, scarce ammunition and falling back raise the threshold. + // The pre-fire budget limits ballistic checks per frame. Every firing request gets fresh checks. "fireControl": { "maxEngageRangeM": 1250.0, "closeRangeM": 100.0, @@ -407,19 +403,19 @@ "longRangeM": 800.0, // At or below this speed the bot counts as standing (also the answer "stop" to a speed request). "stopSpeedMaxMps": 0.45, - "longRangeWindowSec": 4.0, + "longRangeWindowSec": 1.0, // Fixed (casemate) guns: how far off the gun may be before the hull is asked to turn. "baseAlignDeg": 0.42, // Outside close range, the rate at which barrel alignment drifts relative to the aim direction. "barrelSettleDegSec": 1.8, - "closeSettleHoldSec": 0.08, - "settleHoldSec": 0.20, - "aimErrorDeg": 0.12, + "closeSettleHoldSec": 0.06, + "settleHoldSec": 0.12, + "aimErrorDeg": 0.07, "moveErrDegPerMps": 0.35, "turnErrDegPerDegSec": 0.03, "stabErrFactor": 0.2, "targetHalfHeightM": 1.0, - "fireThreshold": 0.35, + "fireThreshold": 0.45, "minFireThreshold": 0.1, "aimingThresholdBonus": 0.1, "closeThresholdBonus": 0.15, @@ -427,20 +423,23 @@ "enemyReloadSec": 3.0, "fleetingThresholdBonus": 0.1, "fleetingLateralMps": 3.0, - "bigGunThresholdPenalty": 0.08, + "fleetingLookAheadSec": 0.65, + "reloadThresholdPenalty": 0.08, + "longReloadSec": 15.0, + "lowAmmoRounds": 5, + "lowAmmoThresholdPenalty": 0.08, + "aimSkill": 0.5, + "autocannonMinShotsPerSec": 1.5, "retreatThresholdPenalty": 0.2, "minShotIntervalSec": 0.65, - // Belt-fed autocannons (6.3): fire while within autocannonAimSlack times the target's angular - // half size, in bursts of burstSec with burstPauseSec between, checking barrel, trajectory and - // friendlies again every burstRecheckSec. Not ready for longer than autocannonReloadDetectSec - // counts as a reload. + // Automatic cannons are identified from stock belt and firing-rate data. They fire in bursts + // while within the aim slack. A longer wait between rounds counts as a reload. "autocannonAimSlack": 3.0, "burstSec": 1.2, "burstPauseSec": 0.6, - "burstRecheckSec": 0.3, "autocannonReloadDetectSec": 0.6, - // Secondary cannon and coaxial weapons (6.4) fire bursts alongside the main gun at light - // vehicles within auxMaxRangeM (at any vehicle with auxFireAtArmor). + // Secondary and coaxial guns have their own aim and ballistic checks. The armor toggle allows + // coaxial fire at vehicles outside the light-vehicle filter. "auxWeapons": true, "auxMaxRangeM": 300.0, "auxFireAtArmor": false, diff --git a/game-ai/ground/wto_ai_ammo_common.das b/game-ai/ground/wto_ai_ammo_common.das new file mode 100644 index 0000000..b678370 --- /dev/null +++ b/game-ai/ground/wto_ai_ammo_common.das @@ -0,0 +1,52 @@ +// Ammunition assigned to the selected primary gun by the stock ammunition stowage. +options indenting = 2 +options no_global_heap = true +module wto_ai_ammo_common shared + +require ecs +require math +require DagorMath +require AmmoStowage +require Unit +require Weapon +require %appGame.wtoai.wto_ai_combat_types_common + +[never_inline] +def public wto_main_gun_ammo(gun : WTGun const?; fc : WtoFireState const&) : int + var stored = 0 + for set in gun.properties.bulletSets + stored += max(0, set.bulletsCount) + let stockCount = fc.rackTurret == fc.turretNo ? fc.rackRounds : -1 + if stockCount < 0 && stored == 0 + return -1 + return max(max(stockCount, stored), int(gun.currentLoadedAmmoCount)) + +def private wto_ammo_type_for_mount(unit : Unit const?; turret : int; first, end : int; weapons : IntList const&) : bool + for i in range(max(0, first), min(length(weapons), end)) + let weapon = get_weapon(unit.weap.Weapons, weapons[i]) + if weapon != null && int(weapon.turretNo) == turret + return true + return false + +[never_inline] +def public wto_ammo_sample(unit : Unit const?; ammoState : uint; types : IPoint4List const&; + weapons : IntList const&; slots : UInt32List const&; counts : IPoint2List const&; + var fc : WtoFireState&) + if fc.turretNo < 0 + return + fc.rackTurret = fc.turretNo + fc.rackRounds = -1 + for i in range(WTO_MAX_SHELL_PROFILES) + fc.rackBySet[i] = 0 + let distinctTypes = (ammoState & uint(AmmoState.ENABLE_PER_AMMO_TYPES)) != 0u + for ammoType in range(length(types)) + let remap = types[ammoType] + if !wto_ammo_type_for_mount(unit, fc.turretNo, remap.y, remap.z, weapons) + continue + var rounds = 0 + for i in range(min(length(slots), length(counts))) + if int(slots[i] & 0xffu) == ammoType + rounds += max(0, counts[i].x) + fc.rackRounds = max(0, fc.rackRounds) + rounds + if distinctTypes && remap.w >= 0 && remap.w < WTO_MAX_SHELL_PROFILES + fc.rackBySet[remap.w] += rounds diff --git a/game-ai/ground/wto_ai_behavior_common.das b/game-ai/ground/wto_ai_behavior_common.das index a145a57..86bd3e2 100644 --- a/game-ai/ground/wto_ai_behavior_common.das +++ b/game-ai/ground/wto_ai_behavior_common.das @@ -1,9 +1,5 @@ -// Hull channel behavior choice (decision layer design, 7.2): every behavior gets a 0-1 score from -// the order, the threat table, the bot's own state and the other channels' requests; the best one -// runs. A chosen behavior is kept for at least behavior.minHoldSec and afterwards until another -// scores behavior.switchMargin higher, unless it ends by itself or can no longer run. Scoring -// happens every behavior.scoreIntervalSec and at once when a target comes into sight or is lost, -// a reload starts or ends, or the bot is hit (a hit also lifts the minimum hold). +// Hull channel behavior choice from the order, threats, vehicle state and weapon requests. +// Actions own their completion conditions. Critical threats and hits can interrupt a commitment. options indenting = 2 options no_global_heap = true module wto_ai_behavior_common shared @@ -15,6 +11,8 @@ require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_order_common require %appGame.wtoai.wto_ai_combat_types_common require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_threat_common +require %appGame.wtoai.wto_ai_facing_common // What one tactics tick knows, built once (wto_ai_tactics_common.das) and read by the scores and // the behaviors. threatPos: the most dangerous known threat, else the remembered target, else the @@ -28,12 +26,15 @@ struct public WtoBhvCtx threatDir : float3 = float3(1.0, 0.0, 0.0) topDanger : float = 0.0 aimingCount : int = 0 + nearThreat : bool = false + targetValue : float = 0.0 baseGoal : float3 = float3(0.0, 0.0, 0.0) distGoal : float = 0.0 atGoal : bool = false urgent : bool = false offensive : bool = false haltWanted : bool = false + turnWanted : bool = false stopRangeOk : bool = false stale : bool = false crowded : bool = false @@ -86,12 +87,17 @@ def public wto_bhv_context(world : WtoWorldSnap const&; now : float; myPos, hull c.topDanger = slot.threat.entries[top].danger c.threatDir = wto_xz_normalize(c.threatPos - myPos, hullFwd) for i in range(slot.threat.count) - if slot.threat.entries[i].aiming && slot.threat.entries[i].seesMe + assume entry = slot.threat.entries[i] + if entry.aiming && entry.seesMe c.aimingCount++ - c.urgent = slot.order.urgency == WTO_URGENCY_HIGH || c.distGoal > 130.0 + c.nearThreat = c.nearThreat || entry.dist <= WTO_AI_FC_CLOSE_RANGE_M + c.urgent = slot.order.valid && slot.order.urgency == WTO_URGENCY_HIGH c.offensive = wto_order_is_offensive(slot.order.role) + c.targetValue = min(1.0, wto_threat_danger_of(slot, p.targetEid)) * slot.trigger.hitProbAligned assume tr = slot.trigger - c.haltWanted = (now - tr.wantSpeedAt) <= WTO_AI_TACTICS_TICK_SEC * 3.0 && tr.wantSpeedMps <= WTO_AI_FC_STOP_SPEED_MAX_MPS + let requestFresh = (now - tr.wantSpeedAt) <= WTO_AI_TACTICS_TICK_SEC * 3.0 + c.haltWanted = requestFresh && tr.targetEid == p.targetEid && slot.fire.gunReady && !slot.spec.isAutocannon && tr.wantSpeedMps <= WTO_AI_FC_STOP_SPEED_MAX_MPS + c.turnWanted = !slot.fire.reloading && wto_face_has_request(slot) c.stopRangeOk = c.hasTarget && wto_bhv_stop_range_ok(c.distTarget, slot) c.stale = stale c.crowded = slot.crowd.isCrowded @@ -121,14 +127,18 @@ def private wto_bhv_scores(now : float; c : WtoBhvCtx const&; slot : WtoBotSlot for i in range(WTO_BHV_COUNT) s[i] = 0.0 let urgentF = c.urgent ? 1.0 : 0.0 - if !c.atGoal + if !c.atGoal && c.holdReason != WTO_HOLD_RALLY s[WTO_BHV_ADVANCE] = c.hasTarget ? 0.0 : WTO_AI_BHV_ADVANCE - s[WTO_BHV_ENGAGE] = c.hasTarget ? (WTO_AI_BHV_ENGAGE + WTO_AI_BHV_URGENCY_W * urgentF) : 0.0 - if c.hasTarget && c.haltWanted && c.stopRangeOk && !c.atGoal && now >= slot.tactics.shortHaltCooldownUntil + if c.hasTarget + s[WTO_BHV_ENGAGE] = WTO_AI_BHV_ENGAGE + WTO_AI_BHV_URGENCY_W * urgentF + WTO_AI_BHV_TARGET_VALUE_W * c.targetValue + let halting = slot.tactics.behavior == WTO_BHV_HALT && slot.tactics.state == WTO_STATE_SHORT_HALT + let haltRequest = c.haltWanted || c.turnWanted || halting + if haltRequest && c.stopRangeOk && !c.atGoal && now >= slot.tactics.shortHaltCooldownUntil let crossfire = float(max(0, c.aimingCount - 1)) - s[WTO_BHV_HALT] = WTO_AI_BHV_HALT + WTO_AI_BHV_URGENCY_W * (1.0 - urgentF) - WTO_AI_BHV_CROSSFIRE * crossfire + let nearBonus = c.nearThreat ? WTO_AI_BHV_NEAR_HALT_BONUS : 0.0 + s[WTO_BHV_HALT] = WTO_AI_BHV_HALT + WTO_AI_BHV_URGENCY_W * (1.0 - urgentF) + nearBonus - WTO_AI_BHV_CROSSFIRE * crossfire let coverRetry = now - slot.tactics.coverFailedAt >= WTO_AI_BHV_COVER_RETRY_SEC - if slot.fire.reloading && (c.hasTarget || c.remembered) && !slot.spec.isAutocannonBelt && coverRetry + if slot.fire.reloading && (c.hasTarget || c.remembered) && !slot.spec.isAutocannon && coverRetry let pushing = c.offensive && c.urgent ? 1.0 : 0.0 s[WTO_BHV_COVER] = WTO_AI_BHV_COVER + WTO_AI_BHV_COVER_DANGER_W * min(1.0, c.topDanger) - WTO_AI_BHV_COVER_OFFENSIVE * pushing if c.stale || slot.tactics.repositionActive @@ -137,6 +147,8 @@ def private wto_bhv_scores(now : float; c : WtoBhvCtx const&; slot : WtoBotSlot s[WTO_BHV_HOLD] = WTO_AI_BHV_HOLD if (c.crowded || now < slot.tactics.disperseUntil) && c.distTarget > WTO_AI_FC_CLOSE_RANGE_M s[WTO_BHV_DISPERSE] = WTO_AI_BHV_DISPERSE + for i in range(WTO_BHV_COUNT) + s[i] = clamp(s[i], 0.0, 1.0) def private wto_bhv_best(s : float[9] const&; skip : int; var bestScore, secondScore : float&; var second : int&) : int var best = WTO_BHV_ADVANCE @@ -156,19 +168,38 @@ def private wto_bhv_best(s : float[9] const&; skip : int; var bestScore, secondS second = i return best -// Scores now if due (or `force`, after the running behavior ended itself: it is then left out), -// and switches when the commitment allows it. +def private wto_bhv_hold_sec(bhv : int) : float + if bhv == WTO_BHV_ADVANCE + return WTO_AI_BHV_ADVANCE_HOLD_SEC + if bhv == WTO_BHV_ENGAGE + return WTO_AI_BHV_ENGAGE_HOLD_SEC + if bhv == WTO_BHV_HALT + return WTO_AI_BHV_HALT_HOLD_SEC + if bhv == WTO_BHV_COVER + return WTO_AI_BHV_COVER_HOLD_SEC + if bhv == WTO_BHV_REPOSITION + return WTO_AI_BHV_REPOSITION_HOLD_SEC + if bhv == WTO_BHV_HOLD + return WTO_AI_BHV_POST_HOLD_SEC + if bhv == WTO_BHV_DISPERSE + return WTO_AI_BHV_DISPERSE_HOLD_SEC + return 0.0 + +// The retreat action owns movement until arrival or timeout. Damage handling runs before this. [never_inline] def public wto_bhv_choose(now : float; c : WtoBhvCtx const&; force : bool; var slot : WtoBotSlot&) assume tac = slot.tactics - let hit = slot.perceive.lastDamagedAt > tac.scoredDamageAt - let due = (force || hit || now >= tac.nextScoreAt || c.hasTarget != tac.scoredHasTarget || + if !force && tac.behavior == WTO_BHV_COVER && tac.state == WTO_STATE_RETREAT_COVER + return + let emergency = slot.perceive.lastDamagedAt > tac.scoredDamageAt || (c.nearThreat && !tac.scoredNearThreat) + let due = (force || emergency || now >= tac.nextScoreAt || c.hasTarget != tac.scoredHasTarget || slot.fire.reloading != tac.scoredReloading) if !due return tac.nextScoreAt = now + WTO_AI_BHV_SCORE_SEC tac.scoredHasTarget = c.hasTarget tac.scoredReloading = slot.fire.reloading + tac.scoredNearThreat = c.nearThreat tac.scoredDamageAt = slot.perceive.lastDamagedAt var s : float[9] wto_bhv_scores(now, c, slot, s) @@ -177,12 +208,12 @@ def public wto_bhv_choose(now : float; c : WtoBhvCtx const&; force : bool; var s var second = -1 let best = wto_bhv_best(s, force ? tac.behavior : -1, bestScore, secondScore, second) let cur = tac.behavior - let curScore = (cur >= 0 && cur < WTO_BHV_COUNT) ? s[cur] : 0.0 + let curScore = s[cur] tac.behaviorScore = curScore if best == cur || bestScore <= 0.0 return - let held = (now - tac.behaviorSince) < WTO_AI_BHV_MIN_HOLD_SEC && !hit - if !force && curScore > 0.0 && (held || bestScore < curScore + WTO_AI_BHV_SWITCH_MARGIN) + let held = (now - tac.behaviorSince) < wto_bhv_hold_sec(cur) + if !force && curScore > 0.0 && held && !emergency && bestScore < curScore + WTO_AI_BHV_SWITCH_MARGIN return if WTO_AI_DIAG_TELEMETRY let secondName = second >= 0 ? wto_bhv_name(second) : "-" diff --git a/game-ai/ground/wto_ai_combat_types_common.das b/game-ai/ground/wto_ai_combat_types_common.das index 89a9ad0..d173e47 100644 --- a/game-ai/ground/wto_ai_combat_types_common.das +++ b/game-ai/ground/wto_ai_combat_types_common.das @@ -88,6 +88,7 @@ struct public WtoPerceiveState lookAroundUntil : float = -100.0 // When the engaged target was last seen firing (it is likely reloading for a while after). targetShotAt : float = -100.0 + targetFleeting : bool = false // One discovered enemy in the bot's threat table (decision layer design, section 4). `seen`: seen // clearly (fireable); `seesMe`: in line of sight this tick; `aiming`: its hull points at the bot or @@ -118,13 +119,13 @@ struct public WtoTurretState lookEid : EntityId = INVALID_ENTITY_ID holdUntil : float = -100.0 -// Trigger channel (decision layer design, section 6). hitProb / threshold: the last estimate for -// the main weapon (hitProbAligned: the same with the barrel on target); aimSlackDeg: how far off -// an autocannon may be and still fire; wantSpeedMps: the highest own speed at which the shot -// would reach the threshold (99 = no limit, 0 = only standing), a request the hull channel -// weighs. biasEpoch changes the aiming bias once per shooting opportunity (per shot, or per -// autocannon burst). burst*: the autocannon's current burst and pause; coax*: the same for the -// secondary and coaxial weapons, coaxBlocked a bit per weapon group failing its last check. +[safe_when_uninitialized] +struct public WtoWeaponBurst + untilAt : float = -100.0 + pauseUntil : float = -100.0 + lastShotAt : float = -100.0 + +// The main gun's hit estimate and speed request, plus independent burst timers. [safe_when_uninitialized] struct public WtoTriggerState hitProb : float = 0.0 @@ -133,16 +134,13 @@ struct public WtoTriggerState aimSlackDeg : float = 1.0 wantSpeedMps : float = 99.0 wantSpeedAt : float = -100.0 + targetEid : EntityId = INVALID_ENTITY_ID biasEpoch : int = 0 burstUntil : float = -100.0 burstPauseUntil : float = -100.0 - burstCheckedUntil : float = -100.0 - coaxBurstUntil : float = -100.0 - coaxPauseUntil : float = -100.0 - coaxCheckedUntil : float = -100.0 - coaxBlocked : int = 0 - coaxShots : int = 0 - lastLogAt : float = -100.0 + secondary : WtoWeaponBurst = WtoWeaponBurst() + coaxial : WtoWeaponBurst = WtoWeaponBurst() + auxShots : int = 0 [safe_when_uninitialized] struct public WtoGunTraverse @@ -152,6 +150,15 @@ struct public WtoGunTraverse hasPitchTable : bool = false pitchSector : float4 = float4(1.0, 0.0, 1.0, 0.0) +[safe_when_uninitialized] +struct public WtoMountFire + shellHash : uint = 0u + shellValid : bool = false + automatic : bool = false + shell : WtoShellProfile = WtoShellProfile() + traverseReady : bool = false + traverse : WtoGunTraverse = WtoGunTraverse() + [safe_when_uninitialized] struct public WtoFireState turretNo : int = -1 @@ -164,6 +171,11 @@ struct public WtoFireState gunDamaged : bool = false notReadySince : float = -100.0 loadedBulletIdx : int = -1 + ammoRemaining : int = -1 + rackTurret : int = -1 + rackRounds : int = -1 + rackBySet : int[12] + mounts : WtoMountFire[16] activeSpeedMps : float = 880.0 activeDragCx : float = 0.35 activeMassKg : float = 10.0 diff --git a/game-ai/ground/wto_ai_drive_common.das b/game-ai/ground/wto_ai_drive_common.das index a9fa33d..d3b7864 100644 --- a/game-ai/ground/wto_ai_drive_common.das +++ b/game-ai/ground/wto_ai_drive_common.das @@ -127,10 +127,11 @@ def private wto_compute_reverse_axes(cmd : WtoDriveCmd const&; spec : WtoVehicle // Coordinate-free signed rear angle: >0 means desired rear travel lies toward hull LEFT (+Z). let rearErr = atan2(dot(wishRear, left), dot(wishRear, rear)) outStr = clamp(rearErr * 1.45 + omega * 0.28, -1.0, 1.0) * WTO_AI_NAV_STEER_SIGN - let maxSafeRev = min(spec.vMaxRev, sqrt(max(1.0, (cmd.rearClearM - 1.8) * 2.2))) - let vTarget = -clamp(cmd.speedMps, 1.2, max(1.4, maxSafeRev)) - let vErr = vTarget - vFwd - outThr = vErr < -0.15 ? clamp(-0.52 + vErr * 0.32, -1.0, -0.35) : -0.28 + let clearanceCap = sqrt(max(0.0, (cmd.rearClearM - 1.8) * 2.2)) + let vTarget = min(cmd.speedMps, min(spec.vMaxRev, clearanceCap)) + let response = (vTarget + vFwd) / WTO_AI_NAV_MOVING_FIRE_SPEED_RAMP_MPS + outThr = -clamp(response, 0.0, 1.0) + outBrk = clamp(-response, 0.0, 1.0) [never_inline] def private wto_compute_cruise_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleSpec const&; diff --git a/game-ai/ground/wto_ai_estimate_common.das b/game-ai/ground/wto_ai_estimate_common.das index cc94929..b496246 100644 --- a/game-ai/ground/wto_ai_estimate_common.das +++ b/game-ai/ground/wto_ai_estimate_common.das @@ -6,6 +6,7 @@ module wto_ai_estimate_common shared require ecs require math +require Ballistics require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_combat_types_common @@ -91,30 +92,37 @@ def public wto_est_on_los_lost(now : float; selfEid : EntityId; var p : WtoPerce if WTO_AI_DIAG_TELEMETRY print("WTO_AI|WATCH|eid={uint(selfEid)}|tgt={uint(p.targetEid)}|dur={dur}\n") +// The same estimated target motion is used to lead and to validate the real barrel shot. +def public wto_est_target_vel(p : WtoPerceiveState const&) : float3 + let scale = p.sampleCount >= 2 ? clamp(0.35 + 0.65 * p.velQuality, 0.0, 1.0) : 0.0 + return p.estVel * scale + +def public wto_shot_drag(dragCx, massKg, caliberM : float) : float + let area = 0.25 * WTO_PI * caliberM * caliberM + return 0.5 * 1.225 * dragCx * area / max(0.1, massKg) + +def private wto_est_avg_speed(speedMps, drag, dist : float) : float + let dragDist = min(drag * dist, 60.0) + if dragDist <= 1.0e-4 + return max(120.0, speedMps) + return max(120.0, speedMps * (dragDist / (exp(dragDist) - 1.0))) + [never_inline] -def public wto_est_compute_biased_lead(muzzlePos, myVel, aimBase : float3; - var slot : WtoBotSlot&; - var outLeadPt : float3&) : float +def private wto_est_compute_biased_lead(muzzlePos, myVel, aimBase : float3; speedMps, drag : float; + var slot : WtoBotSlot&; var outLeadPt : float3&) : float assume p = slot.perceive let rawDelta = aimBase - muzzlePos let rawDist = length(rawDelta) - let dragLoss = clamp(slot.fire.activeDragCx * 0.00011 * rawDist, 0.0, 0.28) - let vEff = max(120.0, slot.fire.activeSpeedMps * (1.0 - dragLoss)) - - // Lead uses ONLY our own visual velocity estimate, scaled by observation quality. - let leadScale = p.sampleCount >= 2 ? clamp(0.35 + 0.65 * p.velQuality, 0.0, 1.0) : 0.0 - let usedVel = p.estVel * leadScale + let vEff = wto_est_avg_speed(speedMps, drag, rawDist) + let usedVel = wto_est_target_vel(p) var leadPt = aimBase var tof = 0.0 for _iter in range(2) tof = clamp(length(leadPt - muzzlePos) / vEff, 0.0, 3.5) - leadPt = aimBase + usedVel * tof - myVel * (tof * 0.85) + leadPt = aimBase + (usedVel - myVel) * tof - // Sample bounded natural bias ONCE per shooting opportunity (target + shot + state + 12m grid). - let gx = uint(int(muzzlePos.x / 12.0) + 4096) - let gz = uint(int(muzzlePos.z / 12.0) + 4096) - let key = (uint(p.targetEid) ^ (uint(slot.trigger.biasEpoch) * 2654435761u) ^ - (uint(slot.tactics.state) * 40503u) ^ (gx * 73856093u) ^ (gz * 19349663u)) + // Keep the same bias until the target, shot opportunity or velocity estimate changes. + let key = uint(p.targetEid) ^ (uint(slot.trigger.biasEpoch) * 2654435761u) if !p.oppSeeded || p.oppKey != key p.oppKey = key p.oppSeeded = true @@ -125,10 +133,28 @@ def public wto_est_compute_biased_lead(muzzlePos, myVel, aimBase : float3; // Error envelope shrinks naturally as observation quality converges. let tgtSpd = length(p.estVel) let leadSpread = tgtSpd * tof * WTO_AI_EST_LEAD_ERR_FRAC * (1.0 - 0.72 * p.velQuality) - let distSpread = WTO_AI_EST_BASE_SIGMA_M * clamp(rawDist / 350.0, 0.25, 2.6) * (1.2 - 0.55 * p.velQuality) + let distSpread = (1.0 - WTO_AI_FC_AIM_SKILL) * WTO_AI_EST_BASE_SIGMA_M * clamp(rawDist / 350.0, 0.25, 2.6) * (1.2 - 0.55 * p.velQuality) let latOff = clamp((leadSpread + distSpread) * p.oppBiasU, -WTO_AI_EST_MAX_BIAS_M, WTO_AI_EST_MAX_BIAS_M) let vertOff = clamp(distSpread * 0.65 * p.oppBiasV, -WTO_AI_EST_MAX_BIAS_M * 0.5, WTO_AI_EST_MAX_BIAS_M * 0.5) let toAimXZ = wto_xz_normalize(rawDelta, float3(1.0, 0.0, 0.0)) let latAxis = float3(-toAimXZ.z, 0.0, toAimXZ.x) outLeadPt = leadPt + latAxis * latOff + float3(0.0, vertOff, 0.0) return rawDist + +[never_inline] +def public wto_solve_ballistic_aim(muzzlePos, myVel, aimBase : float3; speedMps, dragCx, massKg, caliberM : float; + var slot : WtoBotSlot&; var outAimPt, outWishDir : float3&) : float + var leadPt = aimBase + let drag = wto_shot_drag(dragCx, massKg, caliberM) + let rawDist = wto_est_compute_biased_lead(muzzlePos, myVel, aimBase, speedMps, drag, slot, leadPt) + let vEff = wto_est_avg_speed(speedMps, drag, rawDist) + outAimPt = leadPt + var arcDir = float3(0.0, 0.0, 0.0) + if calculate_arc_low_start_dir(muzzlePos, leadPt, vEff, arcDir) && length_sq(arcDir) > 0.25 + outWishDir = normalize(arcDir) + else + let d = max(1.0, length(leadPt - muzzlePos)) + let tof = d / vEff + let dropComp = float3(0.0, 0.5 * 9.81 * tof * tof, 0.0) + outWishDir = normalize(leadPt + dropComp - muzzlePos) + return rawDist diff --git a/game-ai/ground/wto_ai_facing_common.das b/game-ai/ground/wto_ai_facing_common.das index 95f34ab..73c5c25 100644 --- a/game-ai/ground/wto_ai_facing_common.das +++ b/game-ai/ground/wto_ai_facing_common.das @@ -1,9 +1,4 @@ -// Facing constraint of the hull channel (decision layer design, 7.3). Until penetration can be -// estimated, medium tanks, heavy tanks and tank destroyers turn the front toward the most dangerous -// known threat, angled by behavior.hullAngleDeg to the side nearer the current heading; light -// vehicles and SPAA are not bound. A target outside the gun's traverse overrides this for every -// vehicle (the hull turns the gun onto it). While advancing toward a nearby goal with the threat -// behind the direction of travel, the bot drives the route backwards instead of showing its rear. +// Hull facing and the direction of travel along a navigation corridor. options indenting = 2 options no_global_heap = true module wto_ai_facing_common shared @@ -15,9 +10,11 @@ require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_combat_types_common require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_nav_types_common +require %appGame.wtoai.wto_ai_follow_common +require %appGame.wtoai.wto_ai_drive_common -def private wto_face_bound_role(role : int) : bool - return role == WTO_ROLE_MEDIUM || role == WTO_ROLE_HEAVY || role == WTO_ROLE_TD +def private wto_face_bound(spec : WtoVehicleSpec const&) : bool + return spec.isTracked && (spec.role == WTO_ROLE_MEDIUM || spec.role == WTO_ROLE_HEAVY || spec.role == WTO_ROLE_TD) def private wto_face_rotate(dir : float3; rad : float) : float3 return float3(dir.x * cos(rad) - dir.z * sin(rad), 0.0, dir.x * sin(rad) + dir.z * cos(rad)) @@ -42,42 +39,70 @@ def private wto_face_threat_pos(now : float; slot : WtoBotSlot const&; var outPo return true return false -// Per tactics tick, before the behaviors run. +// The turret can request a turn for a visible target that is outside the mount traverse. +def public wto_face_has_request(slot : WtoBotSlot const&) : bool + let target = slot.fire.hullAimTarget + if !target || !slot.perceive.hasClearLos || target != slot.perceive.targetEid || slot.tactics.immobilized + return false + return wto_pivot_drive_mode(slot.spec, slot.nav.frontClearM, slot.nav.rearClearM, true) != WTO_DRIVE_HALT + [never_inline] def public wto_face_update(now : float; myPos, hullFwd : float3; var slot : WtoBotSlot&) assume tac = slot.tactics tac.faceActive = false tac.faceFromThreat = false - if !!slot.fire.hullAimTarget && slot.fire.hullAimTarget == slot.perceive.targetEid - tac.faceDir = wto_xz_normalize(slot.fire.hullAimDir, hullFwd) - tac.faceActive = true - return + tac.faceForGun = false + if !slot.perceive.hasClearLos || tac.gunFacingTarget != slot.perceive.targetEid + tac.gunFacingTarget = INVALID_ENTITY_ID var threatPos = myPos - if !wto_face_bound_role(slot.spec.role) || !wto_face_threat_pos(now, slot, threatPos) + if !wto_face_bound(slot.spec) || !wto_face_threat_pos(now, slot, threatPos) return tac.faceThreatDir = wto_xz_normalize(threatPos - myPos, hullFwd) tac.faceDir = wto_face_angled(tac.faceThreatDir, hullFwd) tac.faceActive = true tac.faceFromThreat = true -// Whether to drive the route backwards this tick (advancing or engaging toward a goal within -// behavior.reverseMaxGoalDistM with the faced threat more than reverseTravelAngleDeg off the -// direction of travel). A decision is kept for at least behavior.reverseHoldSec. +// A standing action can keep the hull facing its gun's target if the strongest threat remains in front. [never_inline] -def public wto_face_reverse_update(now, distGoal : float; var slot : WtoBotSlot&) +def public wto_face_accept_gun(hullFwd : float3; var slot : WtoBotSlot&) assume tac = slot.tactics + if !wto_face_has_request(slot) && !tac.gunFacingTarget + return + let wanted = wto_xz_normalize(slot.fire.hullAimDir, hullFwd) + let allowedAngle = min(90.0, WTO_AI_BHV_HULL_ANGLE_DEG + WTO_AI_BHV_FACE_TOL_DEG) + if tac.faceFromThreat && dot(wanted, tac.faceThreatDir) < cos(allowedAngle * WTO_DEG_TO_RAD) + tac.gunFacingTarget = INVALID_ENTITY_ID + return + tac.gunFacingTarget = slot.perceive.targetEid + tac.faceDir = wanted + tac.faceActive = true + tac.faceForGun = true + +def public wto_face_side_exposed(slot : WtoBotSlot const&) : bool + assume tac = slot.tactics + if !tac.faceFromThreat + return false + let travel = wto_xz_normalize(slot.nav.steerDir, tac.faceThreatDir) + return abs(dot(travel, tac.faceThreatDir)) < sin(WTO_AI_BHV_FACE_TOL_DEG * WTO_DEG_TO_RAD) + +// Choose steering direction after tracking the active corridor and before updating traffic. +[never_inline] +def public wto_face_reverse_update(now : float; myPos, hullFwd : float3; var slot : WtoBotSlot&) + assume tac = slot.tactics + assume rt = slot.route let moving = tac.behavior == WTO_BHV_ADVANCE || tac.behavior == WTO_BHV_ENGAGE - let able = slot.spec.vMaxRev >= WTO_AI_BHV_REVERSE_MIN_MPS && !slot.tactics.immobilized - var want = moving && able && tac.faceFromThreat && distGoal <= WTO_AI_BHV_REVERSE_MAX_GOAL_M + let able = slot.spec.vMaxRev >= WTO_AI_BHV_REVERSE_MIN_MPS && !tac.immobilized + var want = moving && able && tac.faceFromThreat && rt.corridorLen >= 2 if want - let travel = wto_xz_normalize(slot.nav.steerDir, tac.faceThreatDir) - let offDeg = acos(clamp(dot(travel, tac.faceThreatDir), -1.0, 1.0)) * WTO_RAD_TO_DEG - want = offDeg >= WTO_AI_BHV_REVERSE_ANGLE_DEG + let seg = clamp(rt.segIdx, 0, rt.corridorLen - 2) + let travel = wto_xz_normalize(rt.corridor[seg + 1] - rt.corridor[seg], hullFwd) + let opposite = dot(travel, tac.faceThreatDir) <= cos(WTO_AI_BHV_REVERSE_ANGLE_DEG * WTO_DEG_TO_RAD) + want = opposite && wto_follow_near_turn(rt, myPos, WTO_AI_BHV_REVERSE_MAX_TURN_M) if want == tac.reverseTravel return - if (now - tac.reverseSince) < WTO_AI_BHV_REVERSE_HOLD_SEC && moving + if want && (now - tac.reverseSince) < WTO_AI_BHV_REVERSE_HOLD_SEC return tac.reverseTravel = want tac.reverseSince = now if WTO_AI_DIAG_TELEMETRY - print("WTO_AI|REVERSE_TRAVEL|t={now}|eid={uint(slot.eid)}|on={want}|goal={distGoal}\n") + print("WTO_AI|REVERSE_TRAVEL|t={now}|eid={uint(slot.eid)}|on={want}\n") diff --git a/game-ai/ground/wto_ai_fire_aux_common.das b/game-ai/ground/wto_ai_fire_aux_common.das index 56b48c4..af55b90 100644 --- a/game-ai/ground/wto_ai_fire_aux_common.das +++ b/game-ai/ground/wto_ai_fire_aux_common.das @@ -1,9 +1,4 @@ -// Secondary cannon and coaxial weapons (decision layer design, 6.4): each weapon group decides for -// itself, alongside the main gun, so they can fire in the same moment. They fire bursts at the -// engaged target while their own barrel is within the aim slack of it, at light vehicles (any -// vehicle with fireControl.auxFireAtArmor) within fireControl.auxMaxRangeM. Before a burst and -// every burstRecheckSec, each group's straight line from its own muzzle is checked for hard cover -// and friendlies; a group that fails is held until the next check. +// Secondary and coaxial guns have their own aim solution, readiness, burst timer and safety checks. options indenting = 2 options no_global_heap = true module wto_ai_fire_aux_common shared @@ -16,99 +11,138 @@ require Unit require Weapon require %game.utils.utils_common require %appGame.wtoai.wto_ai_config_common -require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_combat_types_common require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_world_common -require %appGame.wtoai.wto_ai_sight_common +require %appGame.wtoai.wto_ai_estimate_common require %appGame.wtoai.wto_ai_trigger_common -require %appGame.wtoai.wto_ai_fire_gate_common +require %appGame.wtoai.wto_ai_traverse_common +require %appGame.wtoai.wto_ai_weapon_profile_common +require %appGame.wtoai.wto_ai_fire_checks_common -let private AUX_SECONDARY_BIT = 1 -let private AUX_COAXIAL_BIT = 2 +def private wto_aux_in_range(dist : float) : bool + return WTO_AI_FC_AUX_ENABLED && dist <= min(WTO_AI_FC_AUX_MAX_RANGE_M, WTO_AI_FC_MAX_RANGE_M) + +def private wto_aux_group(groupNo : int) : bool + return groupNo == int(WeaponTriggerGroups.TRIGGER_GROUP_SECONDARY) || groupNo == int(WeaponTriggerGroups.TRIGGER_GROUP_COAXIAL_GUN) -// The group's first working weapon that is ready to fire: its muzzle and barrel direction. [never_inline] -def private wto_aux_ready_barrel(unit : Unit const?; group : WeaponTriggerGroups; var outPos, outDir : float3&) : bool - var found = false +def public wto_fire_aux_aim(var unit : Unit?; className : string; dt, dist : float; var slot : WtoBotSlot&) : bool + if !wto_aux_in_range(dist) + return false + var changed = false + for tIdx, turret in iter_range(unit.weap.turret), unit.weap.turret + if !wto_aux_group(int(turret.triggerGroupNo)) || tIdx >= length(slot.fire.mounts) + continue + let weapon = get_weapon(unit.weap.Weapons, int(turret.triggerNo), int(turret.weaponIndex)) + if weapon == null || weapon.isDummyGun || weapon.prop.launcher + continue + let gun = as_gun(weapon) + assume mount = slot.fire.mounts[tIdx] + if gun == null || gun.isInoperable || !wto_mount_load_shell(unit, className, tIdx, gun, mount) + continue + var gunTm : float3x4 + weapon_calcShootTm(weapon, unit.unitTm, gunTm) + if length_sq(gunTm[0]) <= 0.25 + continue + let base = slot.perceive.visibleAimPt + var aimPt = base + var direction = gunTm[0] + let _range = wto_solve_ballistic_aim(gunTm[3], unit.vel, base, mount.shell.speedMps, mount.shell.dragCx, mount.shell.massKg, mount.shell.caliberM, slot, aimPt, direction) + if wto_aim_aux_mount(unit, className, dt, tIdx, direction, mount) + changed = true + return changed + +[never_inline] +def private wto_aux_check_barrel(world : WtoWorldSnap const&; unit : Unit const?; weapon : Weapon const?; + now, dist : float; target : WtoUnitSnap const&; mount : WtoMountFire const&; + var slot : WtoBotSlot&) : bool + var gunTm : float3x4 + weapon_calcShootTm(weapon, unit.unitTm, gunTm) + if length_sq(gunTm[0]) <= 0.25 + return false + let actual = normalize(gunTm[0]) + let base = slot.perceive.visibleAimPt + var aimPt = base + var direction = actual + let _range = wto_solve_ballistic_aim(gunTm[3], unit.vel, base, mount.shell.speedMps, mount.shell.dragCx, mount.shell.massKg, mount.shell.caliberM, slot, aimPt, direction) + let error = wto_trig_aim_error(actual, direction) + if !wto_trig_aux_aim_ok(now, dist, length(unit.vel), error, unit.pos, target, mount, slot) + return false + var blockCode = WTO_BLOCK_NONE + return wto_fire_check_barrel(world, unit, slot, gunTm[3], actual, aimPt, mount.shell, !mount.automatic, blockCode) == WTO_DENY_OK + +// Count all guns the native trigger would fire, including barrels without a usable turret entry. +def private wto_aux_ready_count(unit : Unit const?; group : WeaponTriggerGroups) : int + var ready = 0 + var supported = true get_weapons_by_trigger_group(unit.weap.Weapons, group) <| $(weapons : array const#) for i in range(length(weapons)) - if found - break assume weapon = weapons[i] if weapon == null || weapon.isDummyGun continue let gun = as_gun(weapon) - if gun == null || gun.isInoperable || !gun.isReadyToShoot - continue - var tm : float3x4 - weapon_calcShootTm(weapon, unit.unitTm, tm) - if length_sq(tm[0]) > 0.25 - outPos = tm[3] - outDir = normalize(tm[0]) - found = true - return found + if weapon.prop.launcher || gun == null + supported = false + elif !gun.isInoperable && gun.isReadyToShoot + ready++ + return supported ? ready : 0 -// Hard cover or a friendly on the straight line from the group's muzzle (or no ready weapon). [never_inline] -def private wto_aux_blocked(world : WtoWorldSnap const&; unit : Unit const?; group : WeaponTriggerGroups; - aimPt : float3; slot : WtoBotSlot const&) : bool - var muzzle = unit.pos - var dir = unit.unitTm[0] - if !wto_aux_ready_barrel(unit, group, muzzle, dir) - return true - if wto_sight_hard_segment_blocked(world, slot.eid, slot.perceive.targetEid, muzzle, aimPt, 0.05, 0.35, 0.65) != WTO_BLOCK_NONE - return true - let flightSec = length(aimPt - muzzle) / 900.0 - return !wto_gate_friendly_segment_clear(world, slot.eid, slot.army, muzzle, aimPt, flightSec * 0.5) - -// Fires the group once when its ready barrel is within the aim slack and it passed the last check. -[never_inline] -def private wto_aux_fire_group(var unit : Unit?; group : WeaponTriggerGroups; bit : int; aimPt : float3; - var slot : WtoBotSlot&) - assume tr = slot.trigger - if (tr.coaxBlocked & bit) != 0 +def private wto_aux_fire_group(world : WtoWorldSnap const&; var unit : Unit?; className : string; + group : WeaponTriggerGroups; now, dist : float; target : WtoUnitSnap const&; + var slot : WtoBotSlot&; var burst : WtoWeaponBurst&; var fireBudget : int&) + if fireBudget <= 0 || (now >= burst.untilAt && now < burst.pauseUntil) return - var muzzle = unit.pos - var dir = unit.unitTm[0] - if !wto_aux_ready_barrel(unit, group, muzzle, dir) + let needed = wto_aux_ready_count(unit, group) + if needed <= 0 return - let toAim = aimPt - muzzle - let dist = length(toAim) - if dist < 1.0 || dot(dir, toAim / dist) < cos(tr.aimSlackDeg * WTO_DEG_TO_RAD) + var checked = 0 + var rapid = true + for tIdx, turret in iter_range(unit.weap.turret), unit.weap.turret + if int(turret.triggerGroupNo) != int(group) || tIdx >= length(slot.fire.mounts) + continue + let weapon = get_weapon(unit.weap.Weapons, int(turret.triggerNo), int(turret.weaponIndex)) + if weapon == null || weapon.isDummyGun + continue + let gun = as_gun(weapon) + if gun == null || gun.isInoperable || !gun.isReadyToShoot + continue + assume mount = slot.fire.mounts[tIdx] + if checked == 0 + fireBudget-- + if (!wto_mount_load_shell(unit, className, tIdx, gun, mount) || + !wto_aux_check_barrel(world, unit, weapon, now, dist, target, mount, slot)) + return + checked++ + rapid = rapid && mount.automatic + if checked != needed + return + if rapid + var opening = false + if wto_trig_burst_gate(now, true, burst.untilAt, burst.pauseUntil, opening) != WTO_DENY_OK + return + elif now - burst.lastShotAt < WTO_AI_FC_MIN_SHOT_INTERVAL_SEC return unit_single_shot(unit, int(group)) - tr.coaxShots++ + burst.lastShotAt = now + slot.trigger.auxShots++ -def private wto_aux_target_allowed(world : WtoWorldSnap const&; slot : WtoBotSlot const&) : bool +[never_inline] +def public wto_fire_aux_update(world : WtoWorldSnap const&; var unit : Unit?; className : string; + now, dist : float; var slot : WtoBotSlot&; var fireBudget : int&) + if !wto_aux_in_range(dist) + return let idx = wto_world_find_unit(world, slot.perceive.targetEid) if idx < 0 - return false - assume tgt = world.units[idx] - return WTO_AI_FC_AUX_FIRE_AT_ARMOR || tgt.isLightTag || tgt.halfWid < 1.35 - -// Per frame while the main weapon is engaging a target in sight. -[never_inline] -def public wto_fire_aux_update(world : WtoWorldSnap const&; var unit : Unit?; now, distXZ : float; aimPt : float3; - var slot : WtoBotSlot&; var fireBudget : int&) - assume tr = slot.trigger - if !WTO_AI_FC_AUX_ENABLED || unit == null || unit.weap == null || distXZ > WTO_AI_FC_AUX_MAX_RANGE_M return - if !wto_aux_target_allowed(world, slot) - return - var started = false - let onTarget = slot.fire.lastAimErrDeg <= tr.aimSlackDeg - if wto_trig_burst_gate(now, onTarget, tr.coaxBurstUntil, tr.coaxPauseUntil, started) != WTO_DENY_OK - return - if started || now >= tr.coaxCheckedUntil - if fireBudget <= 0 - return - fireBudget-- - tr.coaxBlocked = 0 - if wto_aux_blocked(world, unit, WeaponTriggerGroups.TRIGGER_GROUP_SECONDARY, aimPt, slot) - tr.coaxBlocked |= AUX_SECONDARY_BIT - if wto_aux_blocked(world, unit, WeaponTriggerGroups.TRIGGER_GROUP_COAXIAL_GUN, aimPt, slot) - tr.coaxBlocked |= AUX_COAXIAL_BIT - tr.coaxCheckedUntil = now + WTO_AI_FC_BURST_RECHECK_SEC - wto_aux_fire_group(unit, WeaponTriggerGroups.TRIGGER_GROUP_SECONDARY, AUX_SECONDARY_BIT, aimPt, slot) - wto_aux_fire_group(unit, WeaponTriggerGroups.TRIGGER_GROUP_COAXIAL_GUN, AUX_COAXIAL_BIT, aimPt, slot) + assume target = world.units[idx] + var secondary = slot.trigger.secondary + wto_aux_fire_group(world, unit, className, WeaponTriggerGroups.TRIGGER_GROUP_SECONDARY, now, dist, target, + slot, secondary, fireBudget) + slot.trigger.secondary = secondary + if WTO_AI_FC_AUX_FIRE_AT_ARMOR || target.isLightTag || target.halfWid < 1.35 + var coaxial = slot.trigger.coaxial + wto_aux_fire_group(world, unit, className, WeaponTriggerGroups.TRIGGER_GROUP_COAXIAL_GUN, now, dist, target, + slot, coaxial, fireBudget) + slot.trigger.coaxial = coaxial diff --git a/game-ai/ground/wto_ai_fire_checks_common.das b/game-ai/ground/wto_ai_fire_checks_common.das new file mode 100644 index 0000000..d9de437 --- /dev/null +++ b/game-ai/ground/wto_ai_fire_checks_common.das @@ -0,0 +1,110 @@ +// Per-barrel pre-fire checks: muzzle clearance, the drag-integrated trajectory and friendlies. +options indenting = 2 +options no_global_heap = true +module wto_ai_fire_checks_common shared + +require ecs +require math +require DagorMath +require Unit +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_sight_common +require %appGame.wtoai.wto_ai_estimate_common +require %appGame.wtoai.wto_ai_trigger_common +require %appGame.wtoai.wto_ai_world_common + +[safe_when_uninitialized] +struct private WtoShotWindow + center : float3 = float3(0.0, 0.0, 0.0) + velocity : float3 = float3(0.0, 0.0, 0.0) + along : float3 = float3(1.0, 0.0, 0.0) + halfWidth : float = 0.0 + halfHeight : float = 0.0 + +def private wto_shot_hits_window(window : WtoShotWindow const&; at : float3; time : float) : bool + let miss = at - (window.center + window.velocity * time) + let across = float3(-window.along.z, 0.0, window.along.x) + return abs(dot(miss, across)) <= window.halfWidth && abs(miss.y) <= window.halfHeight + +[never_inline] +def public wto_gate_friendly_segment_clear(world : WtoWorldSnap const&; selfEid : EntityId; + army : int; p0, p1 : float3; tMid : float) : bool + let delta = p1 - p0 + let segLen = length(delta) + if segLen < 0.2 + return true + let dir = delta / segLen + for i in range(world.unitCount) + assume u = world.units[i] + if !u.isAlive || !u.isGround || u.army != army || u.eid == selfEid + continue + let predPos = u.pos + u.vel * tMid + float3(0.0, 1.3, 0.0) + let along = clamp(dot(predPos - p0, dir), 0.0, segLen) + let clearR = WTO_AI_FC_FRIENDLY_CORRIDOR_M + u.halfWid + if length_sq(predPos - (p0 + dir * along)) < clearR * clearR + return false + return true + +[never_inline] +def private wto_gate_check_ballistic_arc(world : WtoWorldSnap const&; selfEid, targetEid : EntityId; army : int; + muzzlePos, liveDir, carrierVel : float3; shell : WtoShellProfile const&; + window : WtoShotWindow const&; checkMiss : bool; var outBlock : int&) : int + let dragK = wto_shot_drag(shell.dragCx, shell.massKg, shell.caliberM) + var cur = muzzlePos + var vel = liveDir * shell.speedMps + carrierVel + var t = 0.0 + for step in range(64) + let spd = length(vel) + let remaining = dot(window.center + window.velocity * t - cur, window.along) + if spd < 20.0 || remaining <= 0.0 + return WTO_DENY_AIM_ERR + let segWant = min(WTO_AI_FC_BALLISTIC_STEP_M, remaining) + let dt = clamp(segWant / spd, 0.004, 0.14) + let accel = float3(0.0, -9.81, 0.0) - vel * (dragK * spd) + var next = cur + vel * dt + accel * (0.5 * dt * dt) + let nextRemaining = dot(window.center + window.velocity * (t + dt) - next, window.along) + let ends = nextRemaining <= 0.0 + var segmentTime = dt + if ends + let fraction = clamp(remaining / max(1.0e-5, remaining - nextRemaining), 0.0, 1.0) + next = lerp(cur, next, fraction) + segmentTime *= fraction + let trimS = step == 0 ? 0.35 : 0.0 + let trimE = ends ? 0.65 : 0.0 + let blk = wto_sight_hard_segment_blocked(world, selfEid, targetEid, cur, next, WTO_AI_FC_BALLISTIC_SWEEP_R_M, trimS, trimE) + if blk != WTO_BLOCK_NONE + outBlock = blk + return WTO_DENY_ARC_HARD + if !wto_gate_friendly_segment_clear(world, selfEid, army, cur, next, t + segmentTime * 0.5) + return WTO_DENY_FRIENDLY + t += segmentTime + if ends + return (!checkMiss || wto_shot_hits_window(window, next, t)) ? WTO_DENY_OK : WTO_DENY_AIM_ERR + cur = next + vel = vel + accel * dt + return WTO_DENY_AIM_ERR + +[never_inline] +def public wto_fire_check_barrel(world : WtoWorldSnap const&; unit : Unit const?; + slot : WtoBotSlot const&; muzzlePos, liveDir, aimPt : float3; + shell : WtoShellProfile const&; checkMiss : bool; + var outBlock : int&) : int + let straightBlk = wto_sight_hard_segment_blocked(world, slot.eid, slot.perceive.targetEid, muzzlePos, aimPt, 0.05, 0.35, 0.65) + if straightBlk != WTO_BLOCK_NONE + outBlock = straightBlk + return WTO_DENY_MUZZLE_HARD + let idx = wto_world_find_unit(world, slot.perceive.targetEid) + if idx < 0 + return WTO_DENY_NO_TARGET + assume target = world.units[idx] + var window = WtoShotWindow() + window.center = slot.perceive.visibleAimPt + window.velocity = wto_est_target_vel(slot.perceive) + window.along = wto_xz_normalize(window.center - muzzlePos, liveDir) + let dist = sqrt(wto_xz_dist_sq(unit.pos, target.pos)) + wto_trig_target_half(unit.pos, target, dist, slot.perceive.visiblePointCount, window.halfWidth, window.halfHeight) + return wto_gate_check_ballistic_arc(world, slot.eid, slot.perceive.targetEid, slot.army, + muzzlePos, liveDir, unit.vel, shell, window, checkMiss, outBlock) diff --git a/game-ai/ground/wto_ai_fire_common.das b/game-ai/ground/wto_ai_fire_common.das index 2958eba..97dd288 100644 --- a/game-ai/ground/wto_ai_fire_common.das +++ b/game-ai/ground/wto_ai_fire_common.das @@ -14,7 +14,6 @@ require Mission require Unit require IGroundModel require Weapon -require Ballistics require %game.utils.utils_common require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_math_common @@ -27,6 +26,7 @@ require %appGame.wtoai.wto_ai_traverse_common require %appGame.wtoai.wto_ai_turret_common require %appGame.wtoai.wto_ai_trigger_common require %appGame.wtoai.wto_ai_fire_aux_common +require %appGame.wtoai.wto_ai_ammo_common [never_inline] def private wto_sync_active_shell(gun : WTGun const?; spec : WtoVehicleSpec const&; var fc : WtoFireState&) @@ -55,8 +55,8 @@ def private wto_sync_active_shell(gun : WTGun const?; spec : WtoVehicleSpec cons return [never_inline] -def private wto_select_next_shell(var gun : WTGun?; spec : WtoVehicleSpec const&; wantSoft : bool) - if gun == null || spec.isAutocannonBelt +def private wto_select_next_shell(var gun : WTGun?; spec : WtoVehicleSpec const&; wantSoft : bool; fc : WtoFireState const&) + if gun == null || spec.isAutocannon return let setCount = length(gun.properties.bulletSets) if setCount < 2 @@ -67,7 +67,9 @@ def private wto_select_next_shell(var gun : WTGun?; spec : WtoVehicleSpec const& var firstAvail = -1 for bsIdx in range(setCount) assume bs = gun.properties.bulletSets[bsIdx] - if bs.bulletsCount <= 0 || length(bs.bullet) <= 0 || bs.bullet[0] == null + let loaded = bsIdx == int(gun.chosenBulletType) && gun.currentLoadedAmmoCount > 0 + let stocked = fc.rackTurret == fc.turretNo && bsIdx < length(fc.rackBySet) && fc.rackBySet[bsIdx] > 0 + if !(loaded || stocked || bs.bulletsCount > 0) || length(bs.bullet) <= 0 || bs.bullet[0] == null continue if firstAvail < 0 firstAvail = bsIdx @@ -80,7 +82,7 @@ def private wto_select_next_shell(var gun : WTGun?; spec : WtoVehicleSpec const& continue if spec.shells[si].isSoftShell && bestSoft < 0 bestSoft = bsIdx - elif spec.shells[si].isAntiArmor && spec.shells[si].penMm > bestArmorPen + if spec.shells[si].isAntiArmor && spec.shells[si].penMm > bestArmorPen bestArmor = bsIdx bestArmorPen = spec.shells[si].penMm break @@ -97,7 +99,7 @@ def private wto_take_primary_gun(var gun : WTGun?; turretNo, previousTurret : in fc.turretNo = turretNo if fc.turretNo != previousTurret fc.loadedBulletIdx = -1 - wto_select_next_shell(gun, spec, wantSoftShell) + wto_select_next_shell(gun, spec, wantSoftShell, fc) wto_sync_active_shell(gun, spec, fc) [never_inline] @@ -109,6 +111,7 @@ def private wto_inspect_primary_weapon(var unit : Unit?; now : float; fc.gunReady = false fc.reloading = false fc.gunDamaged = false + fc.ammoRemaining = -1 if unit == null || unit.weap == null return -1 var selected = -1 @@ -141,8 +144,9 @@ def private wto_inspect_primary_weapon(var unit : Unit?; now : float; if selected < 0 selected = index wto_take_primary_gun(gun, int(weapon.turretNo), previousTurret, spec, wantSoftShell, fc) - if gun.isReadyToShoot - fc.gunReady = true + fc.ammoRemaining = wto_main_gun_ammo(gun, fc) + anyReserve = anyReserve || fc.ammoRemaining > 0 + fc.gunReady = fc.gunReady || gun.isReadyToShoot totalLoaded += max(0, gun.currentLoadedAmmoCount) if gun.currentLoadedAmmoCount > 0 || gun.currentBulletSet.bulletsCount > 0 || weapon.countBullets > 0 anyReserve = true @@ -154,11 +158,11 @@ def private wto_inspect_primary_weapon(var unit : Unit?; now : float; def private wto_finish_weapon_state(now : float; spec : WtoVehicleSpec const&; anyGun, anyAlive, anyReserve : bool; totalLoaded : int; var fc : WtoFireState&) fc.gunDamaged = anyGun && !anyAlive - // A belt-fed autocannon is not ready between two rounds; only a longer wait is a reload. + // An autocannon is not ready between two rounds; only a longer wait is a reload. if fc.gunReady || !anyAlive fc.notReadySince = now let acReload = (now - fc.notReadySince) > WTO_AI_FC_AC_RELOAD_DETECT_SEC - fc.reloading = anyAlive && !fc.gunReady && anyReserve && (!spec.isAutocannonBelt || acReload) + fc.reloading = anyAlive && !fc.gunReady && anyReserve && (!spec.isAutocannon || acReload) if fc.pendingShotConfirm if (fc.prevLoadedAmmo >= 0 && totalLoaded < fc.prevLoadedAmmo) || !fc.gunReady fc.shotCount++ @@ -167,24 +171,6 @@ def private wto_finish_weapon_state(now : float; spec : WtoVehicleSpec const&; a fc.pendingShotConfirm = false fc.prevLoadedAmmo = totalLoaded -[never_inline] -def private wto_solve_ballistic_aim(muzzlePos, myVel : float3; var slot : WtoBotSlot&; - aimBase : float3; var outAimPt, outWishDir : float3&) : float - var leadPt = aimBase - let rawDist = wto_est_compute_biased_lead(muzzlePos, myVel, aimBase, slot, leadPt) - let dragLoss = clamp(slot.fire.activeDragCx * 0.00011 * rawDist, 0.0, 0.28) - let vEff = max(120.0, slot.fire.activeSpeedMps * (1.0 - dragLoss)) - outAimPt = leadPt - var arcDir = float3(0.0, 0.0, 0.0) - if calculate_arc_low_start_dir(muzzlePos, leadPt, vEff, arcDir) && length_sq(arcDir) > 0.25 - outWishDir = normalize(arcDir) - else - let d = max(1.0, length(leadPt - muzzlePos)) - let tof = d / vEff - let dropComp = float3(0.0, 0.5 * 9.81 * tof * tof, 0.0) - outWishDir = normalize(leadPt + dropComp - muzzlePos) - return rawDist - [never_inline] def private wto_sample_muzzle(unit : Unit const?; primaryIndex : int; var outPos, outDir : float3&) : bool @@ -217,13 +203,25 @@ def private wto_clear_aim_tracking(var fc : WtoFireState&) def private wto_yield_air_fire(var unit : Unit?; var slot : WtoBotSlot&) wto_set_hull_aim(unit, false, 0.0, unit.unitTm[0], slot) wto_clear_aim_tracking(slot.fire) - wto_trig_clear(slot.trigger) + wto_trig_set_target(INVALID_ENTITY_ID, slot.trigger) var gm = as_gm(unit) if gm != null *gm |> set_check_visibility_target(true) *gm |> set_ignore_stop_for_fire(true) set_unit_attack_type(unit, "attack_target") +[never_inline] +def private wto_fire_has_engagement(slot : WtoBotSlot const&) : bool + assume p = slot.perceive + let yielding = slot.spec.role == WTO_ROLE_SPAA && slot.tactics.state == WTO_STATE_DISABLED + return p.hasClearLos && !!p.targetEid && !p.targetIsAir && !yielding && !wto_turret_prefers_threat(slot) + +def private wto_fire_wants_soft(world : WtoWorldSnap const&; slot : WtoBotSlot const&) : bool + if !slot.perceive.hasClearLos || slot.perceive.targetIsAir + return false + let idx = wto_world_find_unit(world, slot.perceive.targetEid) + return idx >= 0 && (world.units[idx].isLightTag || world.units[idx].halfWid < 1.35) + [never_inline] def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; className : string; now, dt : float; var slot : WtoBotSlot&; var fireBudget : int&) @@ -233,40 +231,39 @@ def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; classN wto_yield_air_fire(unit, slot) return set_unit_attack_type(unit, "dont_aim") - var wantSoftShell = false - if slot.perceive.hasClearLos && !!slot.perceive.targetEid && !slot.perceive.targetIsAir - let tgtIdx = wto_world_find_unit(world, slot.perceive.targetEid) - if tgtIdx >= 0 - wantSoftShell = world.units[tgtIdx].isLightTag || world.units[tgtIdx].halfWid < 1.35 - let primaryIndex = wto_inspect_primary_weapon(unit, now, slot.spec, wantSoftShell, slot.fire) + let wantSoft = wto_fire_wants_soft(world, slot) + let primaryIndex = wto_inspect_primary_weapon(unit, now, slot.spec, wantSoft, slot.fire) var muzzlePos = unit.pos + float3(0.0, 1.95, 0.0) var liveBarrelDir = unit.unitTm[0] let _preSample = wto_sample_muzzle(unit, primaryIndex, muzzlePos, liveBarrelDir) - let hFwd = unit.unitTm[0] var wishWorldDir = hFwd - var aimPt = muzzlePos + hFwd * 50.0 + var aimPt = muzzlePos var distToTgt = 9999.0 - // A clearly seen target is aimed at unless a more dangerous threat calls the turret away; - // otherwise the turret channel picks where to look (wto_ai_turret_common.das). - let engageValid = (slot.perceive.hasClearLos && !!slot.perceive.targetEid && !slot.perceive.targetIsAir && - !(slot.spec.role == WTO_ROLE_SPAA && slot.tactics.state == WTO_STATE_DISABLED) && !wto_turret_prefers_threat(slot)) - if engageValid - let baseAim = slot.perceive.visibleAimPt - distToTgt = wto_solve_ballistic_aim(muzzlePos, unit.vel, slot, baseAim, aimPt, wishWorldDir) + let engage = wto_fire_has_engagement(slot) + let distXZ = sqrt(wto_xz_dist_sq(unit.pos, slot.perceive.knownPos)) + let target = engage ? slot.perceive.targetEid : INVALID_ENTITY_ID + wto_trig_set_target(target, slot.trigger) + var auxAimed = false + if engage + let aimBase = slot.perceive.visibleAimPt + distToTgt = wto_solve_ballistic_aim(muzzlePos, unit.vel, aimBase, slot.fire.activeSpeedMps, slot.fire.activeDragCx, slot.fire.activeMassKg, slot.fire.activeCaliberM, slot, aimPt, wishWorldDir) + auxAimed = wto_fire_aux_aim(unit, className, dt, distXZ, slot) else wishWorldDir = wto_turret_look_dir(now, muzzlePos, unit.pos, hFwd, slot) - var wishYaw = 0.0 var wishPitch = 0.0 wto_world_to_hull_deg(wishWorldDir, hFwd, unit.unitTm[1], unit.unitTm[2], wishYaw, wishPitch) wto_drive_mounted_gun(unit, className, dt, wishYaw, wishPitch, slot) - let canEngage = engageValid && distToTgt <= WTO_AI_FC_MAX_RANGE_M && wto_sample_muzzle(unit, primaryIndex, muzzlePos, liveBarrelDir) + if slot.fire.traverse.known || auxAimed + wto_apply_weapon_aim(unit, dt) + let canEngage = engage && distToTgt <= WTO_AI_FC_MAX_RANGE_M && wto_sample_muzzle(unit, primaryIndex, muzzlePos, liveBarrelDir) wto_set_hull_aim(unit, canEngage, wishYaw, liveBarrelDir, slot) - if !canEngage + if canEngage + wto_fire_gate_try_shoot(world, unit, className, now, distXZ, muzzlePos, aimPt, liveBarrelDir, wishWorldDir, slot, fireBudget) + else wto_clear_aim_tracking(slot.fire) - wto_trig_clear(slot.trigger) - return - let distXZ = sqrt(wto_xz_dist_sq(unit.pos, slot.perceive.knownPos)) - wto_fire_gate_try_shoot(world, unit, now, distXZ, muzzlePos, aimPt, liveBarrelDir, wishWorldDir, slot, fireBudget) - wto_fire_aux_update(world, unit, now, distXZ, aimPt, slot, fireBudget) + slot.trigger.wantSpeedMps = 99.0 + slot.trigger.wantSpeedAt = -100.0 + if engage + wto_fire_aux_update(world, unit, className, now, distXZ, slot, fireBudget) diff --git a/game-ai/ground/wto_ai_fire_gate_common.das b/game-ai/ground/wto_ai_fire_gate_common.das index 6a14df3..01370be 100644 --- a/game-ai/ground/wto_ai_fire_gate_common.das +++ b/game-ai/ground/wto_ai_fire_gate_common.das @@ -1,10 +1,4 @@ -// Single fire-permission gate for the main weapon (cannon, launcher, SPAA self-defense). -// Every shot must pass visual confirmation, weapon readiness, the 800 m continuous LOS window, the -// trigger channel's hit probability against its fire threshold (wto_ai_trigger_common.das), aim -// settle, frame pre-fire budget, muzzle hard-ray, drag-integrated ballistic trajectory sweep, -// predicted friendly corridor, and multi-barrel group validation. A belt-fed autocannon fires in -// bursts whenever it is roughly on target and repeats the expensive checks only every -// fireControl.burstRecheckSec within a burst. +// Main weapon fire permission and burst control. All fired barrels pass a fresh safety check. options indenting = 2 options no_global_heap = true module wto_ai_fire_gate_common shared @@ -20,113 +14,45 @@ require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_combat_types_common require %appGame.wtoai.wto_ai_types_common -require %appGame.wtoai.wto_ai_sight_common +require %appGame.wtoai.wto_ai_fire_checks_common +require %appGame.wtoai.wto_ai_weapon_profile_common require %appGame.wtoai.wto_ai_trigger_common [never_inline] -def public wto_gate_friendly_segment_clear(world : WtoWorldSnap const&; selfEid : EntityId; - army : int; p0, p1 : float3; tMid : float) : bool - let delta = p1 - p0 - let segLen = length(delta) - if segLen < 0.2 - return true - let dir = delta / segLen - for i in range(world.unitCount) - assume u = world.units[i] - if !u.isAlive || !u.isGround || u.army != army || u.eid == selfEid - continue - let predPos = u.pos + u.vel * tMid + float3(0.0, 1.3, 0.0) - let along = clamp(dot(predPos - p0, dir), 0.0, segLen) - let clearR = WTO_AI_FC_FRIENDLY_CORRIDOR_M + u.halfWid - if length_sq(predPos - (p0 + dir * along)) < clearR * clearR - return false - return true - -[never_inline] -def private wto_gate_check_ballistic_arc(world : WtoWorldSnap const&; - selfEid, targetEid : EntityId; army : int; - muzzlePos, liveDir, carrierVel, aimPt : float3; - speedMps, dragCx, massKg, caliberM : float; checkMiss : bool; - var outBlock : int&) : int - let toAim = aimPt - muzzlePos - let targetDist = length(toAim) - if targetDist < 1.5 - return WTO_DENY_OK - let toAimDir = toAim / targetDist - let area = 0.25 * WTO_PI * caliberM * caliberM - let dragK = 0.5 * 1.225 * dragCx * area / max(0.1, massKg) - var cur = muzzlePos - var vel = liveDir * max(80.0, speedMps) + carrierVel - var t = 0.0 - var traveled = 0.0 - for step in range(64) - let spd = length(vel) - if spd < 20.0 - return WTO_DENY_AIM_ERR - let remain = max(0.5, targetDist - traveled) - let segWant = min(WTO_AI_FC_BALLISTIC_STEP_M, remain) - let dt = clamp(segWant / spd, 0.004, 0.14) - let accel = float3(0.0, -9.81, 0.0) - vel * (dragK * spd) - var next = cur + vel * dt + accel * (0.5 * dt * dt) - let nextProj = dot(next - muzzlePos, toAimDir) - let isLast = nextProj >= targetDist - 0.5 - if isLast && nextProj > targetDist && length_sq(next - cur) > 0.01 - let curProj = dot(cur - muzzlePos, toAimDir) - let frac = clamp((targetDist - curProj) / max(0.01, nextProj - curProj), 0.0, 1.0) - next = lerp(cur, next, frac) - let trimS = step == 0 ? 0.35 : 0.0 - let trimE = isLast ? 0.65 : 0.0 - let blk = wto_sight_hard_segment_blocked(world, selfEid, targetEid, cur, next, WTO_AI_FC_BALLISTIC_SWEEP_R_M, trimS, trimE) - if blk != WTO_BLOCK_NONE - outBlock = blk - return WTO_DENY_ARC_HARD - if !wto_gate_friendly_segment_clear(world, selfEid, army, cur, next, t + dt * 0.5) - return WTO_DENY_FRIENDLY - traveled += length(next - cur) - cur = next - vel = vel + accel * dt - t += dt - if isLast - let missTol = max(3.2, targetDist * 0.012) - if checkMiss && length_sq(cur - aimPt) > missTol * missTol - return WTO_DENY_AIM_ERR - return WTO_DENY_OK - return WTO_DENY_AIM_ERR - -[never_inline] -def private wto_gate_check_barrel(world : WtoWorldSnap const&; unit : Unit const?; - slot : WtoBotSlot const&; muzzlePos, liveDir, aimPt : float3; checkMiss : bool; - var outBlock : int&) : int - let straightBlk = wto_sight_hard_segment_blocked(world, slot.eid, slot.perceive.targetEid, muzzlePos, aimPt, 0.05, 0.35, 0.65) - if straightBlk != WTO_BLOCK_NONE - outBlock = straightBlk - return WTO_DENY_MUZZLE_HARD - return wto_gate_check_ballistic_arc(world, slot.eid, slot.perceive.targetEid, slot.army, - muzzlePos, liveDir, unit.vel, aimPt, - slot.fire.activeSpeedMps, slot.fire.activeDragCx, slot.fire.activeMassKg, slot.fire.activeCaliberM, checkMiss, outBlock) - -[never_inline] -def private wto_gate_check_all_primary_guns(world : WtoWorldSnap const&; unit : Unit const?; - slot : WtoBotSlot const&; primaryMuzzle, primaryDir, aimPt : float3; - checkMiss : bool; var outBlock : int&) : int - let primaryRes = wto_gate_check_barrel(world, unit, slot, primaryMuzzle, primaryDir, aimPt, checkMiss, outBlock) - if primaryRes != WTO_DENY_OK - return primaryRes - if unit == null || unit.weap == null - return WTO_DENY_OK +def private wto_gate_check_all_primary_guns(world : WtoWorldSnap const&; unit : Unit const?; className : string; + primaryMuzzle, primaryDir, aimPt : float3; checkMiss : bool; + var slot : WtoBotSlot&; var outBlock : int&) : int + var shell = WtoShellProfile() + shell.speedMps = slot.fire.activeSpeedMps + shell.dragCx = slot.fire.activeDragCx + shell.massKg = slot.fire.activeMassKg + shell.caliberM = slot.fire.activeCaliberM + let result = wto_fire_check_barrel(world, unit, slot, primaryMuzzle, primaryDir, aimPt, shell, checkMiss, outBlock) + if result != WTO_DENY_OK + return result for tIdx, turret in iter_range(unit.weap.turret), unit.weap.turret if tIdx == slot.fire.turretNo || int(turret.triggerGroupNo) != int(WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY) continue let weapon = get_weapon(unit.weap.Weapons, int(turret.triggerNo), int(turret.weaponIndex)) if weapon == null || weapon.isDummyGun continue + let gun = as_gun(weapon) + if gun == null + return WTO_DENY_MULTI_GUN + if gun.isInoperable || !gun.isReadyToShoot + continue + if tIdx >= length(slot.fire.mounts) + return WTO_DENY_MULTI_GUN + assume cached = slot.fire.mounts[tIdx] + if !wto_mount_load_shell(unit, className, tIdx, gun, cached) + return WTO_DENY_MULTI_GUN var gunTm : float3x4 weapon_calcShootTm(weapon, unit.unitTm, gunTm) if length_sq(gunTm[0]) <= 0.25 - continue - let secRes = wto_gate_check_barrel(world, unit, slot, gunTm[3], normalize(gunTm[0]), aimPt, checkMiss, outBlock) - if secRes != WTO_DENY_OK - return secRes == WTO_DENY_FRIENDLY ? WTO_DENY_FRIENDLY : WTO_DENY_MULTI_GUN + return WTO_DENY_MULTI_GUN + let next = wto_fire_check_barrel(world, unit, slot, gunTm[3], normalize(gunTm[0]), aimPt, cached.shell, checkMiss, outBlock) + if next != WTO_DENY_OK + return next == WTO_DENY_FRIENDLY ? WTO_DENY_FRIENDLY : WTO_DENY_MULTI_GUN return WTO_DENY_OK [never_inline] @@ -165,7 +91,7 @@ def private wto_gate_log_deny(now, distXZ : float; reason, blk : int; var slot : def private wto_gate_request_primary_shot(var unit : Unit?; now, distXZ : float; var slot : WtoBotSlot&) assume fc = slot.fire unit_single_shot(unit, int(WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY)) - let firstOfBurst = !slot.spec.isAutocannonBelt || (now - fc.lastShotAt) > 0.5 + let firstOfBurst = !slot.spec.isAutocannon || (now - fc.lastShotAt) > 0.5 fc.lastShotAt = now fc.pendingShotConfirm = true fc.pendingShotAt = now @@ -173,7 +99,7 @@ def private wto_gate_request_primary_shot(var unit : Unit?; now, distXZ : float; fc.lastDenyBlock = WTO_BLOCK_NONE fc.shotErrSumDeg += fc.lastAimErrDeg fc.maxShotErrDeg = max(fc.maxShotErrDeg, fc.lastAimErrDeg) - if !slot.spec.isAutocannonBelt + if !slot.spec.isAutocannon fc.settleHoldSec = 0.0 slot.trigger.biasEpoch++ if WTO_AI_DIAG_TELEMETRY && firstOfBurst @@ -182,7 +108,7 @@ def private wto_gate_request_primary_shot(var unit : Unit?; now, distXZ : float; // Main gun: one shot per permission, once the hit probability reaches the threshold and the // barrel has settled on the target. [never_inline] -def private wto_gate_try_single(world : WtoWorldSnap const&; var unit : Unit?; now, distXZ : float; +def private wto_gate_try_single(world : WtoWorldSnap const&; var unit : Unit?; className : string; now, distXZ : float; muzzlePos, aimPt, liveDir, wishDir : float3; probOk, withinTraverse : bool; var slot : WtoBotSlot&; var fireBudget : int&) assume fc = slot.fire @@ -208,17 +134,15 @@ def private wto_gate_try_single(world : WtoWorldSnap const&; var unit : Unit?; n return fireBudget-- var blk = WTO_BLOCK_NONE - let gateRes = wto_gate_check_all_primary_guns(world, unit, slot, muzzlePos, liveDir, aimPt, true, blk) + let gateRes = wto_gate_check_all_primary_guns(world, unit, className, muzzlePos, liveDir, aimPt, true, slot, blk) if gateRes != WTO_DENY_OK wto_gate_log_deny(now, distXZ, gateRes, blk, slot) return wto_gate_request_primary_shot(unit, now, distXZ, slot) -// Belt-fed autocannon (decision layer design, 6.3): bursts while within the aim slack, without -// waiting for the barrel to settle; the barrel, trajectory and friendly checks run at the start -// of a burst and every burstRecheckSec, not for every round. +// An automatic gun uses burst timing and the looser aim window, with a fresh safety check per shot. [never_inline] -def private wto_gate_try_burst(world : WtoWorldSnap const&; var unit : Unit?; now, distXZ : float; +def private wto_gate_try_burst(world : WtoWorldSnap const&; var unit : Unit?; className : string; now, distXZ : float; muzzlePos, aimPt, liveDir : float3; aimErrDeg : float; withinTraverse : bool; var slot : WtoBotSlot&; var fireBudget : int&) assume fc = slot.fire @@ -233,34 +157,32 @@ def private wto_gate_try_burst(world : WtoWorldSnap const&; var unit : Unit?; no deny = WTO_DENY_LONG_WINDOW else deny = wto_trig_burst_gate(now, aimErrDeg <= tr.aimSlackDeg, tr.burstUntil, tr.burstPauseUntil, started) - if started - tr.biasEpoch++ - tr.burstCheckedUntil = -100.0 var blk = WTO_BLOCK_NONE - if deny == WTO_DENY_OK && now >= tr.burstCheckedUntil + if deny == WTO_DENY_OK if fireBudget <= 0 deny = WTO_DENY_BUDGET else fireBudget-- - deny = wto_gate_check_all_primary_guns(world, unit, slot, muzzlePos, liveDir, aimPt, false, blk) - if deny == WTO_DENY_OK - tr.burstCheckedUntil = now + WTO_AI_FC_BURST_RECHECK_SEC + deny = wto_gate_check_all_primary_guns(world, unit, className, muzzlePos, liveDir, aimPt, false, slot, blk) if deny != WTO_DENY_OK wto_gate_log_deny(now, distXZ, deny, blk, slot) return + if started + tr.biasEpoch++ wto_gate_request_primary_shot(unit, now, distXZ, slot) [never_inline] -def public wto_fire_gate_try_shoot(world : WtoWorldSnap const&; var unit : Unit?; +def public wto_fire_gate_try_shoot(world : WtoWorldSnap const&; var unit : Unit?; className : string; now, distXZ : float; muzzlePos, aimPt, liveDir, wishDir : float3; var slot : WtoBotSlot&; var fireBudget : int&) assume fc = slot.fire let aimErrDeg = acos(clamp(dot(liveDir, wishDir), -1.0, 1.0)) * WTO_RAD_TO_DEG fc.lastAimErrDeg = aimErrDeg let turnDegSec = abs(slot.drive.omegaYawRad) * WTO_RAD_TO_DEG - let probOk = wto_trig_evaluate(world, now, unit.pos, length(unit.vel), turnDegSec, distXZ, aimErrDeg, slot) + let offset = wto_trig_aim_error(liveDir, wishDir) + let probOk = wto_trig_evaluate(world, now, unit.pos, length(unit.vel), turnDegSec, distXZ, offset, slot) let withinTraverse = fc.hullAimTarget == INVALID_ENTITY_ID - if slot.spec.isAutocannonBelt - wto_gate_try_burst(world, unit, now, distXZ, muzzlePos, aimPt, liveDir, aimErrDeg, withinTraverse, slot, fireBudget) + if slot.spec.isAutocannon + wto_gate_try_burst(world, unit, className, now, distXZ, muzzlePos, aimPt, liveDir, aimErrDeg, withinTraverse, slot, fireBudget) else - wto_gate_try_single(world, unit, now, distXZ, muzzlePos, aimPt, liveDir, wishDir, probOk, withinTraverse, slot, fireBudget) + wto_gate_try_single(world, unit, className, now, distXZ, muzzlePos, aimPt, liveDir, wishDir, probOk, withinTraverse, slot, fireBudget) diff --git a/game-ai/ground/wto_ai_follow_common.das b/game-ai/ground/wto_ai_follow_common.das index 7d8dacc..3d75722 100644 --- a/game-ai/ground/wto_ai_follow_common.das +++ b/game-ai/ground/wto_ai_follow_common.das @@ -56,6 +56,22 @@ def public wto_follow_lookahead(spec : WtoVehicleSpec const&; speedMps : float) def public wto_follow_target(rt : WtoRouteState const&; lookM : float) : float3 return wto_poly_walk(rt.corridor, rt.corridorLen, rt.segIdx, rt.segT, lookM) +// A bend, or the end of the route, is within the distance the hull is willing to reverse. +[never_inline] +def public wto_follow_near_turn(rt : WtoRouteState const&; myPos : float3; limitM : float) : bool + let corner = clamp(rt.segIdx + 1, 1, rt.corridorLen - 1) + var dist = sqrt(wto_xz_dist_sq(myPos, rt.corridor[corner])) + let bendDot = cos(WTO_AI_PF_CORNER_ANGLE_DEG * WTO_DEG_TO_RAD) + for i in range(corner, rt.corridorLen - 1) + if dist > limitM + return false + let into = wto_xz_normalize(rt.corridor[i] - rt.corridor[i - 1], float3(1.0, 0.0, 0.0)) + let out = wto_xz_normalize(rt.corridor[i + 1] - rt.corridor[i], into) + if dot(into, out) <= bendDot + return true + dist += sqrt(wto_xz_dist_sq(rt.corridor[i], rt.corridor[i + 1])) + return !rt.truncated && dist <= limitM + // Highest speed at `distToB` metres before corner b (a -> b -> c) that still allows turning it. [never_inline] def private wto_follow_corner_cap(a, b, c : float3; distToB, lookM, halfLen : float) : float diff --git a/game-ai/ground/wto_ai_nav_common.das b/game-ai/ground/wto_ai_nav_common.das index 6a71a29..9e66e84 100644 --- a/game-ai/ground/wto_ai_nav_common.das +++ b/game-ai/ground/wto_ai_nav_common.das @@ -21,6 +21,7 @@ require %appGame.wtoai.wto_ai_navquery_common require %appGame.wtoai.wto_ai_navmesh_common require %appGame.wtoai.wto_ai_route_common require %appGame.wtoai.wto_ai_follow_common +require %appGame.wtoai.wto_ai_facing_common require %appGame.wtoai.wto_ai_avoid_common require %appGame.wtoai.wto_ai_traffic_common require %appGame.wtoai.wto_ai_unstick_common @@ -32,42 +33,16 @@ def private wto_nav_halt(myPos, hullFwd : float3; var slot : WtoBotSlot&) wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_HALT, myPos, hullFwd, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) slot.nav.bumperBlockedSince = -100.0 -// A target outside the gun's traverse: the fire layer asks for the hull to turn to it, and the -// chassis pivots in place where it has room (wto_ai_traverse_common.das). -[never_inline] -def private wto_try_hull_aim(myPos, hullFwd : float3; var slot : WtoBotSlot&) : bool - let state = slot.tactics.state - let allowed = (state == WTO_STATE_MARCH || state == WTO_STATE_RUN_AND_GUN || state == WTO_STATE_PREAIM || - state == WTO_STATE_SHORT_HALT || state == WTO_STATE_HULL_ANGLE) - if !allowed - return false - if !slot.fire.hullAimTarget || slot.fire.hullAimTarget != slot.perceive.targetEid || slot.tactics.immobilized - return false - if wto_pivot_drive_mode(slot.spec, slot.nav.frontClearM, slot.nav.rearClearM, true) == WTO_DRIVE_HALT - return false - slot.nav.stuckCheckAt = -100.0 - let direction = wto_xz_normalize(slot.fire.hullAimDir, hullFwd) - wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_PIVOT, myPos, direction, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) - return true - -[never_inline] -def private wto_nav_hull_angle(myPos, hullFwd : float3; var slot : WtoBotSlot&) - let wishAngle = wto_xz_normalize(slot.tactics.hullAngleDir, hullFwd) - let angErr = acos(clamp(dot(wishAngle, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG - if angErr > WTO_AI_BHV_FACE_TOL_DEG - slot.nav.stuckCheckAt = -100.0 - wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_PIVOT, myPos + wishAngle * 14.0, wishAngle, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) - else - wto_nav_halt(myPos, hullFwd, slot) - // Standing for a shot or in cover: turn toward the facing direction (decision layer design, 7.3) // only when the hull is more than limitDeg off it, else hold still. [never_inline] -def private wto_nav_stand(myPos, hullFwd : float3; limitDeg : float; var slot : WtoBotSlot&) +def private wto_nav_stand(myPos, hullFwd : float3; var slot : WtoBotSlot&) assume tac = slot.tactics - if tac.faceActive && acos(clamp(dot(tac.faceDir, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG > limitDeg + let limit = tac.faceForGun ? WTO_AI_FC_BASE_ALIGN_DEG : WTO_AI_BHV_FACE_TOL_DEG + let errorDeg = acos(clamp(dot(tac.faceDir, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG + if tac.faceActive && errorDeg > limit && wto_pivot_drive_mode(slot.spec, slot.nav.frontClearM, slot.nav.rearClearM, true) != WTO_DRIVE_HALT slot.nav.stuckCheckAt = -100.0 - wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_PIVOT, myPos + tac.faceDir * 14.0, tac.faceDir, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) + wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_PIVOT, myPos, tac.faceDir, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) return wto_nav_halt(myPos, hullFwd, slot) @@ -168,6 +143,7 @@ def private wto_nav_follow(var world : WtoWorldSnap&; navState : int; now : floa wto_nav_halt(myPos, hullFwd, slot) return wto_follow_track(myPos, rt) + wto_face_reverse_update(now, myPos, hullFwd, slot) let reverse = slot.tactics.reverseTravel let lead = reverse ? -hullFwd : hullFwd let speedNow = abs(slot.drive.lastVFwd) @@ -204,13 +180,10 @@ def public wto_nav_update(var world : WtoWorldSnap&; navState, slotIdx : int; no slot.nav.frontClearM = wto_terrain_hard_ray(probeBase, hullFwd, 24.0) slot.nav.rearClearM = wto_terrain_hard_ray(probeBase, -hullFwd, 18.0) let st = slot.tactics.state - if wto_try_hull_aim(myPos, hullFwd, slot) - return - if st == WTO_STATE_HULL_ANGLE - wto_nav_hull_angle(myPos, hullFwd, slot) - return - if st == WTO_STATE_SHORT_HALT || st == WTO_STATE_COVER_RELOAD - wto_nav_stand(myPos, hullFwd, st == WTO_STATE_SHORT_HALT ? WTO_AI_BHV_FACE_HALT_LIMIT_DEG : WTO_AI_BHV_FACE_TOL_DEG, slot) + if st != WTO_STATE_MARCH && st != WTO_STATE_RUN_AND_GUN + slot.tactics.reverseTravel = false + if st == WTO_STATE_HULL_ANGLE || st == WTO_STATE_SHORT_HALT || st == WTO_STATE_COVER_RELOAD + wto_nav_stand(myPos, hullFwd, slot) return if slot.tactics.desiredSpeedMps <= 0.05 wto_nav_halt(myPos, hullFwd, slot) diff --git a/game-ai/ground/wto_ai_nav_types_common.das b/game-ai/ground/wto_ai_nav_types_common.das index 4791783..3e92006 100644 --- a/game-ai/ground/wto_ai_nav_types_common.das +++ b/game-ai/ground/wto_ai_nav_types_common.das @@ -69,6 +69,7 @@ struct public WtoNavState lastUnstickAt : float = -100.0 reverseTarget : float3 = float3(0.0, 0.0, 0.0) reverseUntil : float = -100.0 + unstickForward : bool = false reverseCount : int = 0 unstickEvents : int = 0 contactEvents : int = 0 diff --git a/game-ai/ground/wto_ai_perceive_common.das b/game-ai/ground/wto_ai_perceive_common.das index e2bdb17..cf814fc 100644 --- a/game-ai/ground/wto_ai_perceive_common.das +++ b/game-ai/ground/wto_ai_perceive_common.das @@ -113,7 +113,7 @@ def private wto_perc_layer_mul(dist, cosGun, cosHull : float; lookAround : bool) return 0.0 // Integrates one enemy's exposure this tick; its track index, or -1 when no perception layer -// covers it or it is hidden. `vis` gets the visible sample count, `aimPt` the first visible one. +// covers it or it is hidden. The output is the visible sample count and its center. [never_inline] def private wto_exp_observe(world : WtoWorldSnap const&; now, dt : float; myEye, lookDir, hullDir : float3; lookAround : bool; u : WtoUnitSnap const&; var slot : WtoBotSlot&; @@ -200,6 +200,17 @@ def private wto_perc_look(now : float; hullDir : float3; var slot : WtoBotSlot&; p.nextLookAroundAt = now + WTO_AI_PERC_LOOK_AROUND_SEC return now < p.lookAroundUntil +// A quick prediction from the bot's own motion estimate, using the existing visual occluders. +[never_inline] +def private wto_perc_fleeting(world : WtoWorldSnap const&; myEye : float3; slot : WtoBotSlot const&) : bool + assume p = slot.perceive + let los = wto_xz_normalize(p.knownPos - myEye, float3(1.0, 0.0, 0.0)) + let laterally = abs(dot(p.estVel, float3(-los.z, 0.0, los.x))) + if laterally < WTO_AI_FC_FLEETING_LAT_MPS + return false + let future = p.visibleAimPt + p.estVel * WTO_AI_FC_FLEETING_LOOKAHEAD_SEC + return wto_sight_visual_clear(world, slot.eid, p.targetEid, myEye, future) != WTO_BLOCK_NONE + [never_inline] def public wto_perceive_update(var world : WtoWorldSnap&; now, dt : float; myPos, hullFwd : float3; var slot : WtoBotSlot&) @@ -229,6 +240,7 @@ def public wto_perceive_update(var world : WtoWorldSnap&; now, dt : float; p.wasEngaging = !tgt.isAir p.watchUntil = -100.0 wto_est_push_visual_sample(now, tgt.eid, tgt.pos, p) + p.targetFleeting = !tgt.isAir && wto_perc_fleeting(world, myEye, slot) if p.lockedEid != tgt.eid || now >= p.lockedUntil - 0.5 p.lockedEid = tgt.eid p.lockedUntil = now + WTO_AI_TACTICS_STICKY_SEC @@ -239,6 +251,7 @@ def public wto_perceive_update(var world : WtoWorldSnap&; now, dt : float; // Lost visual confirmation: immediately revoke LOS, freeze exit point for 2-5 s watch, zero velocity. p.hasClearLos = false + p.targetFleeting = false p.visiblePointCount = 0 p.goodLosSec = 0.0 wto_est_on_los_lost(now, slot.eid, p) diff --git a/game-ai/ground/wto_ai_route_common.das b/game-ai/ground/wto_ai_route_common.das index a249f93..14758b6 100644 --- a/game-ai/ground/wto_ai_route_common.das +++ b/game-ai/ground/wto_ai_route_common.das @@ -35,7 +35,7 @@ def public wto_route_filter(spec : WtoVehicleSpec const&) : int [never_inline] def public wto_route_active_goal(myPos, finalGoal : float3; slot : WtoBotSlot const&) : float3 let st = slot.tactics.state - let marching = st == WTO_STATE_MARCH || st == WTO_STATE_PREAIM || st == WTO_STATE_RELOAD_ADVANCE + let marching = st == WTO_STATE_MARCH || st == WTO_STATE_RUN_AND_GUN if !marching || !slot.order.routeRelayValid return finalGoal let relay = slot.order.routeRelayPos diff --git a/game-ai/ground/wto_ai_runtime.das b/game-ai/ground/wto_ai_runtime.das index 10ac9f8..657e555 100644 --- a/game-ai/ground/wto_ai_runtime.das +++ b/game-ai/ground/wto_ai_runtime.das @@ -38,6 +38,7 @@ require %appGame.wtoai.wto_ai_nav_common require %appGame.wtoai.wto_ai_navmesh_common require %appGame.wtoai.wto_ai_drive_common require %appGame.wtoai.wto_ai_fire_common +require %appGame.wtoai.wto_ai_ammo_common require %appGame.wtoai.wto_ai_diag_common require %appGame.wtoai.wto_ai_stats_common require %appGame.wtoai.wto_ai_slots_common @@ -167,6 +168,20 @@ def wto_ai_world_tick_es(act : UpdateStageInfoAct) wto_navmesh_log_stats(g_navmesh) wto_stats_tick(now, g_stats) +[es(tag=server, before=wto_ai_pipeline_es)] +def wto_ai_ammo_sample_es(act : UpdateStageInfoAct; eid : EntityId; unit__ref : UnitRef; + ammo_stowage__ammoState : uint; ammo_stowage__ammoTypeRemap : IPoint4List; + ammo_stowage__weaponsIds : IntList; ammo_slots__ammoMaskAndType : UInt32List; + ammo_slots__numAmmo : IPoint2List) + if act.dt <= 0.0 || !g_world.valid || !WTO_AI_LAYER_FIRE_CONTROL + return + let index = wto_slots_find(g_bots, eid) + let u = unit__ref.unit + if index < 0 || u == null || u.weap == null || g_world.time < g_bots[index].nextTacticsAt + return + wto_ammo_sample(u, ammo_stowage__ammoState, ammo_stowage__ammoTypeRemap, ammo_stowage__weaponsIds, + ammo_slots__ammoMaskAndType, ammo_slots__numAmmo, g_bots[index].fire) + [es(tag=server, no_order)] def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&; unit__className : string = ""; diff --git a/game-ai/ground/wto_ai_sight_common.das b/game-ai/ground/wto_ai_sight_common.das index 0d4374a..c816c98 100644 --- a/game-ai/ground/wto_ai_sight_common.das +++ b/game-ai/ground/wto_ai_sight_common.das @@ -117,12 +117,24 @@ def public wto_sight_check_target_samples(world : WtoWorldSnap const&; let count = clamp(maxSamples, 1, 4) var vis = 0 var sum = float3(0.0, 0.0, 0.0) + var visible : bool[4] for s in range(count) - if wto_sight_visual_clear(world, selfEid, tgt.eid, eyePos, pts[s]) == WTO_BLOCK_NONE + visible[s] = wto_sight_visual_clear(world, selfEid, tgt.eid, eyePos, pts[s]) == WTO_BLOCK_NONE + if visible[s] sum += pts[s] vis++ // Aim at the middle of what is visible (decision layer design, 6.2), not at the first visible // point, which with the hull hidden is the gun mantlet every time. if vis > 0 outBestPt = sum / float(vis) + if vis > 1 && wto_sight_visual_clear(world, selfEid, tgt.eid, eyePos, outBestPt) != WTO_BLOCK_NONE + let center = outBestPt + var bestDist = 1.0e9 + for s in range(count) + if !visible[s] + continue + let d = length_sq(pts[s] - center) + if d < bestDist + bestDist = d + outBestPt = pts[s] return vis diff --git a/game-ai/ground/wto_ai_slots_common.das b/game-ai/ground/wto_ai_slots_common.das index fd19219..fe81acc 100644 --- a/game-ai/ground/wto_ai_slots_common.das +++ b/game-ai/ground/wto_ai_slots_common.das @@ -23,7 +23,7 @@ def public wto_slots_find(bots : WtoBotSlot[64]; eid : EntityId) : int // Frees the unit's slot and clears engagement counters aimed at it; true when a slot was freed. [never_inline] -def public wto_slots_forget(var bots : WtoBotSlot[64]; eid : EntityId) : bool +def public wto_slots_forget(var bots : WtoBotSlot[64]&; eid : EntityId) : bool let idx = wto_slots_find(bots, eid) if idx >= 0 if bots[idx].drive.routeBOwned @@ -38,7 +38,7 @@ def public wto_slots_forget(var bots : WtoBotSlot[64]; eid : EntityId) : bool // The unit's slot, taking a free one for a new unit (then `created` is set); -1 when full. [never_inline] -def public wto_slots_acquire(var bots : WtoBotSlot[64]; eid : EntityId; army : int; now : float; +def public wto_slots_acquire(var bots : WtoBotSlot[64]&; eid : EntityId; army : int; now : float; var created : bool&) : int let cap = min(WTO_MAX_BOTS, WTO_AI_MAX_TRACKED_BOTS) var freeIdx = -1 @@ -63,7 +63,7 @@ def public wto_slots_acquire(var bots : WtoBotSlot[64]; eid : EntityId; army : i // Releases vehicle control of every bot and clears all slots. [never_inline] -def public wto_slots_reset_all(var bots : WtoBotSlot[64]) +def public wto_slots_reset_all(var bots : WtoBotSlot[64]&) for i in range(WTO_MAX_BOTS) if bots[i].drive.routeBOwned wto_drive_request_control(bots[i].eid, 0) @@ -72,7 +72,7 @@ def public wto_slots_reset_all(var bots : WtoBotSlot[64]) // Slots not refreshed by the pipeline for a while belong to units that are gone. [never_inline] -def public wto_slots_drop_stale(var bots : WtoBotSlot[64]; now : float) +def public wto_slots_drop_stale(var bots : WtoBotSlot[64]&; now : float) for i in range(WTO_MAX_BOTS) if bots[i].used && (now - bots[i].lastSeenAt) > 3.5 bots[i] = WtoBotSlot() @@ -92,7 +92,7 @@ def public wto_slots_phys_available(bots : WtoBotSlot[64]) : bool // A hit on `eid` by `offEid`: confirms an effective shot of our firing bot (resetting its stalemate // counters) and gives our damaged bot the direction it was hit from (never the offender's position). [never_inline] -def public wto_slots_on_damage(world : WtoWorldSnap const&; var bots : WtoBotSlot[64]; eid, offEid : EntityId; +def public wto_slots_on_damage(world : WtoWorldSnap const&; var bots : WtoBotSlot[64]&; eid, offEid : EntityId; u : Unit const?; hitPos : float3; hpDropped : bool; now : float) let offBotIdx = wto_slots_find(bots, offEid) if offBotIdx >= 0 && bots[offBotIdx].army != int(u.army) && hpDropped diff --git a/game-ai/ground/wto_ai_specs_common.das b/game-ai/ground/wto_ai_specs_common.das index 60ebdfb..51e6c12 100644 --- a/game-ai/ground/wto_ai_specs_common.das +++ b/game-ai/ground/wto_ai_specs_common.das @@ -16,6 +16,8 @@ require IGroundModel require HeavyVehicleModel require Weapon require WTBallistics +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_weapon_profile_common require %game.utils.utils_common require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_combat_types_common @@ -36,18 +38,14 @@ def private wto_parse_role_strings(unitType : string; expClass : string; isLight [never_inline] def private wto_record_shell_block(bBlk : DataBlock const&; var spec : WtoVehicleSpec&; isDefault : bool) - let spd = bBlk |> datablock_getReal("speed", 0.0) - if spd <= 80.0 || spd >= 2600.0 + var shell = WtoShellProfile() + if !wto_profile_read(bBlk, shell) return - let cx = clamp(bBlk |> datablock_getReal("Cx", 0.35), 0.05, 1.5) - let mass = clamp(bBlk |> datablock_getReal("mass", 10.0), 0.05, 250.0) - let rawCal = bBlk |> datablock_getReal("ballisticCaliber", 0.0) - let cal = clamp(rawCal > 0.002 ? rawCal : bBlk |> datablock_getReal("caliber", 0.09), 0.005, 0.4) if isDefault && spec.shellCount == 0 - spec.muzzleSpeedMps = spd - spec.shellDragCx = cx - spec.shellMassKg = mass - spec.shellCaliberM = cal + spec.muzzleSpeedMps = shell.speedMps + spec.shellDragCx = shell.dragCx + spec.shellMassKg = shell.massKg + spec.shellCaliberM = shell.caliberM let bName = bBlk |> datablock_getStr("bulletName", "") if empty(bName) || spec.shellCount >= WTO_MAX_SHELL_PROFILES return @@ -57,29 +55,26 @@ def private wto_record_shell_block(bBlk : DataBlock const&; var spec : WtoVehicl return let idx = spec.shellCount let bt = bBlk |> datablock_getStr("bulletType", "") - let isSoft = find(bt, "he_frag") >= 0 || find(bt, "hesh") >= 0 + let isSoft = find(bt, "he_frag") >= 0 || find(bt, "hesh") >= 0 || find(bt, "he_part") >= 0 || find(bt, "heat") >= 0 let isNonCombat = find(bt, "smoke") >= 0 || find(bt, "practice") >= 0 || find(bt, "shrapnel") >= 0 - spec.shells[idx].nameHash = h - spec.shells[idx].speedMps = spd - spec.shells[idx].dragCx = cx - spec.shells[idx].massKg = mass - spec.shells[idx].caliberM = cal - spec.shells[idx].isSoftShell = isSoft - spec.shells[idx].isAntiArmor = !isSoft && !isNonCombat - spec.shells[idx].penMm = float(calc_max_penetration(bBlk)) + shell.nameHash = h + shell.isSoftShell = isSoft + shell.isAntiArmor = !isSoft && !isNonCombat || find(bt, "heat") >= 0 + shell.penMm = float(calc_max_penetration(bBlk)) + spec.shells[idx] = shell spec.shellCount = idx + 1 [never_inline] -def private wto_parse_weapon_blk(weapBlkPath : string; var spec : WtoVehicleSpec&) +def private wto_parse_weapon_blk(weapBlkPath : string; beltMount : bool; var spec : WtoVehicleSpec&) if empty(weapBlkPath) || find(weapBlkPath, "dummy_weapon") >= 0 return datablock_load_cached(weapBlkPath, DataBlockReadFlag.ROBUST) <| $(wBlk) let isRocket = wBlk |> datablock_getBool("rocketGun", false) let isCannon = wBlk |> datablock_getBool("cannon", false) - let isBelt = wBlk |> datablock_getBool("isBulletBelt", false) if isRocket && !isCannon return - spec.isAutocannonBelt = isBelt + spec.isAutocannon = beltMount || wto_profile_is_automatic(wBlk) + spec.reloadSec = wBlk |> datablock_getReal("reloadTime", 0.0) spec.shellCount = 0 datablock_for_each_block(wBlk, "bullet") <| $(bBlk) wto_record_shell_block(bBlk, spec, true) @@ -130,7 +125,8 @@ def private wto_parse_unit_blk(className : string; isLightTag : bool; var spec : let stabBlk = weapBlk |> datablock_get_block_by_name("gunStabilizer") if stabBlk != null spec.hasVertStab = *stabBlk |> datablock_getBool("hasVertical", false) - wto_parse_weapon_blk(wPath, spec) + let beltMount = weapBlk |> datablock_getBool("isBulletBelt", false) + wto_parse_weapon_blk(wPath, beltMount, spec) return loaded [never_inline] diff --git a/game-ai/ground/wto_ai_stats_common.das b/game-ai/ground/wto_ai_stats_common.das index ed37fc1..b1283c0 100644 --- a/game-ai/ground/wto_ai_stats_common.das +++ b/game-ai/ground/wto_ai_stats_common.das @@ -91,8 +91,8 @@ def private wto_stats_spot(now : float; groundTgt : bool; var slot : WtoBotSlot& [never_inline] def private wto_stats_shots(myPos : float3; var slot : WtoBotSlot&; var bs : WtoBattleStats&) assume st = slot.stats - bs.auxShots += slot.trigger.coaxShots - st.lastAuxShots - st.lastAuxShots = slot.trigger.coaxShots + bs.auxShots += slot.trigger.auxShots - st.lastAuxShots + st.lastAuxShots = slot.trigger.auxShots let fired = slot.fire.shotCount - st.lastShots st.lastShots = slot.fire.shotCount if fired <= 0 @@ -104,22 +104,22 @@ def private wto_stats_shots(myPos : float3; var slot : WtoBotSlot&; var bs : Wto if abs(slot.drive.lastVFwd) >= WTO_AI_PF_STATIONARY_MPS bs.movingShots[role] += fired bs.bandMoving[band] += fired - if slot.spec.isAutocannonBelt + if slot.spec.isAutocannon bs.acShots += fired // A shooting window: a ground target seen clearly within engagement range and the gun ready. [never_inline] def private wto_stats_window(dt : float; myPos : float3; groundTgt : bool; slot : WtoBotSlot const&; var bs : WtoBattleStats&) - // A belt-fed autocannon is briefly not ready between rounds; that still counts as a window. - let ready = slot.fire.gunReady || slot.spec.isAutocannonBelt + // An autocannon is briefly not ready between rounds; that still counts as a window. + let ready = slot.fire.gunReady || slot.spec.isAutocannon if !groundTgt || !ready || slot.fire.reloading return if wto_xz_dist_sq(myPos, slot.perceive.knownPos) > WTO_AI_FC_MAX_RANGE_M * WTO_AI_FC_MAX_RANGE_M return bs.windowSec[wto_stats_role(slot)] += dt bs.denySec[clamp(slot.fire.lastDenyReason, 0, WTO_DENY_COUNT - 1)] += dt - if slot.spec.isAutocannonBelt + if slot.spec.isAutocannon bs.acWindowSec += dt // The nearest enemy ground vehicle within statsSampleRangeM if it is in line of sight, else -1. diff --git a/game-ai/ground/wto_ai_tactics_actions_common.das b/game-ai/ground/wto_ai_tactics_actions_common.das index 46b16cd..45bb656 100644 --- a/game-ai/ground/wto_ai_tactics_actions_common.das +++ b/game-ai/ground/wto_ai_tactics_actions_common.das @@ -42,24 +42,30 @@ def public wto_friendly_retreat_dir(world : WtoWorldSnap const&; army : int; return wto_xz_normalize(blended, toSpawn) return wto_xz_normalize(-threatDir, float3(1.0, 0.0, 0.0)) +[never_inline] +def public wto_sm_handle_spaa(world : WtoWorldSnap const&; now : float; + myPos, threatDir : float3; distXZ : float; var slot : WtoBotSlot&) : bool + assume p = slot.perceive + if slot.spec.role != WTO_ROLE_SPAA || !p.hasClearLos || !p.targetEid + return false + if p.targetIsAir + slot.tactics.spaaYieldAir = true + wto_sm_set_state(now, WTO_STATE_MARCH, myPos, 0.0, "spaa_air_engage", distXZ, slot) + return true + if distXZ >= 220.0 + return false + let backDir = wto_friendly_retreat_dir(world, slot.army, myPos, threatDir) + let goal = wto_clamp_battle_xz(myPos + backDir * 70.0, world.battleCenter, world.battleRadius, 40.0) + wto_sm_set_state(now, WTO_STATE_DISABLED, goal, slot.spec.vMaxFwd, "spaa_evade_tank", distXZ, slot) + return true + [never_inline] def public wto_sm_handle_disabled_and_repair(world : WtoWorldSnap const&; now : float; - myPos, threatPos, threatDir : float3; - isBurn : bool; repairRemainingSec, distXZ : float; - var slot : WtoBotSlot&) : bool + myPos, threatPos, threatDir : float3; + isBurn : bool; repairRemainingSec, distXZ : float; + var slot : WtoBotSlot&) : bool assume tac = slot.tactics assume p = slot.perceive - tac.spaaYieldAir = false - if slot.spec.role == WTO_ROLE_SPAA - if p.hasClearLos && p.targetIsAir && !!p.targetEid - tac.spaaYieldAir = true - wto_sm_set_state(now, WTO_STATE_MARCH, myPos, 0.0, "spaa_air_engage", distXZ, slot) - return true - if p.hasClearLos && !p.targetIsAir && !!p.targetEid && distXZ < 220.0 - let backDir = wto_friendly_retreat_dir(world, slot.army, myPos, threatDir) - let goal = wto_clamp_battle_xz(myPos + backDir * 70.0, world.battleCenter, world.battleRadius, 40.0) - wto_sm_set_state(now, WTO_STATE_DISABLED, goal, slot.spec.vMaxFwd, "spaa_evade_tank", distXZ, slot) - return true // Engine/tracks broken (cannot move): halt in place and request native repair; gun keeps self-defending. if tac.immobilized diff --git a/game-ai/ground/wto_ai_tactics_common.das b/game-ai/ground/wto_ai_tactics_common.das index 5b51546..4d0b2cc 100644 --- a/game-ai/ground/wto_ai_tactics_common.das +++ b/game-ai/ground/wto_ai_tactics_common.das @@ -1,7 +1,7 @@ // Hull channel (decision layer design, section 7), once per tactics tick: damage/repair and ridge // withdrawal take over at once; otherwise the behavior chosen by score (wto_ai_behavior_common.das) // runs as a small action that sets the goal, speed and WTO_STATE_* for navigation. The facing -// constraint and the reverse-travel decision (wto_ai_facing_common.das) are updated every tick. +// constraint is updated here, while navigation decides the direction to follow its corridor. // A behavior that ends by itself (shot taken, cover reached and reloaded, no cover found) is // replaced in the same tick. options indenting = 2 @@ -27,11 +27,16 @@ require %appGame.wtoai.wto_ai_facing_common def private wto_sm_sync_engagement_counters(dt : float; var slot : WtoBotSlot&) assume tac = slot.tactics assume p = slot.perceive - if p.hasClearLos && !!p.targetEid && !p.targetIsAir && tac.engageTargetEid != p.targetEid - tac.engageTargetEid = p.targetEid - tac.engageShotsNoEffect = 0 - tac.engageNoShotHalts = 0 - tac.engageTotalHaltSec = 0.0 + let shots = slot.fire.shotCount - tac.engageObservedShots + tac.engageObservedShots = slot.fire.shotCount + if p.hasClearLos && !!p.targetEid && !p.targetIsAir + if tac.engageTargetEid != p.targetEid + tac.engageTargetEid = p.targetEid + tac.engageShotsNoEffect = 0 + tac.engageNoShotHalts = 0 + tac.engageTotalHaltSec = 0.0 + elif shots > 0 && slot.fire.lastShotAt > tac.lastEffectAt + tac.engageShotsNoEffect += shots if tac.state == WTO_STATE_SHORT_HALT tac.engageTotalHaltSec += dt @@ -91,21 +96,20 @@ def private wto_sm_march_speed(slot : WtoBotSlot const&; distGoal : float) : flo // Short halt (7.1): stand until the shot leaves, the reload starts, the target is gone or // stateMachine.shortHaltMaxSec runs out; then a cooldown of shortHaltCooldownSec. [never_inline] -def private wto_tac_halt(now : float; myPos : float3; c : WtoBhvCtx const&; var slot : WtoBotSlot&) : bool +def private wto_tac_halt(now : float; myPos, hullFwd : float3; c : WtoBhvCtx const&; var slot : WtoBotSlot&) : bool assume tac = slot.tactics if tac.state != WTO_STATE_SHORT_HALT + wto_face_accept_gun(hullFwd, slot) wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "halt_for_shot", c.distTarget, slot) return true let shots = slot.fire.shotCount - tac.haltStartShots - if shots > 0 - tac.engageShotsNoEffect += shots - tac.haltStartShots = slot.fire.shotCount let timeout = (now - tac.haltEnterAt) >= WTO_AI_SM_SHORT_HALT_MAX_SEC if timeout && shots <= 0 tac.engageNoShotHalts++ if shots > 0 || timeout || slot.fire.reloading || !c.hasTarget || !c.stopRangeOk tac.shortHaltCooldownUntil = now + WTO_AI_SM_SHORT_HALT_COOLDOWN_SEC return false + wto_face_accept_gun(hullFwd, slot) wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "halt_hold", c.distTarget, slot) return true @@ -117,15 +121,15 @@ def private wto_tac_engage(now : float; c : WtoBhvCtx const&; var slot : WtoBotS var speed = march assume tr = slot.trigger let fresh = (now - tr.wantSpeedAt) <= WTO_AI_TACTICS_TICK_SEC * 3.0 - if fresh && tr.wantSpeedMps > WTO_AI_FC_STOP_SPEED_MAX_MPS && tr.wantSpeedMps < march + let crossExposed = c.urgent && wto_face_side_exposed(slot) + if fresh && tr.targetEid == slot.perceive.targetEid && !crossExposed && tr.wantSpeedMps > WTO_AI_FC_STOP_SPEED_MAX_MPS && tr.wantSpeedMps < march speed = lerp(tr.wantSpeedMps, march, c.urgent ? WTO_AI_BHV_URGENT_SPEED_KEEP : 0.0) wto_sm_set_state(now, WTO_STATE_RUN_AND_GUN, c.baseGoal, speed, "engage", c.distTarget, slot) return true [never_inline] def private wto_tac_hold(now : float; myPos, hullFwd : float3; c : WtoBhvCtx const&; var slot : WtoBotSlot&) : bool - assume tac = slot.tactics - tac.hullAngleDir = tac.faceActive ? tac.faceDir : hullFwd + wto_face_accept_gun(hullFwd, slot) let why = c.holdReason == WTO_HOLD_WATCH ? "watch_last_exit" : (c.holdReason == WTO_HOLD_RALLY ? "rally_wait" : "hold_post") wto_sm_set_state(now, WTO_STATE_HULL_ANGLE, myPos, 0.0, why, c.distTarget, slot) return c.holdReason != WTO_HOLD_NONE @@ -155,7 +159,7 @@ def private wto_tac_run(world : WtoWorldSnap const&; now : float; myPos, hullFwd if bhv == WTO_BHV_ENGAGE return c.hasTarget && wto_tac_engage(now, c, slot) if bhv == WTO_BHV_HALT - return wto_tac_halt(now, myPos, c, slot) + return wto_tac_halt(now, myPos, hullFwd, c, slot) if bhv == WTO_BHV_COVER return wto_tac_cover(world, now, myPos, hullFwd, c, slot) if bhv == WTO_BHV_REPOSITION @@ -177,13 +181,16 @@ def public wto_tactics_update(world : WtoWorldSnap const&; now, dt : float; if !WTO_AI_LAYER_TACTICS wto_sm_set_state(now, WTO_STATE_MARCH, slot.order.valid ? slot.order.goalPos : myPos, slot.spec.vMaxFwd * 0.9, "layer_off", 9999.0, slot) return + wto_sm_sync_engagement_counters(dt, slot) + wto_face_update(now, myPos, hullFwd, slot) var c = WtoBhvCtx() wto_bhv_context(world, now, myPos, hullFwd, wto_sm_reposition_stale(now, slot), slot, c) - wto_sm_sync_engagement_counters(dt, slot) wto_cover_update_memory(world, now, myPos, slot) - wto_face_update(now, myPos, hullFwd, slot) + slot.tactics.spaaYieldAir = false if wto_sm_handle_disabled_and_repair(world, now, myPos, c.threatPos, c.threatDir, isBurn, repairRemainingSec, c.distTarget, slot) wto_bhv_take_over(now, WTO_BHV_REPAIR, slot) + elif wto_sm_handle_spaa(world, now, myPos, c.threatDir, c.distTarget, slot) + wto_bhv_take_over(now, slot.tactics.spaaYieldAir ? WTO_BHV_HOLD : WTO_BHV_WITHDRAW, slot) elif wto_sm_handle_ridge(world, now, myPos, c.threatDir, c.distTarget, slot) wto_bhv_take_over(now, WTO_BHV_WITHDRAW, slot) else @@ -191,5 +198,7 @@ def public wto_tactics_update(world : WtoWorldSnap const&; now, dt : float; if !wto_tac_run(world, now, myPos, hullFwd, c, slot, crowdSummary) wto_bhv_choose(now, c, true, slot) if !wto_tac_run(world, now, myPos, hullFwd, c, slot, crowdSummary) + wto_bhv_take_over(now, WTO_BHV_ADVANCE, slot) wto_tac_advance(now, myPos, c, slot) - wto_face_reverse_update(now, c.distGoal, slot) + if !slot.tactics.faceForGun + slot.tactics.gunFacingTarget = INVALID_ENTITY_ID diff --git a/game-ai/ground/wto_ai_traverse_common.das b/game-ai/ground/wto_ai_traverse_common.das index e24d3a6..e9fe26b 100644 --- a/game-ai/ground/wto_ai_traverse_common.das +++ b/game-ai/ground/wto_ai_traverse_common.das @@ -27,7 +27,7 @@ def private wto_valid_angle_range(angles : float2) : bool return wto_is_finite(angles.x) && wto_is_finite(angles.y) && angles.x <= angles.y [never_inline] -def private wto_read_gunner_mount(className : string; triggerNo, weaponIndex : int; +def public wto_read_gunner_mount(className : string; triggerNo, weaponIndex : int; readMount : block<(mount : DataBlock) : void>) if empty(className) || triggerNo < WTO_FIRST_GUNNER_TRIGGER || weaponIndex < 0 return @@ -40,7 +40,7 @@ def private wto_read_gunner_mount(className : string; triggerNo, weaponIndex : i datablock_for_each_block(*common, "Weapon") <| $(mount) if (mount |> datablock_getStr("trigger", "")) != trigger return - if index == weaponIndex && (mount |> datablock_getStr("triggerGroup", "primary")) == "primary" + if index == weaponIndex invoke(readMount, mount) index++ @@ -177,9 +177,35 @@ def public wto_drive_mounted_gun(var unit : Unit?; className : string; dt : floa let pitchDelta = clamp(wishPitchDeg - fc.curPitchDeg, -maxPitchStep, maxPitchStep) turret.pitchLim = clamp(fc.curPitchDeg + pitchDelta, pitch.x, pitch.y) break - if fc.traverse.known - var uPos = unit.pos - updateWeaponAnims(*unit.weap, dtStep, 1.0, uPos) + +// Secondary mounts with their own limits can track independently. Coaxial mounts with no +// limits follow the main turret through the stock weapon animation. +[never_inline] +def public wto_aim_aux_mount(var unit : Unit?; className : string; dt : float; turretNo : int; + wishDir : float3; var cached : WtoMountFire&) : bool + assume turret = unit.weap.turret[turretNo] + let triggerNo = int(turret.triggerNo) + let weaponIndex = int(turret.weaponIndex) + if !cached.traverseReady + wto_load_gun_traverse(className, triggerNo, weaponIndex, cached.traverse) + cached.traverseReady = true + if !cached.traverse.known + return false + var wishYaw = 0.0 + var wishPitch = 0.0 + wto_world_to_hull_deg(wishDir, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2], wishYaw, wishPitch) + let step = clamp(dt, 0.005, 0.12) + let cmdYaw = wto_step_mounted_yaw(turret.currentState.yaw, wishYaw, step * 24.0, cached.traverse.yaw) + let pitch = wto_gun_pitch_at_yaw(className, triggerNo, weaponIndex, cmdYaw, cached.traverse) + turret.yawLim = cmdYaw + if pitch.x <= pitch.y + let pitchChange = clamp(wishPitch - turret.currentState.pitch, -step * 10.0, step * 10.0) + turret.pitchLim = clamp(turret.currentState.pitch + pitchChange, pitch.x, pitch.y) + return true + +def public wto_apply_weapon_aim(var unit : Unit?; dt : float) + var pos = unit.pos + updateWeaponAnims(*unit.weap, clamp(dt, 0.005, 0.12), 1.0, pos) def public wto_set_hull_aim(unit : Unit const?; active : bool; wishYaw : float; liveBarrelDir : float3; var slot : WtoBotSlot&) diff --git a/game-ai/ground/wto_ai_trigger_common.das b/game-ai/ground/wto_ai_trigger_common.das index f63b4c6..5705072 100644 --- a/game-ai/ground/wto_ai_trigger_common.das +++ b/game-ai/ground/wto_ai_trigger_common.das @@ -31,10 +31,15 @@ def private wto_trig_window(half, offset, sigma : float) : float return clamp(0.5 * (wto_trig_erf((half - offset) / s) + wto_trig_erf((half + offset) / s)), 0.0, 1.0) // Hit probability against a target `halfW` x `halfH` metres at `dist` (angles in radians). -def private wto_trig_prob(halfW, halfH, dist, offsetRad, sigmaRad : float) : float - let o = offsetRad * 0.7071 +def private wto_trig_prob(halfW, halfH, dist : float; offset : float2; sigmaRad : float) : float let d = max(dist, 5.0) - return wto_trig_window(atan2(halfW, d), o, sigmaRad) * wto_trig_window(atan2(halfH, d), o, sigmaRad) + return wto_trig_window(atan2(halfW, d), offset.x, sigmaRad) * wto_trig_window(atan2(halfH, d), offset.y, sigmaRad) + +def public wto_trig_aim_error(actual, wanted : float3) : float2 + let across = wto_xz_normalize(float3(-wanted.z, 0.0, wanted.x), float3(0.0, 0.0, 1.0)) + let up = cross(across, wanted) + let ahead = dot(actual, wanted) + return float2(atan2(dot(actual, across), ahead), atan2(dot(actual, up), ahead)) // Expected angular spread of a shot (radians) at own speed and hull turn rate. def private wto_trig_sigma(spec : WtoVehicleSpec const&; speedMps, turnDegSec, leadErrM, dist : float) : float @@ -46,7 +51,7 @@ def private wto_trig_sigma(spec : WtoVehicleSpec const&; speedMps, turnDegSec, l return sqrt(base * base + move * move + lead * lead) // Half width and half height (m) of the visible part of the target as seen from `myPos`. -def private wto_trig_target_half(myPos : float3; tgt : WtoUnitSnap const&; dist : float; visCount : int; +def public wto_trig_target_half(myPos : float3; tgt : WtoUnitSnap const&; dist : float; visCount : int; var halfW, halfH : float&) let los = wto_xz_normalize(tgt.pos - myPos, float3(1.0, 0.0, 0.0)) let perp = float3(-los.z, 0.0, los.x) @@ -61,7 +66,7 @@ def private wto_trig_target_half(myPos : float3; tgt : WtoUnitSnap const&; dist // has just fired (reloading) or is about to slip out of sight; higher for big slow-loading guns // and while pulling back to cover. [never_inline] -def private wto_trig_threshold(now, dist : float; fleeting : bool; slot : WtoBotSlot const&) : float +def private wto_trig_threshold(now, dist, reloadSec : float; ammo : int; slot : WtoBotSlot const&) : float assume p = slot.perceive var thr = WTO_AI_FC_FIRE_THRESHOLD for i in range(slot.threat.count) @@ -71,9 +76,11 @@ def private wto_trig_threshold(now, dist : float; fleeting : bool; slot : WtoBot thr -= WTO_AI_FC_CLOSE_BONUS * (1.0 - dist / WTO_AI_FC_CLOSE_RANGE_M) if now - p.targetShotAt <= WTO_AI_FC_ENEMY_RELOAD_SEC thr -= WTO_AI_FC_ENEMY_RELOAD_BONUS - if fleeting + if p.targetFleeting thr -= WTO_AI_FC_FLEETING_BONUS - thr += WTO_AI_FC_BIG_GUN_PENALTY * clamp((slot.fire.activeCaliberM - 0.075) / 0.05, 0.0, 1.0) + thr += WTO_AI_FC_RELOAD_PENALTY * clamp(reloadSec / WTO_AI_FC_LONG_RELOAD_SEC, 0.0, 1.0) + if ammo >= 0 && ammo < WTO_AI_FC_LOW_AMMO_ROUNDS + thr += WTO_AI_FC_LOW_AMMO_PENALTY * (1.0 - float(ammo) / float(WTO_AI_FC_LOW_AMMO_ROUNDS)) if slot.tactics.state == WTO_STATE_RETREAT_COVER thr += WTO_AI_FC_RETREAT_PENALTY return clamp(thr, WTO_AI_FC_MIN_THRESHOLD, 0.95) @@ -82,15 +89,15 @@ def private wto_trig_threshold(now, dist : float; fleeting : bool; slot : WtoBot // threshold: 99 when the current speed is fine or when even standing would not help. [never_inline] def private wto_trig_speed_request(spec : WtoVehicleSpec const&; halfW, halfH, dist, leadErrM, speedNow, thr : float) : float - if wto_trig_prob(halfW, halfH, dist, 0.0, wto_trig_sigma(spec, speedNow, 0.0, leadErrM, dist)) >= thr + if wto_trig_prob(halfW, halfH, dist, float2(0.0, 0.0), wto_trig_sigma(spec, speedNow, 0.0, leadErrM, dist)) >= thr return 99.0 - if wto_trig_prob(halfW, halfH, dist, 0.0, wto_trig_sigma(spec, 0.0, 0.0, leadErrM, dist)) < thr + if wto_trig_prob(halfW, halfH, dist, float2(0.0, 0.0), wto_trig_sigma(spec, 0.0, 0.0, leadErrM, dist)) < thr return 99.0 var lo = 0.0 var hi = speedNow for _i in range(6) let mid = 0.5 * (lo + hi) - if wto_trig_prob(halfW, halfH, dist, 0.0, wto_trig_sigma(spec, mid, 0.0, leadErrM, dist)) >= thr + if wto_trig_prob(halfW, halfH, dist, float2(0.0, 0.0), wto_trig_sigma(spec, mid, 0.0, leadErrM, dist)) >= thr lo = mid else hi = mid @@ -101,7 +108,7 @@ def private wto_trig_speed_request(spec : WtoVehicleSpec const&; halfW, halfH, d // the autocannon aim slack and the speed request. True when the shot is good enough. [never_inline] def public wto_trig_evaluate(world : WtoWorldSnap const&; now : float; myPos : float3; speedNow, turnDegSec, - dist, aimErrDeg : float; var slot : WtoBotSlot&) : bool + dist : float; offset : float2; var slot : WtoBotSlot&) : bool assume tr = slot.trigger assume p = slot.perceive let tgtIdx = wto_world_find_unit(world, p.targetEid) @@ -119,13 +126,16 @@ def public wto_trig_evaluate(world : WtoWorldSnap const&; now : float; myPos : f let tof = dist / max(120.0, slot.fire.activeSpeedMps) let leadErrM = latSpeed * tof * WTO_AI_EST_LEAD_ERR_FRAC * (1.0 - 0.72 * p.velQuality) let sigma = wto_trig_sigma(slot.spec, speedNow, turnDegSec, leadErrM, dist) - let fleeting = latSpeed >= WTO_AI_FC_FLEETING_LAT_MPS && p.visiblePointCount < 3 - tr.threshold = wto_trig_threshold(now, dist, fleeting, slot) - tr.hitProb = wto_trig_prob(halfW, halfH, dist, aimErrDeg * WTO_DEG_TO_RAD, sigma) - tr.hitProbAligned = wto_trig_prob(halfW, halfH, dist, 0.0, sigma) + tr.threshold = wto_trig_threshold(now, dist, slot.spec.reloadSec, slot.fire.ammoRemaining, slot) + tr.hitProb = wto_trig_prob(halfW, halfH, dist, offset, sigma) + tr.hitProbAligned = wto_trig_prob(halfW, halfH, dist, float2(0.0, 0.0), sigma) tr.aimSlackDeg = max(WTO_AI_FC_BASE_ALIGN_DEG, WTO_AI_FC_AC_AIM_SLACK * atan2(0.5 * (halfW + halfH), max(dist, 5.0)) * WTO_RAD_TO_DEG) - tr.wantSpeedMps = wto_trig_speed_request(slot.spec, halfW, halfH, dist, leadErrM, speedNow, tr.threshold) - tr.wantSpeedAt = now + if slot.fire.gunReady && !slot.fire.reloading && !slot.spec.isAutocannon + tr.wantSpeedMps = wto_trig_speed_request(slot.spec, halfW, halfH, dist, leadErrM, speedNow, tr.threshold) + tr.wantSpeedAt = now + else + tr.wantSpeedMps = 99.0 + tr.wantSpeedAt = -100.0 return tr.hitProb >= tr.threshold // Autocannon and coaxial bursts (decision layer design, 6.3): fire for burstSec, pause for @@ -144,8 +154,34 @@ def public wto_trig_burst_gate(now : float; aimOk : bool; var burstUntil, pauseU started = true return WTO_DENY_OK -// No engaged target: nothing is requested from the hull. -def public wto_trig_clear(var tr : WtoTriggerState&) +// Track burst schedules and speed requests by target. Leaving it starts a fresh opportunity. +def public wto_trig_set_target(eid : EntityId; var tr : WtoTriggerState&) + if eid == tr.targetEid + return + tr.targetEid = eid + tr.biasEpoch++ + tr.wantSpeedMps = 99.0 + tr.wantSpeedAt = -100.0 tr.hitProb = 0.0 tr.hitProbAligned = 0.0 - tr.wantSpeedMps = 99.0 + tr.burstUntil = -100.0 + tr.burstPauseUntil = -100.0 + tr.secondary = WtoWeaponBurst() + tr.coaxial = WtoWeaponBurst() + +[never_inline] +def public wto_trig_aux_aim_ok(now, dist, ownSpeed : float; aimErr : float2; myPos : float3; + target : WtoUnitSnap const&; mount : WtoMountFire const&; + slot : WtoBotSlot const&) : bool + var halfW = 0.0 + var halfH = 0.0 + wto_trig_target_half(myPos, target, dist, slot.perceive.visiblePointCount, halfW, halfH) + if mount.automatic + let slack = atan2(0.5 * (halfW + halfH), max(dist, 5.0)) * WTO_AI_FC_AC_AIM_SLACK + return length(aimErr) <= max(WTO_AI_FC_BASE_ALIGN_DEG * WTO_DEG_TO_RAD, slack) + let los = wto_xz_normalize(target.pos - myPos, float3(1.0, 0.0, 0.0)) + let lateral = abs(dot(slot.perceive.estVel, float3(-los.z, 0.0, los.x))) + let leadErr = lateral * (dist / mount.shell.speedMps) * WTO_AI_EST_LEAD_ERR_FRAC * (1.0 - 0.72 * slot.perceive.velQuality) + let turn = abs(slot.drive.omegaYawRad) * WTO_RAD_TO_DEG + let sigma = wto_trig_sigma(slot.spec, ownSpeed, turn, leadErr, dist) + return wto_trig_prob(halfW, halfH, dist, aimErr, sigma) >= wto_trig_threshold(now, dist, 0.0, -1, slot) diff --git a/game-ai/ground/wto_ai_types_common.das b/game-ai/ground/wto_ai_types_common.das index 79877f8..9373fb4 100644 --- a/game-ai/ground/wto_ai_types_common.das +++ b/game-ai/ground/wto_ai_types_common.das @@ -24,18 +24,16 @@ let public WTO_ROLE_SPAA = 4 let public WTO_STATE_MARCH = 0 let public WTO_STATE_RUN_AND_GUN = 1 -let public WTO_STATE_PREAIM = 2 let public WTO_STATE_SHORT_HALT = 3 let public WTO_STATE_RETREAT_COVER = 4 let public WTO_STATE_COVER_RELOAD = 5 -let public WTO_STATE_RELOAD_ADVANCE = 6 let public WTO_STATE_HULL_ANGLE = 7 let public WTO_STATE_REPOSITION = 8 let public WTO_STATE_DISABLED = 9 let public WTO_STATE_DISPERSE = 10 let public WTO_STATE_RIDGE_WITHDRAW = 11 -// Hull channel behaviors (decision layer design, 7.1), chosen by score in +// Hull channel behaviors, chosen by score in // wto_ai_behavior_common.das; each runs as one or more WTO_STATE_* actions. REPAIR and WITHDRAW // are not scored: they take over at once. let public WTO_BHV_ADVANCE = 0 @@ -67,7 +65,8 @@ struct public WtoVehicleSpec shellCaliberM : float = 0.09 shellCount : int = 0 shells : WtoShellProfile[12] - isAutocannonBelt : bool = false + isAutocannon : bool = false + reloadSec : float = 0.0 isPureLauncher : bool = false halfLen : float = 3.4 halfWid : float = 1.75 @@ -190,12 +189,12 @@ struct public WtoTacticsState retreatTarget : float3 = float3(0.0, 0.0, 0.0) retreatUntil : float = -100.0 retreatReverse : bool = false - hullAngleDir : float3 = float3(1.0, 0.0, 0.0) repositionGoal : float3 = float3(0.0, 0.0, 0.0) repositionOrigin : float3 = float3(0.0, 0.0, 0.0) repositionActive : bool = false engageTargetEid : EntityId = INVALID_ENTITY_ID engageShotsNoEffect : int = 0 + engageObservedShots : int = 0 engageNoShotHalts : int = 0 engageTotalHaltSec : float = 0.0 lastEffectAt : float = -100.0 @@ -217,6 +216,7 @@ struct public WtoTacticsState nextScoreAt : float = 0.0 scoredHasTarget : bool = false scoredReloading : bool = false + scoredNearThreat : bool = false scoredDamageAt : float = -100.0 coverFailedAt : float = -100.0 // Facing constraint (7.3): the hull should point along faceDir (within the facing tolerance) @@ -226,6 +226,8 @@ struct public WtoTacticsState faceDir : float3 = float3(1.0, 0.0, 0.0) faceThreatDir : float3 = float3(1.0, 0.0, 0.0) faceFromThreat : bool = false + faceForGun : bool = false + gunFacingTarget : EntityId = INVALID_ENTITY_ID reverseTravel : bool = false reverseSince : float = -100.0 diff --git a/game-ai/ground/wto_ai_unstick_common.das b/game-ai/ground/wto_ai_unstick_common.das index 4e349ff..99f87d1 100644 --- a/game-ai/ground/wto_ai_unstick_common.das +++ b/game-ai/ground/wto_ai_unstick_common.das @@ -19,17 +19,19 @@ require %appGame.wtoai.wto_ai_navquery_common require %appGame.wtoai.wto_ai_navmesh_common require %appGame.wtoai.wto_ai_follow_common -// Where to back up to: unstickReverseM back along the corridor (or straight back), cut short +// Move against the previous direction of travel along the corridor, cut short // where the mesh ends; false when there is no room behind. [never_inline] -def private wto_unstick_reverse_target(navState : int; myPos, hullFwd : float3; slot : WtoBotSlot const&; +def private wto_unstick_reverse_target(navState : int; myPos, hullFwd : float3; forward : bool; slot : WtoBotSlot const&; var target : float3&) : bool - if slot.nav.rearClearM < 2.5 + let clear = forward ? slot.nav.frontClearM : slot.nav.rearClearM + if clear < 2.5 return false assume rt = slot.route - let straightBack = myPos - hullFwd * WTO_AI_PF_UNSTICK_REV_M + let leaveDir = forward ? hullFwd : -hullFwd + let straightBack = myPos + leaveDir * WTO_AI_PF_UNSTICK_REV_M target = rt.corridorLen >= 2 ? wto_poly_walk_back(rt.corridor, rt.corridorLen, rt.segIdx, rt.segT, WTO_AI_PF_UNSTICK_REV_M) : straightBack - if wto_xz_dist_sq(myPos, target) < 4.0 + if wto_xz_dist_sq(myPos, target) < 4.0 || dot(target - myPos, leaveDir) <= 0.0 target = straightBack if navState != WTO_NAVMESH_LOADED || rt.tier < 0 return true @@ -44,9 +46,11 @@ def private wto_unstick_reverse_target(navState : int; myPos, hullFwd : float3; [never_inline] def private wto_unstick_start_reverse(navState : int; now : float; myPos, hullFwd : float3; var slot : WtoBotSlot&) var target = myPos - if !wto_unstick_reverse_target(navState, myPos, hullFwd, slot, target) + let forward = slot.tactics.reverseTravel + if !wto_unstick_reverse_target(navState, myPos, hullFwd, forward, slot, target) return slot.nav.reverseTarget = target + slot.nav.unstickForward = forward slot.nav.reverseUntil = now + WTO_AI_PF_UNSTICK_REV_SEC slot.nav.reverseCount++ @@ -105,19 +109,22 @@ def public wto_unstick_contact(var world : WtoWorldSnap&; navState : int; now : print("WTO_AI|NAV_CONTACT|eid={uint(slot.eid)}|repeat={nav.contactRepeats}|pos={myPos}|body={nav.contactBodyPos}\n") wto_unstick_start_reverse(navState, now, myPos, hullFwd, slot) -// Backing up after being stuck; true while the manoeuvre runs (the drive command is set). +// True while moving away from a blockage, with the drive command set. [never_inline] def public wto_unstick_reversing(now : float; myPos : float3; var slot : WtoBotSlot&) : bool assume nav = slot.nav if now >= nav.reverseUntil return false - if wto_xz_dist_sq(myPos, nav.reverseTarget) < 1.0 || nav.rearClearM < 2.1 + let clear = nav.unstickForward ? nav.frontClearM : nav.rearClearM + if wto_xz_dist_sq(myPos, nav.reverseTarget) < 1.0 || clear < 2.1 nav.reverseUntil = -100.0 nav.stuckCheckAt = -100.0 return false let dir = wto_xz_normalize(nav.reverseTarget - myPos, -nav.steerDir) nav.steerDir = dir - wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_REVERSE, nav.reverseTarget, dir, max(2.0, slot.spec.vMaxRev), nav.frontClearM, nav.rearClearM) + let mode = nav.unstickForward ? WTO_DRIVE_CRUISE : WTO_DRIVE_REVERSE + let speed = nav.unstickForward ? min(slot.spec.vMaxFwd, slot.spec.vMaxRev) : max(2.0, slot.spec.vMaxRev) + wto_drive_cmd_set(slot.driveCmd, mode, nav.reverseTarget, dir, speed, nav.frontClearM, nav.rearClearM) return true // Per nav tick while following: detects no progress and escalates through the three levels. diff --git a/game-ai/ground/wto_ai_weapon_profile_common.das b/game-ai/ground/wto_ai_weapon_profile_common.das new file mode 100644 index 0000000..23d429b --- /dev/null +++ b/game-ai/ground/wto_ai_weapon_profile_common.das @@ -0,0 +1,76 @@ +// Stock shell data for a gun mount's active ammunition. Modules sharing a trigger still check +// each available barrel and its ammunition before firing. +options indenting = 2 +options no_global_heap = true +module wto_ai_weapon_profile_common shared + +require ecs +require app +require math +require strings +require DagorDataBlock +require Unit +require Weapon +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_traverse_common + +def public wto_profile_read(bullet : DataBlock const&; var shell : WtoShellProfile&) : bool + let speed = bullet |> datablock_getReal("speed", 0.0) + if speed <= 80.0 || speed >= 2600.0 + return false + let cal = bullet |> datablock_getReal("ballisticCaliber", 0.0) + shell.speedMps = speed + shell.dragCx = clamp(bullet |> datablock_getReal("Cx", 0.35), 0.05, 1.5) + shell.massKg = clamp(bullet |> datablock_getReal("mass", 10.0), 0.05, 250.0) + shell.caliberM = clamp(cal > 0.002 ? cal : bullet |> datablock_getReal("caliber", 0.09), 0.005, 0.4) + return true + +def public wto_profile_is_automatic(weapon : DataBlock const&) : bool + let cannon = weapon |> datablock_getBool("cannon", false) + let belt = weapon |> datablock_getBool("isBulletBelt", false) + let rate = weapon |> datablock_getReal("shotFreq", 0.0) + return belt || (cannon && rate >= WTO_AI_FC_AC_MIN_RATE_HZ) + +def private wto_profile_match(bullet : DataBlock const&; var cached : WtoMountFire&) + let name = bullet |> datablock_getStr("bulletName", "") + if !cached.shellValid && !empty(name) && ecs_hash(name) == cached.shellHash + cached.shellValid = wto_profile_read(bullet, cached.shell) + +[never_inline] +def private wto_profile_read_weapon(mount : DataBlock const&; var cached : WtoMountFire&) + let path = mount |> datablock_getStr("blk", "") + if empty(path) + return + let belt = mount |> datablock_getBool("isBulletBelt", false) + datablock_load_cached(path, DataBlockReadFlag.ROBUST) <| $(weapon) + cached.automatic = belt || wto_profile_is_automatic(weapon) + datablock_for_each_block(weapon, "bullet") <| $(bullet) + wto_profile_match(bullet, cached) + if !cached.shellValid + datablock_for_each_block(weapon) <| $(set) + datablock_for_each_block(set, "bullet") <| $(bullet) + wto_profile_match(bullet, cached) + +// Cache per turret and loaded projectile. Every ballistic check uses that weapon's profile. +[never_inline] +def public wto_mount_load_shell(unit : Unit const?; className : string; turretNo : int; + gun : WTGun const?; var cached : WtoMountFire&) : bool + let idx = int(gun.chosenBulletType) + if idx < 0 || idx >= length(gun.properties.bulletSets) + return false + assume bulletSet = gun.properties.bulletSets[idx] + if length(bulletSet.bullet) == 0 || bulletSet.bullet[0] == null + return false + let name = bulletSet.bullet[0].getName + if empty(name) + return false + let hash = ecs_hash(name) + if cached.shellHash == hash + return cached.shellValid + cached.shellHash = hash + cached.shellValid = false + assume turret = unit.weap.turret[turretNo] + wto_read_gunner_mount(className, int(turret.triggerNo), int(turret.weaponIndex)) <| $(mount) + wto_profile_read_weapon(mount, cached) + return cached.shellValid diff --git a/packages/patcher/src/ground-ai/ground-ai-config.ts b/packages/patcher/src/ground-ai/ground-ai-config.ts index 6f88c9b..60ff06d 100644 --- a/packages/patcher/src/ground-ai/ground-ai-config.ts +++ b/packages/patcher/src/ground-ai/ground-ai-config.ts @@ -254,7 +254,15 @@ export interface GroundAiConfig { }; readonly behavior: { readonly scoreIntervalSec: number; - readonly minHoldSec: number; + readonly advanceHoldSec: number; + readonly engageHoldSec: number; + readonly haltHoldSec: number; + readonly coverHoldSec: number; + readonly repositionHoldSec: number; + readonly postHoldSec: number; + readonly disperseHoldSec: number; + readonly targetValueWeight: number; + readonly nearThreatHaltBonus: number; readonly switchMargin: number; readonly advanceScore: number; readonly engageScore: number; @@ -272,9 +280,8 @@ export interface GroundAiConfig { readonly hullAngleDeg: number; readonly faceToleranceDeg: number; readonly faceMinDanger: number; - readonly faceHaltLimitDeg: number; readonly reverseTravelAngleDeg: number; - readonly reverseMaxGoalDistM: number; + readonly reverseMaxTurnDistM: number; readonly reverseMinSpeedMps: number; readonly reverseHoldSec: number; }; @@ -302,13 +309,18 @@ export interface GroundAiConfig { readonly enemyReloadSec: number; readonly fleetingThresholdBonus: number; readonly fleetingLateralMps: number; - readonly bigGunThresholdPenalty: number; + readonly fleetingLookAheadSec: number; + readonly reloadThresholdPenalty: number; + readonly longReloadSec: number; + readonly lowAmmoRounds: number; + readonly lowAmmoThresholdPenalty: number; + readonly aimSkill: number; + readonly autocannonMinShotsPerSec: number; readonly retreatThresholdPenalty: number; readonly minShotIntervalSec: number; readonly autocannonAimSlack: number; readonly burstSec: number; readonly burstPauseSec: number; - readonly burstRecheckSec: number; readonly autocannonReloadDetectSec: number; readonly auxWeapons: boolean; readonly auxMaxRangeM: number; @@ -496,7 +508,15 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['WTO_AI_TURRET_SCAN_ARC_DEG', 'float', c.turret.scanArcDeg], ['WTO_AI_TURRET_SCAN_PERIOD_SEC', 'float', c.turret.scanPeriodSec], ['WTO_AI_BHV_SCORE_SEC', 'float', c.behavior.scoreIntervalSec], - ['WTO_AI_BHV_MIN_HOLD_SEC', 'float', c.behavior.minHoldSec], + ['WTO_AI_BHV_ADVANCE_HOLD_SEC', 'float', c.behavior.advanceHoldSec], + ['WTO_AI_BHV_ENGAGE_HOLD_SEC', 'float', c.behavior.engageHoldSec], + ['WTO_AI_BHV_HALT_HOLD_SEC', 'float', c.behavior.haltHoldSec], + ['WTO_AI_BHV_COVER_HOLD_SEC', 'float', c.behavior.coverHoldSec], + ['WTO_AI_BHV_REPOSITION_HOLD_SEC', 'float', c.behavior.repositionHoldSec], + ['WTO_AI_BHV_POST_HOLD_SEC', 'float', c.behavior.postHoldSec], + ['WTO_AI_BHV_DISPERSE_HOLD_SEC', 'float', c.behavior.disperseHoldSec], + ['WTO_AI_BHV_TARGET_VALUE_W', 'float', c.behavior.targetValueWeight], + ['WTO_AI_BHV_NEAR_HALT_BONUS', 'float', c.behavior.nearThreatHaltBonus], ['WTO_AI_BHV_SWITCH_MARGIN', 'float', c.behavior.switchMargin], ['WTO_AI_BHV_ADVANCE', 'float', c.behavior.advanceScore], ['WTO_AI_BHV_ENGAGE', 'float', c.behavior.engageScore], @@ -514,9 +534,8 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['WTO_AI_BHV_HULL_ANGLE_DEG', 'float', c.behavior.hullAngleDeg], ['WTO_AI_BHV_FACE_TOL_DEG', 'float', c.behavior.faceToleranceDeg], ['WTO_AI_BHV_FACE_MIN_DANGER', 'float', c.behavior.faceMinDanger], - ['WTO_AI_BHV_FACE_HALT_LIMIT_DEG', 'float', c.behavior.faceHaltLimitDeg], ['WTO_AI_BHV_REVERSE_ANGLE_DEG', 'float', c.behavior.reverseTravelAngleDeg], - ['WTO_AI_BHV_REVERSE_MAX_GOAL_M', 'float', c.behavior.reverseMaxGoalDistM], + ['WTO_AI_BHV_REVERSE_MAX_TURN_M', 'float', c.behavior.reverseMaxTurnDistM], ['WTO_AI_BHV_REVERSE_MIN_MPS', 'float', c.behavior.reverseMinSpeedMps], ['WTO_AI_BHV_REVERSE_HOLD_SEC', 'float', c.behavior.reverseHoldSec], ['WTO_AI_FC_MAX_RANGE_M', 'float', c.fireControl.maxEngageRangeM], @@ -542,13 +561,18 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['WTO_AI_FC_ENEMY_RELOAD_SEC', 'float', c.fireControl.enemyReloadSec], ['WTO_AI_FC_FLEETING_BONUS', 'float', c.fireControl.fleetingThresholdBonus], ['WTO_AI_FC_FLEETING_LAT_MPS', 'float', c.fireControl.fleetingLateralMps], - ['WTO_AI_FC_BIG_GUN_PENALTY', 'float', c.fireControl.bigGunThresholdPenalty], + ['WTO_AI_FC_FLEETING_LOOKAHEAD_SEC', 'float', c.fireControl.fleetingLookAheadSec], + ['WTO_AI_FC_RELOAD_PENALTY', 'float', c.fireControl.reloadThresholdPenalty], + ['WTO_AI_FC_LONG_RELOAD_SEC', 'float', c.fireControl.longReloadSec], + ['WTO_AI_FC_LOW_AMMO_ROUNDS', 'int', c.fireControl.lowAmmoRounds], + ['WTO_AI_FC_LOW_AMMO_PENALTY', 'float', c.fireControl.lowAmmoThresholdPenalty], + ['WTO_AI_FC_AIM_SKILL', 'float', c.fireControl.aimSkill], + ['WTO_AI_FC_AC_MIN_RATE_HZ', 'float', c.fireControl.autocannonMinShotsPerSec], ['WTO_AI_FC_RETREAT_PENALTY', 'float', c.fireControl.retreatThresholdPenalty], ['WTO_AI_FC_MIN_SHOT_INTERVAL_SEC', 'float', c.fireControl.minShotIntervalSec], ['WTO_AI_FC_AC_AIM_SLACK', 'float', c.fireControl.autocannonAimSlack], ['WTO_AI_FC_BURST_SEC', 'float', c.fireControl.burstSec], ['WTO_AI_FC_BURST_PAUSE_SEC', 'float', c.fireControl.burstPauseSec], - ['WTO_AI_FC_BURST_RECHECK_SEC', 'float', c.fireControl.burstRecheckSec], ['WTO_AI_FC_AC_RELOAD_DETECT_SEC', 'float', c.fireControl.autocannonReloadDetectSec], ['WTO_AI_FC_AUX_ENABLED', 'bool', c.fireControl.auxWeapons], ['WTO_AI_FC_AUX_MAX_RANGE_M', 'float', c.fireControl.auxMaxRangeM], From 038d897b1efc429fa8633cf25d35f772062f31bf Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sun, 6 Dec 2026 01:53:54 +0800 Subject: [PATCH 15/19] fix(launcher): translate ground AI tuning labels --- .../src/renderer/src/i18n/locales/zh-CN.json | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index 77958af..b8b88fd 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -686,15 +686,15 @@ }, "behavior": { "scoreIntervalSec": "行为打分间隔", - "advanceHoldSec": "??????", - "engageHoldSec": "????????", - "haltHoldSec": "????????", - "coverHoldSec": "????????", - "repositionHoldSec": "??????", - "postHoldSec": "??????", - "disperseHoldSec": "??????", - "targetValueWeight": "???????????", - "nearThreatHaltBonus": "??????????", + "advanceHoldSec": "推进承诺时间", + "engageHoldSec": "交战推进承诺时间", + "haltHoldSec": "短停射击承诺时间", + "coverHoldSec": "退入掩体承诺时间", + "repositionHoldSec": "换位承诺时间", + "postHoldSec": "守位承诺时间", + "disperseHoldSec": "疏散承诺时间", + "targetValueWeight": "运动中有机会命中的权重", + "nearThreatHaltBonus": "近距威胁下的短停加分", "switchMargin": "切换行为所需高出的分数", "advanceScore": "得分:沿任务路线推进", "engageScore": "得分:交战推进", @@ -713,7 +713,7 @@ "faceToleranceDeg": "停车时朝向容差", "faceMinDanger": "需要车头对准的威胁危险度下限", "reverseTravelAngleDeg": "威胁偏离行进方向多少度时倒车跟路", - "reverseMaxTurnDistM": "????????????????????", + "reverseMaxTurnDistM": "倒车时距下一拐点或路线终点的最远距离", "reverseMinSpeedMps": "倒车跟路所需的最低倒车极速", "reverseHoldSec": "前进与倒车切换的最短间隔" }, @@ -741,13 +741,13 @@ "enemyReloadSec": "目标开火后视为装填中的时长", "fleetingThresholdBonus": "目标即将离开视线时门槛降低", "fleetingLateralMps": "视为即将离开视线的横穿速度", - "fleetingLookAheadSec": "?????????", - "reloadThresholdPenalty": "????????????", - "longReloadSec": "????????????", - "lowAmmoRounds": "???????????", - "lowAmmoThresholdPenalty": "????????????", - "aimSkill": "???????????", - "autocannonMinShotsPerSec": "???????????/??", + "fleetingLookAheadSec": "预判视线遮挡的时间", + "reloadThresholdPenalty": "装填时间长时提高开火门槛", + "longReloadSec": "开火门槛加满时的装填时间", + "lowAmmoRounds": "开始节省弹药的剩余发数", + "lowAmmoThresholdPenalty": "剩余弹药少时提高开火门槛", + "aimSkill": "影响瞄点散布的炮手技能", + "autocannonMinShotsPerSec": "识别机炮的最低射速(发/秒)", "retreatThresholdPenalty": "退入掩体途中的门槛升高", "minShotIntervalSec": "主炮最短开火间隔", "autocannonAimSlack": "机炮放宽倍数(目标尺寸的倍数)", @@ -756,7 +756,7 @@ "autocannonReloadDetectSec": "机炮持续未就绪多久算换弹", "auxWeapons": "使用副炮和并列武器", "auxMaxRangeM": "副炮和并列武器的射击距离", - "auxFireAtArmor": "副炮和并列武器也打装甲目标", + "auxFireAtArmor": "并列武器也可以向非轻型车辆开火", "friendlyCorridorM": "友军弹道禁射走廊宽度", "ballisticStepMaxM": "弹道硬遮挡检测步长", "ballisticSweepRadiusM": "弹道扫掠半径", From 0b841ce2a2f3cb190d9c2bb79e3570c13f8961b9 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sun, 6 Dec 2026 13:53:51 +0800 Subject: [PATCH 16/19] fix(ground-ai): follow up the Berlin decision layer review The first battles with the single-vehicle decision layer showed bots sensing from a stale turret direction, fixed mounts and elevation-limited guns that never got the hull turned for them, and bots braking late for vehicles and wrecks. - Perception samples the live barrel before sensing; near, mid and sight arcs are all measured from the barrel, and visible near and mid contacts in the barrel's front half are ranked with the same danger model. - The turret may swing to a contact before it is confirmed; the trigger still waits for visual confirmation. - A short halt only brakes. A fixed mount beyond its yaw span (turret.fixedMountYawSpanDeg) asks the hull to turn; an elevation-limited gun asks for a hull turn only when the stock elevation table shows the turn opens a sector that reaches the target. - Friendly and enemy vehicles and wrecks take part in front and rear dynamic braking; detours try the sides, then backing off. Builds and loads on the 2.61.0.64 lab client; played in three lab battles together with the replay trace. --- .../src/renderer/src/i18n/locales/en.json | 7 +- .../src/renderer/src/i18n/locales/zh-CN.json | 7 +- .../src/pages/tuning/bot-tuning-fields.ts | 1 + apps/launcher/src/shared/schemas/tuning.ts | 1 + apps/server/src/tuning/ground-ai-tuning.ts | 1 + apps/server/tuning/ground-ai.jsonc | 20 +- game-ai/ground/wto_ai_behavior_common.das | 3 +- game-ai/ground/wto_ai_combat_types_common.das | 12 +- game-ai/ground/wto_ai_drive_common.das | 17 +- game-ai/ground/wto_ai_facing_common.das | 6 +- game-ai/ground/wto_ai_fire_common.das | 54 ++++-- game-ai/ground/wto_ai_fire_gate_common.das | 2 +- game-ai/ground/wto_ai_hull_aim_common.das | 107 +++++++++++ game-ai/ground/wto_ai_nav_common.das | 27 ++- game-ai/ground/wto_ai_nav_types_common.das | 6 + game-ai/ground/wto_ai_perceive_common.das | 174 ++++++++---------- game-ai/ground/wto_ai_runtime.das | 3 +- game-ai/ground/wto_ai_stats_common.das | 5 +- game-ai/ground/wto_ai_tactics_common.das | 9 +- game-ai/ground/wto_ai_threat_common.das | 43 ++--- game-ai/ground/wto_ai_traffic_common.das | 110 +++++------ .../ground/wto_ai_traffic_geometry_common.das | 97 ++++++++++ game-ai/ground/wto_ai_traverse_common.das | 41 ++--- game-ai/ground/wto_ai_turret_common.das | 40 ++-- game-ai/ground/wto_ai_types_common.das | 1 - game-ai/ground/wto_ai_unstick_common.das | 4 +- game-ai/ground/wto_ai_world_common.das | 2 +- .../patcher/src/ground-ai/ground-ai-config.ts | 2 + 28 files changed, 518 insertions(+), 284 deletions(-) create mode 100644 game-ai/ground/wto_ai_hull_aim_common.das create mode 100644 game-ai/ground/wto_ai_traffic_geometry_common.das diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index a763e0a..be4ecb9 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -642,8 +642,8 @@ "decayPerSec": "Exposure decay rate per second", "gunFovHalfDeg": "Gun sight half-angle", "nearAwareM": "Close all-round awareness range", - "nearArcDeg": "Close awareness arc around the hull", - "midAwareM": "Commander awareness range (hull front half)", + "nearArcDeg": "Close awareness arc around the barrel", + "midAwareM": "Medium awareness range (barrel front hemisphere)", "nearSpotMul": "Close awareness spotting time multiplier", "midSpotMul": "Commander awareness spotting time multiplier", "lookAroundSec": "Look-around interval", @@ -682,7 +682,8 @@ "minDwellSec": "Minimum time on a chosen look direction", "switchMargin": "Extra danger needed to turn from the engaged target", "scanArcDeg": "Scan arc either side of the route", - "scanPeriodSec": "Scan sweep period" + "scanPeriodSec": "Scan sweep period", + "fixedMountYawSpanDeg": "Max yaw range for hull-mounted guns" }, "behavior": { "scoreIntervalSec": "Behavior scoring interval", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index b8b88fd..612b6cb 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -642,8 +642,8 @@ "decayPerSec": "失联曝光每秒衰减率", "gunFovHalfDeg": "瞄准镜视野半角", "nearAwareM": "近距环视感知距离", - "nearArcDeg": "近距感知覆盖车体周围的角度", - "midAwareM": "车长感知距离(车体前半球)", + "nearArcDeg": "以炮口为基准的近距感知角度", + "midAwareM": "中距感知距离(炮口前半球)", "nearSpotMul": "近距感知看清耗时倍数", "midSpotMul": "车长感知看清耗时倍数", "lookAroundSec": "环视间隔", @@ -682,7 +682,8 @@ "minDwellSec": "选定的观察方向至少保持的时间", "switchMargin": "从交战目标转向其他威胁所需高出的危险度", "scanArcDeg": "沿路线向两侧扫视的角度", - "scanPeriodSec": "扫视一个来回的时长" + "scanPeriodSec": "扫视一个来回的时长", + "fixedMountYawSpanDeg": "判定为固定炮座时的最大水平射界" }, "behavior": { "scoreIntervalSec": "行为打分间隔", diff --git a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts index a2a531a..5ed854e 100644 --- a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts +++ b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts @@ -247,6 +247,7 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ num('turret', 'switchMargin', 0, 3), num('turret', 'scanArcDeg', 0, 180, '°'), num('turret', 'scanPeriodSec', 1, 30, 's'), + num('turret', 'fixedMountYawSpanDeg', 0, 180, '°'), ], }, { diff --git a/apps/launcher/src/shared/schemas/tuning.ts b/apps/launcher/src/shared/schemas/tuning.ts index 1076abc..402b07f 100644 --- a/apps/launcher/src/shared/schemas/tuning.ts +++ b/apps/launcher/src/shared/schemas/tuning.ts @@ -227,6 +227,7 @@ const GroundAiTurretSchema = z.object({ switchMargin: z.number().min(0).max(3), scanArcDeg: z.number().min(0).max(180), scanPeriodSec: z.number().min(1).max(30), + fixedMountYawSpanDeg: z.number().min(0).max(180), }); const GroundAiBehaviorSchema = z.object({ diff --git a/apps/server/src/tuning/ground-ai-tuning.ts b/apps/server/src/tuning/ground-ai-tuning.ts index 399ab50..2da0bca 100644 --- a/apps/server/src/tuning/ground-ai-tuning.ts +++ b/apps/server/src/tuning/ground-ai-tuning.ts @@ -371,6 +371,7 @@ function readTurretSection(turret: TuningReader): GroundAiTuning['turret'] { switchMargin: turret.number('switchMargin', { min: 0, max: 3 }), scanArcDeg: turret.number('scanArcDeg', { min: 0, max: 180 }), scanPeriodSec: turret.number('scanPeriodSec', { min: 1, max: 30 }), + fixedMountYawSpanDeg: turret.number('fixedMountYawSpanDeg', { min: 0, max: 180 }), }; } diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index 1e8f6b4..c7f96cf 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -265,12 +265,10 @@ "normalSpotSec": 0.60, "farSpotSec": 1.45, "decayPerSec": 1.5, - // Layered awareness (decision layer design, section 3): the gun sight sees gunFovHalfDeg either - // side of the barrel; within nearAwareM the crew notices enemies all round the hull except a - // rear blind arc (nearArcDeg wide is covered), and every lookAroundSec for lookAroundHoldSec - // the rear too; within midAwareM the commander covers the hull's front half. Near and mid - // spotting take nearSpotMul / midSpotMul times as long as through the gun sight. An enemy whose - // exposure reaches discoverScore counts as discovered (position known, not yet fireable). + // Every visual arc is relative to the barrel. The sight covers gunFovHalfDeg either side; + // near awareness covers nearArcDeg around the barrel and every lookAroundSec opens the rear + // for lookAroundHoldSec. Mid-distance awareness covers the barrel's front half. + // Near and mid spotting use nearSpotMul and midSpotMul respectively. "gunFovHalfDeg": 30.0, "nearAwareM": 150.0, "nearArcDeg": 270.0, @@ -335,15 +333,15 @@ "hitMul": 2.0 }, - // Turret channel (decision layer design, section 5): with no target in sight the turret looks at - // the most dangerous discovered threat, then at cues, then sweeps scanArcDeg either side of the - // route over scanPeriodSec. It turns from the engaged target to another threat only when that - // one is switchMargin more dangerous, and keeps a chosen look for at least minDwellSec. + // The turret gives visible contacts attention by danger, then checks memory and directional cues. + // While engaged, the competing threat needs switchMargin more danger to take over. + // The turret sweeps the route when it has no contact or cue. "turret": { "minDwellSec": 0.6, "switchMargin": 0.25, "scanArcDeg": 60.0, - "scanPeriodSec": 6.0 + "scanPeriodSec": 6.0, + "fixedMountYawSpanDeg": 60.0 }, // Hull channel: choose a behavior by score, holding each for its configured commitment time diff --git a/game-ai/ground/wto_ai_behavior_common.das b/game-ai/ground/wto_ai_behavior_common.das index 86bd3e2..06ffbb4 100644 --- a/game-ai/ground/wto_ai_behavior_common.das +++ b/game-ai/ground/wto_ai_behavior_common.das @@ -135,7 +135,8 @@ def private wto_bhv_scores(now : float; c : WtoBhvCtx const&; slot : WtoBotSlot let haltRequest = c.haltWanted || c.turnWanted || halting if haltRequest && c.stopRangeOk && !c.atGoal && now >= slot.tactics.shortHaltCooldownUntil let crossfire = float(max(0, c.aimingCount - 1)) - let nearBonus = c.nearThreat ? WTO_AI_BHV_NEAR_HALT_BONUS : 0.0 + let near = c.nearThreat || c.distTarget <= WTO_AI_PERC_NEAR_AWARE_M + let nearBonus = near ? WTO_AI_BHV_NEAR_HALT_BONUS : 0.0 s[WTO_BHV_HALT] = WTO_AI_BHV_HALT + WTO_AI_BHV_URGENCY_W * (1.0 - urgentF) + nearBonus - WTO_AI_BHV_CROSSFIRE * crossfire let coverRetry = now - slot.tactics.coverFailedAt >= WTO_AI_BHV_COVER_RETRY_SEC if slot.fire.reloading && (c.hasTarget || c.remembered) && !slot.spec.isAutocannon && coverRetry diff --git a/game-ai/ground/wto_ai_combat_types_common.das b/game-ai/ground/wto_ai_combat_types_common.das index d173e47..f2cbd77 100644 --- a/game-ai/ground/wto_ai_combat_types_common.das +++ b/game-ai/ground/wto_ai_combat_types_common.das @@ -81,6 +81,7 @@ struct public WtoPerceiveState lastRadioSentAt : float = -100.0 expEids : EntityId[8] expScore : float[8] + expDanger : float[8] expGoodLosSec : float[8] expSeenAt : float[8] expPos : float3[8] @@ -103,14 +104,13 @@ struct public WtoThreatEntry seesMe : bool = false danger : float = 0.0 -// Rebuilt every perception tick; topIdx is the most dangerous entry, topUnseenIdx the most -// dangerous one not seen clearly yet (both -1 when there is none). +// Rebuilt every perception tick, with the highest danger overall and among visible contacts. [safe_when_uninitialized] struct public WtoThreatTable count : int = 0 entries : WtoThreatEntry[8] topIdx : int = -1 - topUnseenIdx : int = -1 + topVisibleIdx : int = -1 // Turret channel (decision layer design, section 5): the threat it is looking at and until when // that look is held. @@ -165,6 +165,8 @@ struct public WtoFireState traverseTurretNo : int = -1 traverse : WtoGunTraverse = WtoGunTraverse() hullAimTarget : EntityId = INVALID_ENTITY_ID + hullAimForPitch : bool = false + mountCanAim : bool = true hullAimDir : float3 = float3(0.0, 0.0, 0.0) gunReady : bool = false reloading : bool = false @@ -181,11 +183,15 @@ struct public WtoFireState activeMassKg : float = 10.0 activeCaliberM : float = 0.09 pitchBlocked : bool = false + pitchAtLimit : bool = false pitchClampSec : float = 0.0 curYawDeg : float = 0.0 curPitchDeg : float = 0.0 prevPitchDeg : float = 0.0 servoInit : bool = false + sightPrimaryIndex : int = -1 + hasBarrelSight : bool = false + barrelSight : float3 = float3(1.0, 0.0, 0.0) aimTargetEid : EntityId = INVALID_ENTITY_ID prevAimOffset : float3 = float3(0.0, 0.0, 0.0) prevAimAt : float = -100.0 diff --git a/game-ai/ground/wto_ai_drive_common.das b/game-ai/ground/wto_ai_drive_common.das index d3b7864..503229f 100644 --- a/game-ai/ground/wto_ai_drive_common.das +++ b/game-ai/ground/wto_ai_drive_common.das @@ -18,6 +18,7 @@ require vehicle require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_nav_types_common [never_inline] def public wto_drive_announce_script_ready() @@ -151,9 +152,9 @@ def private wto_compute_cruise_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleS outThr = clamp(response, 0.0, 1.0) outBrk = clamp(-response, 0.0, 1.0) return - if vErr < -1.5 + if vErr < 0.0 outThr = 0.0 - outBrk = clamp((-vErr - 1.2) * 0.35, 0.2, 1.0) + outBrk = clamp(-vErr / WTO_AI_NAV_MOVING_FIRE_SPEED_RAMP_MPS, 0.0, 1.0) elif vErr >= 0.6 outThr = 1.0 else @@ -193,6 +194,17 @@ def private wto_ensure_phys_owner(gm : IGroundModel const?; var actor : VehicleP st.routeBOwned = true return st.routeBOwned +// Keep the physical brake active even while a pivot or unstick has requested throttle. +def private wto_drive_traffic_brake(vFwd : float; nav : WtoNavState const&; var thr, brk : float&) + if (thr > 0.0 && nav.frontTrafficSpeedCap <= 0.05) || (thr < 0.0 && nav.rearTrafficSpeedCap <= 0.05) + thr = 0.0 + brk = 1.0 + let excess = max(vFwd - nav.frontTrafficSpeedCap, -vFwd - nav.rearTrafficSpeedCap) + if excess > 0.0 + if thr * vFwd > 0.0 + thr = 0.0 + brk = max(brk, clamp(excess / WTO_AI_NAV_MOVING_FIRE_SPEED_RAMP_MPS, 0.0, 1.0)) + [never_inline] def private wto_apply_drive_cmd(var actor : VehiclePhysActor&; fwd, left, velocity : float3; var slot : WtoBotSlot&) @@ -215,6 +227,7 @@ def private wto_apply_drive_cmd(var actor : VehiclePhysActor&; fwd, left, veloci let firingOnMove = slot.tactics.state == WTO_STATE_RUN_AND_GUN let speed = firingOnMove ? length(velocity) : vFwd wto_compute_cruise_axes(cmd, slot.spec, fwd, left, speed, st.omegaYawRad, firingOnMove, thr, str, brk) + wto_drive_traffic_brake(vFwd, slot.nav, thr, brk) st.prevThr = thr st.prevStr = str wto_set_phys_axes(actor, thr, str, brk, hand) diff --git a/game-ai/ground/wto_ai_facing_common.das b/game-ai/ground/wto_ai_facing_common.das index 73c5c25..6df8aec 100644 --- a/game-ai/ground/wto_ai_facing_common.das +++ b/game-ai/ground/wto_ai_facing_common.das @@ -52,8 +52,6 @@ def public wto_face_update(now : float; myPos, hullFwd : float3; var slot : WtoB tac.faceActive = false tac.faceFromThreat = false tac.faceForGun = false - if !slot.perceive.hasClearLos || tac.gunFacingTarget != slot.perceive.targetEid - tac.gunFacingTarget = INVALID_ENTITY_ID var threatPos = myPos if !wto_face_bound(slot.spec) || !wto_face_threat_pos(now, slot, threatPos) return @@ -66,14 +64,12 @@ def public wto_face_update(now : float; myPos, hullFwd : float3; var slot : WtoB [never_inline] def public wto_face_accept_gun(hullFwd : float3; var slot : WtoBotSlot&) assume tac = slot.tactics - if !wto_face_has_request(slot) && !tac.gunFacingTarget + if !wto_face_has_request(slot) return let wanted = wto_xz_normalize(slot.fire.hullAimDir, hullFwd) let allowedAngle = min(90.0, WTO_AI_BHV_HULL_ANGLE_DEG + WTO_AI_BHV_FACE_TOL_DEG) if tac.faceFromThreat && dot(wanted, tac.faceThreatDir) < cos(allowedAngle * WTO_DEG_TO_RAD) - tac.gunFacingTarget = INVALID_ENTITY_ID return - tac.gunFacingTarget = slot.perceive.targetEid tac.faceDir = wanted tac.faceActive = true tac.faceForGun = true diff --git a/game-ai/ground/wto_ai_fire_common.das b/game-ai/ground/wto_ai_fire_common.das index 97dd288..4bcf52b 100644 --- a/game-ai/ground/wto_ai_fire_common.das +++ b/game-ai/ground/wto_ai_fire_common.das @@ -23,6 +23,7 @@ require %appGame.wtoai.wto_ai_world_common require %appGame.wtoai.wto_ai_estimate_common require %appGame.wtoai.wto_ai_fire_gate_common require %appGame.wtoai.wto_ai_traverse_common +require %appGame.wtoai.wto_ai_hull_aim_common require %appGame.wtoai.wto_ai_turret_common require %appGame.wtoai.wto_ai_trigger_common require %appGame.wtoai.wto_ai_fire_aux_common @@ -174,23 +175,45 @@ def private wto_finish_weapon_state(now : float; spec : WtoVehicleSpec const&; a [never_inline] def private wto_sample_muzzle(unit : Unit const?; primaryIndex : int; var outPos, outDir : float3&) : bool - if unit == null || unit.weap == null || primaryIndex < 0 + if unit == null || unit.weap == null return false var sampled = false get_weapons_by_trigger_group(unit.weap.Weapons, WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY) <| $(weapons : array const#) if primaryIndex >= length(weapons) return - assume weapon = weapons[primaryIndex] - if weapon == null - return - var gunTm : float3x4 - weapon_calcShootTm(weapon, unit.unitTm, gunTm) - if length_sq(gunTm[0]) > 0.25 - outPos = gunTm[3] - outDir = normalize(gunTm[0]) - sampled = true + let first = max(0, primaryIndex) + let end = primaryIndex < 0 ? length(weapons) : min(primaryIndex + 1, length(weapons)) + for i in range(first, end) + assume weapon = weapons[i] + if weapon == null || weapon.isDummyGun + continue + var gunTm : float3x4 + weapon_calcShootTm(weapon, unit.unitTm, gunTm) + if wto_is_finite3(gunTm[0]) && length_sq(gunTm[0]) > 0.25 + outPos = gunTm[3] + outDir = normalize(gunTm[0]) + sampled = true + return return sampled +// Sense from the live barrel even when the stock controller is moving the turret. +def public wto_fire_sample_sight(unit : Unit const?; var state : WtoFireState&) + var muzzlePos = float3(0.0, 0.0, 0.0) + var barrelDir = muzzlePos + let primary = state.sightPrimaryIndex + state.hasBarrelSight = wto_sample_muzzle(unit, primary, muzzlePos, barrelDir) + if !state.hasBarrelSight && primary >= 0 + state.hasBarrelSight = wto_sample_muzzle(unit, -1, muzzlePos, barrelDir) + if state.hasBarrelSight + state.barrelSight = barrelDir + +def private wto_fire_sample_primary(unit : Unit const?; var state : WtoFireState&; var muzzlePos, barrelDir : float3&) : bool + if state.sightPrimaryIndex < 0 || !wto_sample_muzzle(unit, state.sightPrimaryIndex, muzzlePos, barrelDir) + return false + state.hasBarrelSight = true + state.barrelSight = barrelDir + return true + def private wto_clear_aim_tracking(var fc : WtoFireState&) fc.aimTargetEid = INVALID_ENTITY_ID fc.aimDriftDegSec = 0.0 @@ -201,7 +224,7 @@ def private wto_clear_aim_tracking(var fc : WtoFireState&) // SPAA vs aircraft only delegates to stock air-target fire control (never ground targets). [never_inline] def private wto_yield_air_fire(var unit : Unit?; var slot : WtoBotSlot&) - wto_set_hull_aim(unit, false, 0.0, unit.unitTm[0], slot) + wto_set_hull_aim(unit, "", false, 0.0, 0.0, unit.unitTm[0], slot) wto_clear_aim_tracking(slot.fire) wto_trig_set_target(INVALID_ENTITY_ID, slot.trigger) var gm = as_gm(unit) @@ -232,10 +255,10 @@ def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; classN return set_unit_attack_type(unit, "dont_aim") let wantSoft = wto_fire_wants_soft(world, slot) - let primaryIndex = wto_inspect_primary_weapon(unit, now, slot.spec, wantSoft, slot.fire) + slot.fire.sightPrimaryIndex = wto_inspect_primary_weapon(unit, now, slot.spec, wantSoft, slot.fire) var muzzlePos = unit.pos + float3(0.0, 1.95, 0.0) var liveBarrelDir = unit.unitTm[0] - let _preSample = wto_sample_muzzle(unit, primaryIndex, muzzlePos, liveBarrelDir) + var muzzleReady = wto_fire_sample_primary(unit, slot.fire, muzzlePos, liveBarrelDir) let hFwd = unit.unitTm[0] var wishWorldDir = hFwd var aimPt = muzzlePos @@ -257,8 +280,9 @@ def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; classN wto_drive_mounted_gun(unit, className, dt, wishYaw, wishPitch, slot) if slot.fire.traverse.known || auxAimed wto_apply_weapon_aim(unit, dt) - let canEngage = engage && distToTgt <= WTO_AI_FC_MAX_RANGE_M && wto_sample_muzzle(unit, primaryIndex, muzzlePos, liveBarrelDir) - wto_set_hull_aim(unit, canEngage, wishYaw, liveBarrelDir, slot) + muzzleReady = wto_fire_sample_primary(unit, slot.fire, muzzlePos, liveBarrelDir) + let canEngage = engage && distToTgt <= WTO_AI_FC_MAX_RANGE_M && muzzleReady + wto_set_hull_aim(unit, className, canEngage, wishYaw, wishPitch, liveBarrelDir, slot) if canEngage wto_fire_gate_try_shoot(world, unit, className, now, distXZ, muzzlePos, aimPt, liveBarrelDir, wishWorldDir, slot, fireBudget) else diff --git a/game-ai/ground/wto_ai_fire_gate_common.das b/game-ai/ground/wto_ai_fire_gate_common.das index 01370be..169f526 100644 --- a/game-ai/ground/wto_ai_fire_gate_common.das +++ b/game-ai/ground/wto_ai_fire_gate_common.das @@ -181,7 +181,7 @@ def public wto_fire_gate_try_shoot(world : WtoWorldSnap const&; var unit : Unit? let turnDegSec = abs(slot.drive.omegaYawRad) * WTO_RAD_TO_DEG let offset = wto_trig_aim_error(liveDir, wishDir) let probOk = wto_trig_evaluate(world, now, unit.pos, length(unit.vel), turnDegSec, distXZ, offset, slot) - let withinTraverse = fc.hullAimTarget == INVALID_ENTITY_ID + let withinTraverse = fc.mountCanAim && fc.hullAimTarget == INVALID_ENTITY_ID if slot.spec.isAutocannon wto_gate_try_burst(world, unit, className, now, distXZ, muzzlePos, aimPt, liveDir, aimErrDeg, withinTraverse, slot, fireBudget) else diff --git a/game-ai/ground/wto_ai_hull_aim_common.das b/game-ai/ground/wto_ai_hull_aim_common.das new file mode 100644 index 0000000..2f950f7 --- /dev/null +++ b/game-ai/ground/wto_ai_hull_aim_common.das @@ -0,0 +1,107 @@ +// The chassis helps a fixed mount that runs out of yaw, or opens an elevation sector for a turret. +options indenting = 2 +options no_global_heap = true +module wto_ai_hull_aim_common shared + +require ecs +require math +require DagorMath +require DagorDataBlock +require Unit +require Weapon +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_traverse_common + +def private wto_pitch_reaches(pitch : float2; wanted : float) : bool + return wto_valid_angle_range(pitch) && wanted >= pitch.x && wanted <= pitch.y + +// Keep some space from a boundary shared by two pitch sectors. +def private wto_pitch_sector_yaw(preferred : float; arc : float2) : float + let margin = min(WTO_AI_FC_BASE_ALIGN_DEG, (arc.y - arc.x) * 0.5) + return clamp(wto_yaw_in_mount_coordinates(preferred, arc), arc.x + margin, arc.y - margin) + +[never_inline] +def private wto_find_pitch_yaw(className : string; triggerNo, weaponIndex : int; + preferred, wantedPitch : float; var traverse : WtoGunTraverse&; + var outYaw : float&) : bool + let arc = traverse.yaw + let preferredYaw = wto_pitch_sector_yaw(preferred, arc) + let preferredPitch = wto_gun_pitch_at_yaw(className, triggerNo, weaponIndex, preferredYaw, traverse) + if wto_pitch_reaches(preferredPitch, wantedPitch) + outYaw = preferredYaw + return true + var best = 360.0 + wto_read_gunner_mount(className, triggerNo, weaponIndex) <| $(mount) + let pitchTable = mount |> datablock_get_block_by_name("limitsTable") + if pitchTable == null + return + for i in 0u..pitchTable.paramCount + if (*pitchTable |> datablock_getParamType(i)) != int(DataBlockParamType.TYPE_POINT4) + continue + let sector = *pitchTable |> datablock_getPoint4(int(i)) + if !wto_pitch_reaches(float2(sector.z, sector.w), wantedPitch) + continue + let yaw = float2(max(arc.x, sector.x), min(arc.y, sector.y)) + if !wto_valid_angle_range(yaw) + continue + let candidate = wto_pitch_sector_yaw(preferred, yaw) + let cost = abs(wto_wrap_deg(candidate - preferred)) + if cost < best + best = cost + outYaw = candidate + return best < 360.0 + +// Prefer a solution that preserves frontal armor if the hull channel has a threat facing. +[never_inline] +def private wto_pitch_turn(unit : Unit const?; className : string; wantedYaw, wantedPitch : float; + var slot : WtoBotSlot&; var outYaw : float&) : bool + assume fc = slot.fire + if !fc.traverse.hasPitchTable || fc.turretNo < 0 || fc.turretNo >= length(unit.weap.turret) + return false + var preferred = wantedYaw + if slot.tactics.faceFromThreat + var armorYaw = 0.0 + var armorPitch = 0.0 + wto_world_to_hull_deg(slot.tactics.faceDir, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2], armorYaw, armorPitch) + preferred = wto_wrap_deg(wantedYaw - armorYaw) + assume turret = unit.weap.turret[fc.turretNo] + return wto_find_pitch_yaw(className, int(turret.triggerNo), int(turret.weaponIndex), preferred, wantedPitch, fc.traverse, outYaw) + +[never_inline] +def public wto_set_hull_aim(unit : Unit const?; className : string; active : bool; + wishYaw, wishPitch : float; liveBarrelDir : float3; var slot : WtoBotSlot&) + assume fc = slot.fire + var target = INVALID_ENTITY_ID + var pitchTurn = false + fc.mountCanAim = true + if active + var arc = fc.traverse.yaw + let hasLimits = fc.traverse.known + let hullMounted = !fc.servoInit || (hasLimits && arc.y - arc.x <= WTO_AI_TURRET_FIXED_MOUNT_SPAN_DEG) + if !fc.servoInit + var fixedYaw = 0.0 + var barrelPitch = 0.0 + wto_world_to_hull_deg(liveBarrelDir, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2], fixedYaw, barrelPitch) + arc = float2(fixedYaw, fixedYaw) + let yaw = wto_yaw_in_mount_coordinates(wishYaw, arc) + let tolerance = arc.x == arc.y ? WTO_AI_FC_BASE_ALIGN_DEG : 0.0 + let limited = hasLimits || !fc.servoInit + let yawBlocked = limited && !wto_full_gun_traverse(arc) && (yaw < arc.x - tolerance || yaw > arc.y + tolerance) + fc.mountCanAim = !yawBlocked && !fc.pitchAtLimit + var mountYaw = 0.5 * (arc.x + arc.y) + let fixedTurn = hullMounted && yawBlocked + if !yawBlocked && fc.pitchAtLimit + pitchTurn = wto_pitch_turn(unit, className, wishYaw, wishPitch, slot, mountYaw) + if fixedTurn || pitchTurn + target = slot.perceive.targetEid + let turn = wto_wrap_deg(wishYaw - mountYaw) + fc.hullAimDir = wto_hull_deg_to_world(turn, 0.0, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2]) + if target != fc.hullAimTarget || pitchTurn != fc.hullAimForPitch + slot.nextNavAt = 0.0 + if WTO_AI_DIAG_TELEMETRY && !!target + print("WTO_AI|HULL_AIM|eid={uint(slot.eid)}|target={uint(target)}|pitch={pitchTurn}\n") + fc.hullAimTarget = target + fc.hullAimForPitch = pitchTurn diff --git a/game-ai/ground/wto_ai_nav_common.das b/game-ai/ground/wto_ai_nav_common.das index 9e66e84..82b4e99 100644 --- a/game-ai/ground/wto_ai_nav_common.das +++ b/game-ai/ground/wto_ai_nav_common.das @@ -24,6 +24,7 @@ require %appGame.wtoai.wto_ai_follow_common require %appGame.wtoai.wto_ai_facing_common require %appGame.wtoai.wto_ai_avoid_common require %appGame.wtoai.wto_ai_traffic_common +require %appGame.wtoai.wto_ai_traffic_geometry_common require %appGame.wtoai.wto_ai_unstick_common [never_inline] @@ -38,6 +39,9 @@ def private wto_nav_halt(myPos, hullFwd : float3; var slot : WtoBotSlot&) [never_inline] def private wto_nav_stand(myPos, hullFwd : float3; var slot : WtoBotSlot&) assume tac = slot.tactics + if tac.state == WTO_STATE_SHORT_HALT && !tac.faceForGun + wto_nav_halt(myPos, hullFwd, slot) + return let limit = tac.faceForGun ? WTO_AI_FC_BASE_ALIGN_DEG : WTO_AI_BHV_FACE_TOL_DEG let errorDeg = acos(clamp(dot(tac.faceDir, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG if tac.faceActive && errorDeg > limit && wto_pivot_drive_mode(slot.spec, slot.nav.frontClearM, slot.nav.rearClearM, true) != WTO_DRIVE_HALT @@ -63,7 +67,8 @@ def private wto_nav_tactical_reverse(navState : int; myPos, hullFwd : float3; va let dir = wto_xz_normalize(goal - myPos, -hullFwd) slot.nav.steerDir = dir slot.nav.stuckCheckAt = -100.0 - wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_REVERSE, goal, dir, max(2.0, slot.spec.vMaxRev), slot.nav.frontClearM, slot.nav.rearClearM) + let speed = min(slot.spec.vMaxRev, slot.nav.rearTrafficSpeedCap) + wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_REVERSE, goal, dir, speed, slot.nav.frontClearM, slot.nav.rearClearM) return true // Surface, flags and room to the mesh edge under the bot (battles with a pack only). @@ -160,6 +165,8 @@ def private wto_nav_follow(var world : WtoWorldSnap&; navState : int; now : floa let target = slot.nav.avoidActive ? slot.nav.avoidTarget : pathTarget let dir = wto_xz_normalize(target - myPos, lead) var speed = wto_nav_speed(navState, now, myPos, dir, lookM, narrow, slot) + let trafficLimit = reverse ? slot.nav.rearTrafficSpeedCap : slot.nav.frontTrafficSpeedCap + speed = min(speed, trafficLimit) if reverse speed = min(speed, slot.spec.vMaxRev) slot.nav.steerDir = dir @@ -169,6 +176,20 @@ def private wto_nav_follow(var world : WtoWorldSnap&; navState : int; now : floa let movingIntent = slot.tactics.desiredSpeedMps > 1.2 && now >= slot.nav.yieldUntil wto_unstick_watch(world, navState, now, myPos, hullFwd, myPos + dir * 6.0, movingIntent, slot) +// Check both ends in the actual chassis frame. This also applies during pivots, short halts, +// tactical withdrawal and unstick, when the usual route traffic solver may not run. +[never_inline] +def private wto_nav_clearance(world : WtoWorldSnap const&; myPos, hullFwd : float3; var slot : WtoBotSlot&) + let probeBase = myPos + float3(0.0, 1.25, 0.0) + var traffic = WtoTrafficClearance() + wto_traffic_clearance(world, myPos, hullFwd, slot, traffic) + assume nav = slot.nav + nav.frontClearM = min(wto_terrain_hard_ray(probeBase, hullFwd, 24.0), traffic.frontM) + nav.rearClearM = min(wto_terrain_hard_ray(probeBase, -hullFwd, 18.0), traffic.rearM) + let speed = slot.drive.lastVFwd + nav.frontTrafficSpeedCap = wto_traffic_brake_speed(traffic.frontM, traffic.frontSpeed, max(0.0, speed), slot.spec.halfLen) + nav.rearTrafficSpeedCap = wto_traffic_brake_speed(traffic.rearM, traffic.rearSpeed, max(0.0, -speed), slot.spec.halfLen) + [never_inline] def public wto_nav_update(var world : WtoWorldSnap&; navState, slotIdx : int; now : float; myPos, rawHullFwd : float3; var slot : WtoBotSlot&) @@ -176,9 +197,7 @@ def public wto_nav_update(var world : WtoWorldSnap&; navState, slotIdx : int; no slot.driveCmd.valid = false return let hullFwd = wto_xz_normalize(rawHullFwd, float3(1.0, 0.0, 0.0)) - let probeBase = myPos + float3(0.0, 1.25, 0.0) - slot.nav.frontClearM = wto_terrain_hard_ray(probeBase, hullFwd, 24.0) - slot.nav.rearClearM = wto_terrain_hard_ray(probeBase, -hullFwd, 18.0) + wto_nav_clearance(world, myPos, hullFwd, slot) let st = slot.tactics.state if st != WTO_STATE_MARCH && st != WTO_STATE_RUN_AND_GUN slot.tactics.reverseTravel = false diff --git a/game-ai/ground/wto_ai_nav_types_common.das b/game-ai/ground/wto_ai_nav_types_common.das index 3e92006..41b5db9 100644 --- a/game-ai/ground/wto_ai_nav_types_common.das +++ b/game-ai/ground/wto_ai_nav_types_common.das @@ -41,6 +41,8 @@ struct public WtoNavState steerDir : float3 = float3(1.0, 0.0, 0.0) frontClearM : float = 30.0 rearClearM : float = 16.0 + frontTrafficSpeedCap : float = 99.0 + rearTrafficSpeedCap : float = 99.0 onMesh : bool = false wallDistM : float = 99.0 surfaceArea : int = 0 @@ -51,6 +53,10 @@ struct public WtoNavState yieldCooldownUntil : float = -100.0 avoidActive : bool = false avoidTarget : float3 = float3(0.0, 0.0, 0.0) + passEntry : float3 = float3(0.0, 0.0, 0.0) + passExit : float3 = float3(0.0, 0.0, 0.0) + passAtSide : bool = false + passUntil : float = -100.0 avoidSide : float = 0.0 avoidSideUntil : float = -100.0 avoidSpeedCap : float = 99.0 diff --git a/game-ai/ground/wto_ai_perceive_common.das b/game-ai/ground/wto_ai_perceive_common.das index cf814fc..b7204ac 100644 --- a/game-ai/ground/wto_ai_perceive_common.das +++ b/game-ai/ground/wto_ai_perceive_common.das @@ -10,47 +10,50 @@ require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_combat_types_common require %appGame.wtoai.wto_ai_types_common -require %appGame.wtoai.wto_ai_terrain_common require %appGame.wtoai.wto_ai_sight_common require %appGame.wtoai.wto_ai_estimate_common require %appGame.wtoai.wto_ai_world_common +require %appGame.wtoai.wto_ai_threat_common +// The current engagement and more dangerous contacts keep their tracks when the table is full. [never_inline] -def private wto_exp_find_or_alloc(var p : WtoPerceiveState&; eid : EntityId) : int +def private wto_exp_find_or_alloc(var p : WtoPerceiveState&; eid : EntityId; now, danger : float) : int var freeIdx = -1 - var minIdx = 0 - var minScore = 2.0 + var weakest = -1 + var minScore = danger for i in range(WTO_MAX_EXPOSURE_TRACKS) if p.expEids[i] == eid return i - if !p.expEids[i] && freeIdx < 0 - freeIdx = i - if p.expScore[i] < minScore - minScore = p.expScore[i] - minIdx = i - let dst = freeIdx >= 0 ? freeIdx : minIdx - p.expEids[dst] = eid - p.expScore[dst] = 0.0 - p.expGoodLosSec[dst] = 0.0 + if !p.expEids[i] + if freeIdx < 0 + freeIdx = i + continue + if p.hasClearLos && p.expEids[i] == p.targetEid + continue + let fresh = now - p.expSeenAt[i] <= WTO_AI_TACTICS_TICK_SEC * 1.5 + let score = p.expDanger[i] * (fresh ? 1.0 : WTO_AI_THREAT_UNSEEN_MUL) + if score < minScore + minScore = score + weakest = i + let dst = freeIdx >= 0 ? freeIdx : weakest + if dst >= 0 + p.expEids[dst] = eid + p.expScore[dst] = 0.0 + p.expGoodLosSec[dst] = 0.0 return dst [never_inline] -def private wto_exp_decay_all(world : WtoWorldSnap const&; dt : float; var p : WtoPerceiveState&) +def private wto_exp_decay_unseen(world : WtoWorldSnap const&; now, dt : float; var p : WtoPerceiveState&) let decay = WTO_AI_PERC_DECAY_PER_SEC * dt for i in range(WTO_MAX_EXPOSURE_TRACKS) - if !p.expEids[i] - continue - let uIdx = wto_world_find_unit(world, p.expEids[i]) - if uIdx < 0 || !world.units[uIdx].isAlive - p.expEids[i] = INVALID_ENTITY_ID - p.expScore[i] = 0.0 - p.expGoodLosSec[i] = 0.0 + if !p.expEids[i] || p.expSeenAt[i] >= now continue + let idx = wto_world_find_unit(world, p.expEids[i]) + p.expGoodLosSec[i] = 0.0 p.expScore[i] = max(0.0, p.expScore[i] - decay) - if p.expScore[i] <= 0.001 + if idx < 0 || !world.units[idx].isAlive || p.expScore[i] <= 0.001 p.expEids[i] = INVALID_ENTITY_ID p.expScore[i] = 0.0 - p.expGoodLosSec[i] = 0.0 [never_inline] def private wto_spot_fill_time(dist : float; cosAngle : float; isShooting : bool; visCount : int) : float @@ -99,23 +102,28 @@ def private wto_update_audio_and_radio_alerts(world : WtoWorldSnap const&; now : p.alertUntil = now + 2.8 return -// Spotting-time multiplier of the perception layer that covers an enemy (decision layer design, -// section 3.1): 1 in the gun sight, nearSpotMul within close awareness around the hull (the rear -// blind arc only during a look-around), midSpotMul in the commander's front half; 0 when no layer -// covers it. -def private wto_perc_layer_mul(dist, cosGun, cosHull : float; lookAround : bool) : float - if cosGun >= cos(WTO_AI_PERC_GUN_FOV_HALF_DEG * WTO_DEG_TO_RAD) +// Horizontal bearings for ground targets use the live barrel yaw. For airborne targets or a +// vertical barrel the full 3D angle gives a bearing without inventing a horizontal forward axis. +def private wto_perc_bearing(delta, barrel : float3; isAir : bool) : float + let ground = float2(delta.x, delta.z) + let sight = float2(barrel.x, barrel.z) + if !isAir && length_sq(ground) > 1.0e-6 && length_sq(sight) > 1.0e-6 + return clamp(dot(normalize(ground), normalize(sight)), -1.0, 1.0) + return clamp(dot(normalize(delta), barrel), -1.0, 1.0) + +def private wto_perc_layer_mul(dist, cosBarrel : float; lookAround : bool) : float + if cosBarrel >= cos(WTO_AI_PERC_GUN_FOV_HALF_DEG * WTO_DEG_TO_RAD) return 1.0 - if dist <= WTO_AI_PERC_NEAR_AWARE_M && (lookAround || cosHull >= cos(0.5 * WTO_AI_PERC_NEAR_ARC_DEG * WTO_DEG_TO_RAD)) + if dist <= WTO_AI_PERC_NEAR_AWARE_M && (lookAround || cosBarrel >= cos(0.5 * WTO_AI_PERC_NEAR_ARC_DEG * WTO_DEG_TO_RAD)) return WTO_AI_PERC_NEAR_SPOT_MUL - if dist <= WTO_AI_PERC_MID_AWARE_M && cosHull >= 0.0 + if dist <= WTO_AI_PERC_MID_AWARE_M && cosBarrel >= 0.0 return WTO_AI_PERC_MID_SPOT_MUL return 0.0 // Integrates one enemy's exposure this tick; its track index, or -1 when no perception layer // covers it or it is hidden. The output is the visible sample count and its center. [never_inline] -def private wto_exp_observe(world : WtoWorldSnap const&; now, dt : float; myEye, lookDir, hullDir : float3; +def private wto_exp_observe(world : WtoWorldSnap const&; now, dt : float; myEye, barrelDir : float3; lookAround : bool; u : WtoUnitSnap const&; var slot : WtoBotSlot&; var vis : int&; var aimPt : float3&) : int assume p = slot.perceive @@ -123,47 +131,43 @@ def private wto_exp_observe(world : WtoWorldSnap const&; now, dt : float; myEye, let dist = length(delta) if dist > (u.isAir ? 2600.0 : WTO_AI_TACTICS_VISION_RANGE_M) || dist < 1.0 return -1 - let dirXZ = wto_xz_normalize(delta, lookDir) - let cosAng = dot(dirXZ, lookDir) - let layerMul = u.isAir ? 1.0 : wto_perc_layer_mul(dist, cosAng, dot(dirXZ, hullDir), lookAround) + let cosAng = wto_perc_bearing(delta, barrelDir, u.isAir) + let airFront = u.isAir && cosAng >= 0.0 + let layerMul = airFront ? 1.0 : wto_perc_layer_mul(dist, cosAng, lookAround) if layerMul <= 0.0 return -1 aimPt = u.pos + float3(0.0, 1.3, 0.0) vis = wto_sight_check_target_samples(world, slot.eid, myEye, u, dist > WTO_AI_FC_LONG_RANGE_M ? 2 : 4, aimPt) if vis <= 0 - for k in range(WTO_MAX_EXPOSURE_TRACKS) - if p.expEids[k] == u.eid - p.expGoodLosSec[k] = 0.0 return -1 - let tIdx = wto_exp_find_or_alloc(p, u.eid) + let danger = wto_threat_observed_danger(now, myEye, u, p) + let tIdx = wto_exp_find_or_alloc(p, u.eid, now, danger) + if tIdx < 0 + return -1 let fillSec = wto_spot_fill_time(dist, cosAng, u.isShooting, vis) * layerMul - p.expScore[tIdx] = clamp(p.expScore[tIdx] + WTO_AI_PERC_DECAY_PER_SEC * dt + dt / fillSec, 0.0, 1.0) + p.expScore[tIdx] = clamp(p.expScore[tIdx] + dt / fillSec, 0.0, 1.0) p.expGoodLosSec[tIdx] = vis >= 2 ? (p.expGoodLosSec[tIdx] + dt) : 0.0 + p.expDanger[tIdx] = danger p.expSeenAt[tIdx] = now p.expPos[tIdx] = u.pos return tIdx -// Target preference among clearly seen enemies: lower is better. -def private wto_exp_target_score(now, dist : float; u : WtoUnitSnap const&; isSpaa : bool; p : WtoPerceiveState const&) : float - var score = dist - (u.isAir && isSpaa ? 900.0 : 0.0) - if u.eid == p.lockedEid && now < p.lockedUntil - score -= 320.0 - elif u.eid == p.lastOffenderEid && (now - p.lastDamagedAt) <= 5.0 - score -= 90.0 - elif u.isShooting && dist < 220.0 - score -= 35.0 - if dist < 45.0 - score -= 180.0 - return score +def private wto_exp_shot_priority(u : WtoUnitSnap const&; myEye : float3; isSpaa : bool) : int + if !isSpaa + return 0 + if u.isAir + return 1 + return wto_xz_dist_sq(u.pos, myEye) <= wto_sq(WTO_AI_FC_CLOSE_RANGE_M) ? 2 : 0 [never_inline] def private wto_scan_visual_exposure(world : WtoWorldSnap const&; now, dt : float; - myEye, lookDir, hullDir : float3; lookAround : bool; var slot : WtoBotSlot&; + myEye, barrelDir : float3; lookAround : bool; var slot : WtoBotSlot&; var outBestIdx, outVisCount : int&; var outGoodLosSec : float&; var outAimPt : float3&) assume p = slot.perceive let isSpaa = slot.spec.role == WTO_ROLE_SPAA - var bestScore = 1.0e9 + var bestScore = -1.0 + var bestPriority = -1 outBestIdx = -1 outVisCount = 0 outGoodLosSec = 0.0 @@ -173,28 +177,24 @@ def private wto_scan_visual_exposure(world : WtoWorldSnap const&; now, dt : floa continue var vis = 0 var aimPt = u.pos - let tIdx = wto_exp_observe(world, now, dt, myEye, lookDir, hullDir, lookAround, u, slot, vis, aimPt) + let tIdx = wto_exp_observe(world, now, dt, myEye, barrelDir, lookAround, u, slot, vis, aimPt) if tIdx < 0 || p.expScore[tIdx] < 0.999 continue - let score = wto_exp_target_score(now, length(u.pos - myEye), u, isSpaa, p) - if score < bestScore + let priority = wto_exp_shot_priority(u, myEye, isSpaa) + let locked = u.eid == p.lockedEid && now < p.lockedUntil + let score = p.expDanger[tIdx] * (locked ? 1.0 + WTO_AI_TURRET_SWITCH_MARGIN : 1.0) + if priority > bestPriority || (priority == bestPriority && score > bestScore) + bestPriority = priority bestScore = score outBestIdx = i outVisCount = vis outGoodLosSec = p.expGoodLosSec[tIdx] outAimPt = aimPt -// The gun sight's flat direction (the hull's until the turret servo is known), and the -// look-around (pressing C): every lookAroundSec, while not engaging, the rear blind arc opens. -[never_inline] -def private wto_perc_look(now : float; hullDir : float3; var slot : WtoBotSlot&; var lookDir : float3&) : bool - assume p = slot.perceive - lookDir = hullDir - if slot.fire.servoInit - let worldYaw = atan2(hullDir.z, hullDir.x) - slot.fire.curYawDeg * WTO_DEG_TO_RAD - lookDir = float3(cos(worldYaw), 0.0, sin(worldYaw)) +// Look-around temporarily opens the close rear arc relative to the barrel. +def private wto_perc_look_around(now : float; eid : EntityId; var p : WtoPerceiveState&) : bool if p.nextLookAroundAt <= 0.0 - p.nextLookAroundAt = now + float(int(uint(slot.eid) % 8u)) + p.nextLookAroundAt = now + float(int(uint(eid) % 8u)) elif now >= p.nextLookAroundAt && !p.hasClearLos p.lookAroundUntil = now + WTO_AI_PERC_LOOK_AROUND_HOLD_SEC p.nextLookAroundAt = now + WTO_AI_PERC_LOOK_AROUND_SEC @@ -213,18 +213,17 @@ def private wto_perc_fleeting(world : WtoWorldSnap const&; myEye : float3; slot [never_inline] def public wto_perceive_update(var world : WtoWorldSnap&; now, dt : float; - myPos, hullFwd : float3; var slot : WtoBotSlot&) + myPos : float3; var slot : WtoBotSlot&) assume p = slot.perceive let myEye = myPos + float3(0.0, 2.15, 0.0) - let hullDir = wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0)) - var lookDir = hullDir - let lookAround = wto_perc_look(now, hullDir, slot, lookDir) - wto_exp_decay_all(world, dt, p) + let lookAround = wto_perc_look_around(now, slot.eid, p) var bestIdx = -1 var visCount = 0 var goodLosSec = 0.0 var aimPt = myPos - wto_scan_visual_exposure(world, now, dt, myEye, lookDir, hullDir, lookAround, slot, bestIdx, visCount, goodLosSec, aimPt) + if slot.fire.hasBarrelSight + wto_scan_visual_exposure(world, now, dt, myEye, slot.fire.barrelSight, lookAround, slot, bestIdx, visCount, goodLosSec, aimPt) + wto_exp_decay_unseen(world, now, dt, p) if bestIdx >= 0 assume tgt = world.units[bestIdx] if tgt.isShooting || p.targetEid != tgt.eid @@ -241,7 +240,7 @@ def public wto_perceive_update(var world : WtoWorldSnap&; now, dt : float; p.watchUntil = -100.0 wto_est_push_visual_sample(now, tgt.eid, tgt.pos, p) p.targetFleeting = !tgt.isAir && wto_perc_fleeting(world, myEye, slot) - if p.lockedEid != tgt.eid || now >= p.lockedUntil - 0.5 + if p.lockedEid != tgt.eid p.lockedEid = tgt.eid p.lockedUntil = now + WTO_AI_TACTICS_STICKY_SEC if !tgt.isAir && (now - p.lastRadioSentAt) >= 2.5 @@ -261,30 +260,3 @@ def public wto_perceive_update(var world : WtoWorldSnap&; now, dt : float; p.lockedEid = INVALID_ENTITY_ID p.watchUntil = -100.0 wto_update_audio_and_radio_alerts(world, now, myPos, slot) - -[never_inline] -def public wto_perceive_pick_hunt_pos(world : WtoWorldSnap const&; army : int; eid : EntityId; - myPos : float3; now : float; var outPos : float3&) : bool - var bestDistSq = wto_sq(min(WTO_AI_TACTICS_RADIO_SHARE_M, 560.0)) - var found = false - var spotPos = myPos - for r in range(WTO_MAX_RADIO) - assume sp = world.radioSpots[r] - if sp.untilAt <= now || sp.army != army - continue - let dSq = wto_xz_dist_sq(myPos, sp.pos) - if dSq < bestDistSq && dSq > 2500.0 - bestDistSq = dSq - spotPos = sp.pos - found = true - if !found - return false - let toSpot = wto_xz_normalize(spotPos - myPos, float3(1.0, 0.0, 0.0)) - let lat = float3(-toSpot.z, 0.0, toSpot.x) - let fanOffset = float(int(uint(eid) % 5u) - 2) * 28.0 - var cand = spotPos - toSpot * 65.0 + lat * fanOffset - cand = wto_clamp_battle_xz(cand, world.battleCenter, world.battleRadius, 40.0) - if !wto_terrain_point_valid(army, cand) - cand = spotPos - outPos = cand - return true diff --git a/game-ai/ground/wto_ai_runtime.das b/game-ai/ground/wto_ai_runtime.das index 657e555..a25c5f9 100644 --- a/game-ai/ground/wto_ai_runtime.das +++ b/game-ai/ground/wto_ai_runtime.das @@ -208,7 +208,8 @@ def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : if now >= slot.nextTacticsAt slot.nextTacticsAt = now + WTO_AI_TACTICS_TICK_SEC if WTO_AI_LAYER_TACTICS || WTO_AI_LAYER_FIRE_CONTROL - wto_perceive_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], slot) + wto_fire_sample_sight(unit, slot.fire) + wto_perceive_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, slot) wto_threat_update(g_world, now, unit.pos, slot) wto_tactics_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], unit.isBurn, repair_system_remaining_repair_time, slot, g_crowd) wto_fire_update(g_world, unit, unit__className, now, act.dt, slot, g_fire_budget) diff --git a/game-ai/ground/wto_ai_stats_common.das b/game-ai/ground/wto_ai_stats_common.das index b1283c0..bcbb6b7 100644 --- a/game-ai/ground/wto_ai_stats_common.das +++ b/game-ai/ground/wto_ai_stats_common.das @@ -165,9 +165,8 @@ def private wto_stats_sample(world : WtoWorldSnap const&; now : float; myPos, hu bs.samples[role]++ if !wto_stats_knows(slot, u.eid) bs.unaware[role]++ - if slot.fire.servoInit - let yaw = atan2(fwd.z, fwd.x) - slot.fire.curYawDeg * WTO_DEG_TO_RAD - let gunDir = float3(cos(yaw), 0.0, sin(yaw)) + if slot.fire.hasBarrelSight + let gunDir = wto_xz_normalize(slot.fire.barrelSight, fwd) bs.turretSamples[role]++ bs.turretErrSum[role] += acos(clamp(dot(gunDir, toEnemy), -1.0, 1.0)) * WTO_RAD_TO_DEG if role == WTO_ROLE_MEDIUM || role == WTO_ROLE_HEAVY || role == WTO_ROLE_TD diff --git a/game-ai/ground/wto_ai_tactics_common.das b/game-ai/ground/wto_ai_tactics_common.das index 4d0b2cc..679c981 100644 --- a/game-ai/ground/wto_ai_tactics_common.das +++ b/game-ai/ground/wto_ai_tactics_common.das @@ -58,7 +58,7 @@ def private wto_sm_handle_ridge(world : WtoWorldSnap const&; now : float; tac.ridgeShotsStart = slot.fire.shotCount let dwellOver = (now - tac.ridgeEnterAt) >= WTO_AI_TERRAIN_RIDGE_MAX_DWELL_SEC let shotsOver = (slot.fire.shotCount - tac.ridgeShotsStart) >= WTO_AI_TERRAIN_RIDGE_MAX_SHOTS - if dwellOver || shotsOver || slot.fire.pitchBlocked + if dwellOver || shotsOver || (slot.fire.pitchBlocked && !slot.fire.hullAimForPitch) let lat = float3(-backDir.z, 0.0, backDir.x) let side = (uint(slot.eid) & 1u) == 0u ? 1.0 : -1.0 var anc = myPos + backDir * WTO_AI_NAV_TAC_REV_DIST_M + lat * (side * 16.0) @@ -121,9 +121,10 @@ def private wto_tac_engage(now : float; c : WtoBhvCtx const&; var slot : WtoBotS var speed = march assume tr = slot.trigger let fresh = (now - tr.wantSpeedAt) <= WTO_AI_TACTICS_TICK_SEC * 3.0 - let crossExposed = c.urgent && wto_face_side_exposed(slot) + let urgentAdvance = c.urgent && c.distTarget > WTO_AI_PERC_NEAR_AWARE_M + let crossExposed = urgentAdvance && wto_face_side_exposed(slot) if fresh && tr.targetEid == slot.perceive.targetEid && !crossExposed && tr.wantSpeedMps > WTO_AI_FC_STOP_SPEED_MAX_MPS && tr.wantSpeedMps < march - speed = lerp(tr.wantSpeedMps, march, c.urgent ? WTO_AI_BHV_URGENT_SPEED_KEEP : 0.0) + speed = lerp(tr.wantSpeedMps, march, urgentAdvance ? WTO_AI_BHV_URGENT_SPEED_KEEP : 0.0) wto_sm_set_state(now, WTO_STATE_RUN_AND_GUN, c.baseGoal, speed, "engage", c.distTarget, slot) return true @@ -200,5 +201,3 @@ def public wto_tactics_update(world : WtoWorldSnap const&; now, dt : float; if !wto_tac_run(world, now, myPos, hullFwd, c, slot, crowdSummary) wto_bhv_take_over(now, WTO_BHV_ADVANCE, slot) wto_tac_advance(now, myPos, c, slot) - if !slot.tactics.faceForGun - slot.tactics.gunFacingTarget = INVALID_ENTITY_ID diff --git a/game-ai/ground/wto_ai_threat_common.das b/game-ai/ground/wto_ai_threat_common.das index 41ffeee..0e6ccb0 100644 --- a/game-ai/ground/wto_ai_threat_common.das +++ b/game-ai/ground/wto_ai_threat_common.das @@ -1,7 +1,4 @@ -// Threat table (decision layer design, section 4): every enemy the bot has discovered (exposure at -// least perception.discoverScore), with how dangerous it is to the bot. Rebuilt every perception -// tick from the bot's own exposure tracks, so it never knows more than the bot perceived. -// Penetration is not counted yet (see docs/AI-imporve/armor-probe). +// Threats measured by this bot. Near and mid visual contacts can enter before confirmation. options indenting = 2 options no_global_heap = true module wto_ai_threat_common shared @@ -14,10 +11,6 @@ require %appGame.wtoai.wto_ai_combat_types_common require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_world_common -// Seen this tick: the perception tick writes expSeenAt for every enemy in line of sight. -def private wto_threat_in_sight(now, seenAt : float) : bool - return now - seenAt <= WTO_AI_TACTICS_TICK_SEC * 1.5 - // The enemy's hull points within aimConeDeg of the bot, or it hit the bot within hitMemorySec. def private wto_threat_aiming(now : float; myPos : float3; u : WtoUnitSnap const&; p : WtoPerceiveState const&) : bool if p.lastOffenderEid == u.eid && now - p.lastDamagedAt <= WTO_AI_THREAT_HIT_MEMORY_SEC @@ -25,35 +18,39 @@ def private wto_threat_aiming(now : float; myPos : float3; u : WtoUnitSnap const let toMe = wto_xz_normalize(myPos - u.pos, u.hullFwd) return dot(u.hullFwd, toMe) >= cos(WTO_AI_THREAT_AIM_CONE_DEG * WTO_DEG_TO_RAD) -[never_inline] -def private wto_threat_danger(now : float; e : WtoThreatEntry const&; eid : EntityId; p : WtoPerceiveState const&) : float - var danger = 1.0 / (1.0 + e.dist / WTO_AI_THREAT_RANGE_SCALE_M) - if !e.seen - danger *= WTO_AI_THREAT_DISCOVERED_MUL - if !e.aiming +def private wto_threat_score(now, dist : float; aiming : bool; eid : EntityId; p : WtoPerceiveState const&) : float + var danger = 1.0 / (1.0 + dist / WTO_AI_THREAT_RANGE_SCALE_M) + if !aiming danger *= WTO_AI_THREAT_NOT_AIMING_MUL - if !e.seesMe - danger *= WTO_AI_THREAT_UNSEEN_MUL if p.lastOffenderEid == eid && now - p.lastDamagedAt <= WTO_AI_THREAT_HIT_MEMORY_SEC danger *= WTO_AI_THREAT_HIT_MUL return danger +// The same danger model ranks visible targets at every distance. +def public wto_threat_observed_danger(now : float; eye : float3; u : WtoUnitSnap const&; p : WtoPerceiveState const&) : float + let dist = sqrt(wto_xz_dist_sq(eye, u.pos)) + return wto_threat_score(now, dist, wto_threat_aiming(now, eye, u, p), u.eid, p) + [never_inline] def private wto_threat_add(now : float; myPos : float3; u : WtoUnitSnap const&; track : int; var slot : WtoBotSlot&) assume tt = slot.threat assume p = slot.perceive assume e = tt.entries[tt.count] e.eid = u.eid - e.seesMe = wto_threat_in_sight(now, p.expSeenAt[track]) + e.seesMe = p.expSeenAt[track] >= now e.seen = e.seesMe && p.expScore[track] >= 0.999 e.pos = p.expPos[track] e.dist = sqrt(wto_xz_dist_sq(myPos, e.pos)) e.aiming = wto_threat_aiming(now, myPos, u, p) - e.danger = wto_threat_danger(now, e, u.eid, p) + e.danger = wto_threat_score(now, e.dist, e.aiming, u.eid, p) + if !e.seen + e.danger *= WTO_AI_THREAT_DISCOVERED_MUL + if !e.seesMe + e.danger *= WTO_AI_THREAT_UNSEEN_MUL if tt.topIdx < 0 || e.danger > tt.entries[tt.topIdx].danger tt.topIdx = tt.count - if !e.seen && (tt.topUnseenIdx < 0 || e.danger > tt.entries[tt.topUnseenIdx].danger) - tt.topUnseenIdx = tt.count + if e.seesMe && (tt.topVisibleIdx < 0 || e.danger > tt.entries[tt.topVisibleIdx].danger) + tt.topVisibleIdx = tt.count tt.count++ // Per perception tick, right after wto_perceive_update. @@ -62,7 +59,11 @@ def public wto_threat_update(world : WtoWorldSnap const&; now : float; myPos : f slot.threat = WtoThreatTable() assume p = slot.perceive for k in range(WTO_MAX_EXPOSURE_TRACKS) - if !p.expEids[k] || p.expScore[k] < WTO_AI_PERC_DISCOVER_SCORE + if !p.expEids[k] + continue + let awareness = max(WTO_AI_PERC_NEAR_AWARE_M, WTO_AI_PERC_MID_AWARE_M) + let fresh = p.expSeenAt[k] >= now && wto_xz_dist_sq(myPos, p.expPos[k]) <= wto_sq(awareness) + if p.expScore[k] < WTO_AI_PERC_DISCOVER_SCORE && !fresh continue let uIdx = wto_world_find_unit(world, p.expEids[k]) if uIdx >= 0 && world.units[uIdx].isAlive && !world.units[uIdx].isAir diff --git a/game-ai/ground/wto_ai_traffic_common.das b/game-ai/ground/wto_ai_traffic_common.das index dd27736..334e139 100644 --- a/game-ai/ground/wto_ai_traffic_common.das +++ b/game-ai/ground/wto_ai_traffic_common.das @@ -16,45 +16,8 @@ require %appGame.wtoai.wto_ai_nav_types_common require %appGame.wtoai.wto_ai_navquery_common require %appGame.wtoai.wto_ai_navmesh_common -// A vehicle or wreck seen from the bot: how far ahead (along) and to the left (lat) its centre is, -// and the half extents of its hull along and across the bot's heading. -[safe_when_uninitialized] -struct private WtoTrafficBody - idx : int = -1 - isWreck : bool = false - pos : float3 = float3(0.0, 0.0, 0.0) - vel : float3 = float3(0.0, 0.0, 0.0) - along : float = 0.0 - lat : float = 0.0 - extAlong : float = 0.0 - extLat : float = 0.0 - -[never_inline] -def private wto_traffic_frame(myPos, dir, pos, vel, fwd : float3; halfLen, halfWid : float; var body : WtoTrafficBody&) - let left = float3(-dir.z, 0.0, dir.x) - let rel = float3(pos.x - myPos.x, 0.0, pos.z - myPos.z) - let fd = abs(dot(fwd, dir)) - let fl = abs(dot(fwd, left)) - body.pos = pos - body.vel = vel - body.along = dot(rel, dir) - body.lat = dot(rel, left) - body.extAlong = halfLen * fd + halfWid * fl - body.extLat = halfLen * fl + halfWid * fd - -// Free distance from the bot's front to the body's near end; negative once they overlap. -[never_inline] -def private wto_traffic_gap(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&) : float - return body.along - spec.halfLen - body.extAlong - -// Sideways distance between the centres that lets the hulls pass with passMarginM between them. -[never_inline] -def private wto_traffic_need(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&) : float - return spec.halfWid + body.extLat + WTO_AI_PF_PASS_MARGIN_M - -[never_inline] -def private wto_traffic_in_lane(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&; maxGap : float) : bool - return body.along > 0.0 && abs(body.lat) < wto_traffic_need(body, spec) && wto_traffic_gap(body, spec) < maxGap +require %appGame.wtoai.wto_ai_traffic_geometry_common +require %appGame.wtoai.wto_ai_math_common // The nearest standing body (stopped vehicle or wreck) in the bot's lane within `lookM`. [never_inline] @@ -130,36 +93,68 @@ def private wto_traffic_moving(world : WtoWorldSnap const&; myPos, dir : float3; // Side room for the hull: the mesh must allow the straight line to the passing point. [never_inline] -def private wto_traffic_room(navState : int; myPos, wp : float3; slot : WtoBotSlot const&) : bool +def private wto_traffic_room(world : WtoWorldSnap const&; navState : int; fromPos, toPos : float3; slot : WtoBotSlot const&) : bool + let delta = toPos - fromPos + let dist = wto_xz_len(delta) + if dist <= 0.1 + return true + let dir = wto_xz_normalize(delta, float3(1.0, 0.0, 0.0)) + var body = WtoTrafficBody() + if wto_traffic_find_standing(world, fromPos, dir, dist, slot, body) + return false if navState != WTO_NAVMESH_LOADED || slot.route.tier < 0 return true var frac = 0.0 - return wto_navq_raycast(slot.route.tier, slot.route.filter, myPos, wp, frac) != 0 + return wto_navq_raycast(slot.route.tier, slot.route.filter, fromPos, toPos, frac) != 0 -// Steers past `body` on the side with room: the nearer side first (or the side chosen within the -// last blockWaitSec, so the bot does not swing between sides), then the other. +// A stationary obstruction must be passed in two legs: get to its side before the near end, +// then drive past its far end. Keeping those points prevents a premature return to the path. [never_inline] -def private wto_traffic_pass(navState : int; now : float; myPos, dir : float3; body : WtoTrafficBody const&; - var slot : WtoBotSlot&) : bool +def private wto_traffic_pass(world : WtoWorldSnap const&; navState : int; now : float; myPos, dir : float3; body : WtoTrafficBody const&; + persistent : bool; var slot : WtoBotSlot&) : bool assume nav = slot.nav let left = float3(-dir.z, 0.0, dir.x) let need = wto_traffic_need(body, slot.spec) var side = abs(body.lat + need) <= abs(body.lat - need) ? 1.0 : -1.0 if now < nav.avoidSideUntil && nav.avoidSide != 0.0 side = nav.avoidSide - let beyond = max(body.along + body.extAlong + slot.spec.halfLen, WTO_AI_PF_BUMPER_RAY_M) - for _k in range(2) - let wp = myPos + dir * beyond + left * (body.lat + side * need) - if wto_traffic_room(navState, myPos, wp, slot) + let front = max(0.0, wto_traffic_gap(body, slot.spec) - WTO_AI_PF_BUMPER_STOP_M) + let back = body.along + body.extAlong + slot.spec.halfLen + WTO_AI_PF_BUMPER_STOP_M + for _i in range(2) + let lateral = left * (body.lat + side * (need + WTO_AI_PF_PASS_MARGIN_M)) + let entry = myPos + dir * front + lateral + let exit = myPos + dir * back + lateral + if wto_traffic_room(world, navState, myPos, entry, slot) && wto_traffic_room(world, navState, entry, exit, slot) nav.avoidActive = true - nav.avoidTarget = wp + nav.avoidTarget = entry nav.avoidSide = side nav.avoidSideUntil = now + WTO_AI_PF_BLOCK_WAIT_SEC nav.avoidSpeedCap = min(nav.avoidSpeedCap, WTO_AI_PF_PASS_SPEED_MPS) + if persistent + nav.passEntry = entry + nav.passExit = exit + nav.passAtSide = false + nav.passUntil = now + WTO_AI_PF_BLOCK_TTL_SEC + max(0.0, back) / WTO_AI_PF_PASS_SPEED_MPS return true side = -side return false +[never_inline] +def private wto_traffic_follow_pass(now : float; myPos, routeDir : float3; var nav : WtoNavState&) : bool + if now >= nav.passUntil + return false + let along = wto_xz_normalize(nav.passExit - nav.passEntry, routeDir) + let marginSq = wto_sq(WTO_AI_PF_PASS_MARGIN_M) + if dot(along, routeDir) < 0.0 || wto_xz_dist_sq(myPos, nav.passExit) <= marginSq || dot(myPos - nav.passExit, along) >= 0.0 + nav.passUntil = -100.0 + return false + if wto_xz_dist_sq(myPos, nav.passEntry) <= marginSq + nav.passAtSide = true + nav.avoidActive = true + nav.avoidTarget = nav.passAtSide ? nav.passExit : nav.passEntry + nav.avoidSpeedCap = min(nav.avoidSpeedCap, WTO_AI_PF_PASS_SPEED_MPS) + return true + // No way past: stop short; after blockWaitSec mark the body for path searches and plan again. [never_inline] def private wto_traffic_blocked(navState : int; now : float; body : WtoTrafficBody const&; var slot : WtoBotSlot&) @@ -226,19 +221,24 @@ def public wto_traffic_update(world : WtoWorldSnap const&; navState : int; now : let meets = wto_traffic_moving(world, myPos, dir, speedMps, slot, oncoming) var standing = WtoTrafficBody() let lookM = max(WTO_AI_PF_BUMPER_RAY_M, speedMps * WTO_AI_PF_TRAFFIC_TTC_SEC) - if wto_traffic_find_standing(world, myPos, dir, lookM, slot, standing) + let blockedAhead = wto_traffic_find_standing(world, myPos, dir, lookM, slot, standing) + if blockedAhead wto_traffic_contact(now, speedMps, standing, slot) - if !wto_traffic_pass(navState, now, myPos, dir, standing, slot) + else + nav.contactSince = -100.0 + if wto_traffic_follow_pass(now, myPos, dir, nav) + return + if blockedAhead + if !wto_traffic_pass(world, navState, now, myPos, dir, standing, true, slot) wto_traffic_blocked(navState, now, standing, slot) return nav.blockedSince = -100.0 - nav.contactSince = -100.0 if !meets nav.yieldUntil = -100.0 return if !narrow - if !wto_traffic_pass(navState, now, myPos, dir, oncoming, slot) - nav.avoidSpeedCap = min(nav.avoidSpeedCap, WTO_AI_PF_PASS_SPEED_MPS) + if !wto_traffic_pass(world, navState, now, myPos, dir, oncoming, false, slot) + wto_traffic_yield(now, nav) return if !wto_traffic_has_priority(slot, world.units[oncoming.idx]) wto_traffic_yield(now, nav) diff --git a/game-ai/ground/wto_ai_traffic_geometry_common.das b/game-ai/ground/wto_ai_traffic_geometry_common.das new file mode 100644 index 0000000..8fce273 --- /dev/null +++ b/game-ai/ground/wto_ai_traffic_geometry_common.das @@ -0,0 +1,97 @@ +// Shared hull projections for route traffic, speed caps, and forward and rear clearance. +options indenting = 2 +options no_global_heap = true +module wto_ai_traffic_geometry_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_types_common + +// A vehicle or wreck seen from the bot: how far ahead (along) and to the left (lat) its centre is, +// and the half extents of its hull along and across the bot's heading. +[safe_when_uninitialized] +struct public WtoTrafficBody + idx : int = -1 + isWreck : bool = false + pos : float3 = float3(0.0, 0.0, 0.0) + vel : float3 = float3(0.0, 0.0, 0.0) + along : float = 0.0 + lat : float = 0.0 + extAlong : float = 0.0 + extLat : float = 0.0 + +[never_inline] +def public wto_traffic_frame(myPos, dir, pos, vel, fwd : float3; halfLen, halfWid : float; var body : WtoTrafficBody&) + let left = float3(-dir.z, 0.0, dir.x) + let rel = float3(pos.x - myPos.x, 0.0, pos.z - myPos.z) + let fd = abs(dot(fwd, dir)) + let fl = abs(dot(fwd, left)) + body.pos = pos + body.vel = vel + body.along = dot(rel, dir) + body.lat = dot(rel, left) + body.extAlong = halfLen * fd + halfWid * fl + body.extLat = halfLen * fl + halfWid * fd + +// Free distance from the bot's front to the body's near end; negative once they overlap. +[never_inline] +def public wto_traffic_gap(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&) : float + return body.along - spec.halfLen - body.extAlong + +// Sideways distance between the centres that lets the hulls pass with passMarginM between them. +[never_inline] +def public wto_traffic_need(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&) : float + return spec.halfWid + body.extLat + WTO_AI_PF_PASS_MARGIN_M + +[never_inline] +def public wto_traffic_in_lane(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&; maxGap : float) : bool + return body.along > 0.0 && abs(body.lat) < wto_traffic_need(body, spec) && wto_traffic_gap(body, spec) < maxGap + +[safe_when_uninitialized] +struct public WtoTrafficClearance + frontM : float = 99.0 + rearM : float = 99.0 + frontSpeed : float = 0.0 + rearSpeed : float = 0.0 + +def private wto_traffic_clip(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&; + hullDir : float3; var clearance : WtoTrafficClearance&) + if abs(body.lat) >= wto_traffic_need(body, spec) + return + let edge = max(0.0, abs(body.along) - body.extAlong) + if body.along >= 0.0 && edge < clearance.frontM + clearance.frontM = edge + clearance.frontSpeed = dot(body.vel, hullDir) + elif body.along < 0.0 && edge < clearance.rearM + clearance.rearM = edge + clearance.rearSpeed = -dot(body.vel, hullDir) + +// Project both ends of the current hull against living vehicles of either team and wrecks. +[never_inline] +def public wto_traffic_clearance(world : WtoWorldSnap const&; myPos, hullDir : float3; + slot : WtoBotSlot const&; var clear : WtoTrafficClearance&) + var body = WtoTrafficBody() + for i in range(world.unitCount) + assume u = world.units[i] + if u.eid == slot.eid || !u.isGround || !u.isAlive + continue + wto_traffic_frame(myPos, hullDir, u.pos, u.vel, u.hullFwd, u.halfLen, u.halfWid, body) + wto_traffic_clip(body, slot.spec, hullDir, clear) + let still = float3(0.0, 0.0, 0.0) + for i in range(world.wreckCount) + assume w = world.wrecks[i] + if w.eid == slot.eid + continue + wto_traffic_frame(myPos, hullDir, w.pos, still, w.hullFwd, w.halfLen, w.halfWid, body) + wto_traffic_clip(body, slot.spec, hullDir, clear) + +def public wto_traffic_brake_speed(edgeM, neighborSpeed, currentSpeed, halfLen : float) : float + if edgeM >= 99.0 + return 99.0 + let room = edgeM - halfLen - WTO_AI_PF_BUMPER_STOP_M + if room <= 0.0 + return 0.0 + let closing = max(0.0, currentSpeed - neighborSpeed) + let remaining = max(0.0, room - closing * WTO_AI_NAV_TICK_SEC) + return max(0.0, neighborSpeed + sqrt(2.0 * WTO_AI_PF_BRAKE_DECEL * remaining)) diff --git a/game-ai/ground/wto_ai_traverse_common.das b/game-ai/ground/wto_ai_traverse_common.das index e9fe26b..d5b99bb 100644 --- a/game-ai/ground/wto_ai_traverse_common.das +++ b/game-ai/ground/wto_ai_traverse_common.das @@ -23,7 +23,7 @@ let private WTO_FIRST_GUNNER_TRIGGER = int(0x13) def public wto_unit_model_path(className : string) : string return find(className, "/") >= 0 ? ("gamedata/units/" + className + ".blk") : ("gamedata/units/tankModels/" + className + ".blk") -def private wto_valid_angle_range(angles : float2) : bool +def public wto_valid_angle_range(angles : float2) : bool return wto_is_finite(angles.x) && wto_is_finite(angles.y) && angles.x <= angles.y [never_inline] @@ -62,15 +62,15 @@ def private wto_load_gun_traverse(className : string; triggerNo, weaponIndex : i let sectors = mount |> datablock_get_block_by_name("limitsTable") traverse.hasPitchTable = sectors != null && sectors.paramCount > 0u -def private wto_full_gun_traverse(yaw : float2) : bool +def public wto_full_gun_traverse(yaw : float2) : bool return yaw.y - yaw.x >= 360.0 -def private wto_yaw_in_mount_coordinates(yaw : float; arc : float2) : float +def public wto_yaw_in_mount_coordinates(yaw : float; arc : float2) : float let center = (arc.x + arc.y) * 0.5 return center + wto_wrap_deg(yaw - center) [never_inline] -def private wto_gun_pitch_at_yaw(className : string; triggerNo, weaponIndex : int; yaw : float; +def public wto_gun_pitch_at_yaw(className : string; triggerNo, weaponIndex : int; yaw : float; var traverse : WtoGunTraverse&) : float2 if !traverse.hasPitchTable return traverse.pitch @@ -115,7 +115,7 @@ def public wto_world_to_hull_deg(worldDir, hullFwd, hullUp, hullLeft : float3; outPitchDeg = atan2(u, max(1.0e-5, horiz)) * WTO_RAD_TO_DEG [never_inline] -def private wto_hull_deg_to_world(yawDeg, pitchDeg : float; hullFwd, hullUp, hullLeft : float3) : float3 +def public wto_hull_deg_to_world(yawDeg, pitchDeg : float; hullFwd, hullUp, hullLeft : float3) : float3 let yr = yawDeg * WTO_DEG_TO_RAD let pr = pitchDeg * WTO_DEG_TO_RAD let cp = cos(pr) @@ -130,11 +130,15 @@ def private wto_step_mounted_yaw(current, desired, step : float; arc : float2) : let clampedTarget = clamp(wto_yaw_in_mount_coordinates(desired, arc), arc.x, arc.y) return clamp(clampedCurrent + clamp(clampedTarget - clampedCurrent, -step, step), arc.x, arc.y) -def private wto_track_blocked_pitch(wishPitchDeg, dtStep : float; var slot : WtoBotSlot&) +def private wto_track_blocked_pitch(wishPitch, wishYaw, cmdYaw, dtStep : float; pitch : float2; var slot : WtoBotSlot&) assume fc = slot.fire let pitchSpd = abs(fc.curPitchDeg - fc.prevPitchDeg) / dtStep fc.prevPitchDeg = fc.curPitchDeg - if slot.perceive.hasClearLos && wishPitchDeg < fc.curPitchDeg - 2.3 && pitchSpd < 0.8 + let align = WTO_AI_FC_BASE_ALIGN_DEG + let aimedYaw = abs(wto_wrap_deg(cmdYaw - wishYaw)) <= align + let outside = wishPitch < pitch.x - align || wishPitch > pitch.y + align + fc.pitchAtLimit = aimedYaw && wto_valid_angle_range(pitch) && outside + if slot.perceive.hasClearLos && fc.pitchAtLimit && pitchSpd < 0.8 fc.pitchClampSec = min(2.0, fc.pitchClampSec + dtStep) fc.pitchBlocked = fc.pitchClampSec >= 0.75 else @@ -147,6 +151,7 @@ def public wto_drive_mounted_gun(var unit : Unit?; className : string; dt : floa wishYawDeg, wishPitchDeg : float; var slot : WtoBotSlot&) assume fc = slot.fire let dtStep = clamp(dt, 0.005, 0.12) + fc.pitchAtLimit = false if fc.traverseTurretNo != fc.turretNo fc.traverseTurretNo = fc.turretNo fc.traverse = WtoGunTraverse() @@ -166,12 +171,12 @@ def public wto_drive_mounted_gun(var unit : Unit?; className : string; dt : floa fc.curPitchDeg = turret.currentState.pitch if !fc.traverse.known return - wto_track_blocked_pitch(wishPitchDeg, dtStep, slot) let yaw = fc.traverse.yaw let maxYawStep = max(24.0, slot.spec.turretYawSpd * 1.1) * dtStep let cmdYaw = wto_step_mounted_yaw(fc.curYawDeg, wishYawDeg, maxYawStep, yaw) let maxPitchStep = max(10.0, slot.spec.turretPitchSpd * 1.1) * dtStep let pitch = wto_gun_pitch_at_yaw(className, triggerNo, weaponIndex, cmdYaw, fc.traverse) + wto_track_blocked_pitch(wishPitchDeg, wishYawDeg, cmdYaw, dtStep, pitch, slot) turret.yawLim = cmdYaw if pitch.x <= pitch.y let pitchDelta = clamp(wishPitchDeg - fc.curPitchDeg, -maxPitchStep, maxPitchStep) @@ -206,23 +211,3 @@ def public wto_aim_aux_mount(var unit : Unit?; className : string; dt : float; t def public wto_apply_weapon_aim(var unit : Unit?; dt : float) var pos = unit.pos updateWeaponAnims(*unit.weap, clamp(dt, 0.005, 0.12), 1.0, pos) - -def public wto_set_hull_aim(unit : Unit const?; active : bool; wishYaw : float; liveBarrelDir : float3; - var slot : WtoBotSlot&) - assume fc = slot.fire - var target = INVALID_ENTITY_ID - if active - var arc = fc.traverse.yaw - if !fc.traverse.known - var fixedYaw, pitch : float - wto_world_to_hull_deg(liveBarrelDir, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2], fixedYaw, pitch) - arc = float2(fixedYaw, fixedYaw) - let aimYaw = wto_yaw_in_mount_coordinates(wishYaw, arc) - let tolerance = arc.x == arc.y ? WTO_AI_FC_BASE_ALIGN_DEG : 0.0 - if !wto_full_gun_traverse(arc) && (aimYaw < arc.x - tolerance || aimYaw > arc.y + tolerance) - target = slot.perceive.targetEid - let yawToTurn = wto_wrap_deg(wishYaw - (arc.x + arc.y) * 0.5) - fc.hullAimDir = wto_hull_deg_to_world(yawToTurn, 0.0, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2]) - if target != fc.hullAimTarget - slot.nextNavAt = 0.0 - fc.hullAimTarget = target diff --git a/game-ai/ground/wto_ai_turret_common.das b/game-ai/ground/wto_ai_turret_common.das index 28f71db..7db5a26 100644 --- a/game-ai/ground/wto_ai_turret_common.das +++ b/game-ai/ground/wto_ai_turret_common.das @@ -1,8 +1,4 @@ -// Turret channel (decision layer design, section 5): where the turret looks when it is not aiming -// at an engaged target. Never the hull's front by default: the most dangerous discovered threat -// not seen clearly yet, then the last exit of a lost target, the remembered target, a cue (hit, -// sound, radio), and otherwise a sweep across the route ahead. A chosen threat is kept for at -// least turret.minDwellSec so the turret does not swing between two of them. +// The turret focuses the most dangerous visible contact, then watches memory and cues or scans. options indenting = 2 options no_global_heap = true module wto_ai_turret_common shared @@ -16,29 +12,35 @@ require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_nav_types_common require %appGame.wtoai.wto_ai_threat_common -// Whether a threat not seen clearly yet is enough more dangerous than the engaged target that -// the turret should turn to it instead of aiming (turret.switchMargin). def public wto_turret_prefers_threat(slot : WtoBotSlot const&) : bool - let top = slot.threat.topUnseenIdx - if top < 0 + let top = slot.threat.topVisibleIdx + if top < 0 || slot.perceive.targetIsAir + return false + assume threat = slot.threat.entries[top] + if threat.eid == slot.perceive.targetEid return false let engaged = wto_threat_danger_of(slot, slot.perceive.targetEid) - return slot.threat.entries[top].danger > engaged * (1.0 + WTO_AI_TURRET_SWITCH_MARGIN) + return threat.danger > engaged * (1.0 + WTO_AI_TURRET_SWITCH_MARGIN) -// The threat to look at: the most dangerous one not seen clearly, or the one already looked at -// while its minimum dwell lasts and it is still in the table; -1 for none. [never_inline] def private wto_turret_pick_threat(now : float; var slot : WtoBotSlot&) : int assume tr = slot.turret assume tt = slot.threat - if now < tr.holdUntil - for i in range(tt.count) - if tt.entries[i].eid == tr.lookEid && !tt.entries[i].seen - return i - let top = tt.topUnseenIdx - if top >= 0 && tt.entries[top].eid != tr.lookEid - tr.lookEid = tt.entries[top].eid + let top = tt.topVisibleIdx + if top < 0 + tr.lookEid = INVALID_ENTITY_ID + return -1 + assume threat = tt.entries[top] + if threat.eid != tr.lookEid + if now < tr.holdUntil + for i in range(tt.count) + assume held = tt.entries[i] + if held.eid == tr.lookEid && held.seesMe && threat.danger <= held.danger * (1.0 + WTO_AI_TURRET_SWITCH_MARGIN) + return i + tr.lookEid = threat.eid tr.holdUntil = now + WTO_AI_TURRET_MIN_DWELL_SEC + if WTO_AI_DIAG_TELEMETRY + print("WTO_AI|TURRET_FOCUS|eid={uint(slot.eid)}|target={uint(tr.lookEid)}|dist={threat.dist}|danger={threat.danger}\n") return top // Sweep across the route: scanArcDeg either side of where the bot drives (or of its order goal diff --git a/game-ai/ground/wto_ai_types_common.das b/game-ai/ground/wto_ai_types_common.das index 9373fb4..4122da4 100644 --- a/game-ai/ground/wto_ai_types_common.das +++ b/game-ai/ground/wto_ai_types_common.das @@ -227,7 +227,6 @@ struct public WtoTacticsState faceThreatDir : float3 = float3(1.0, 0.0, 0.0) faceFromThreat : bool = false faceForGun : bool = false - gunFacingTarget : EntityId = INVALID_ENTITY_ID reverseTravel : bool = false reverseSince : float = -100.0 diff --git a/game-ai/ground/wto_ai_unstick_common.das b/game-ai/ground/wto_ai_unstick_common.das index 99f87d1..97e2fe2 100644 --- a/game-ai/ground/wto_ai_unstick_common.das +++ b/game-ai/ground/wto_ai_unstick_common.das @@ -49,6 +49,7 @@ def private wto_unstick_start_reverse(navState : int; now : float; myPos, hullFw let forward = slot.tactics.reverseTravel if !wto_unstick_reverse_target(navState, myPos, hullFwd, forward, slot, target) return + slot.nav.passUntil = -100.0 slot.nav.reverseTarget = target slot.nav.unstickForward = forward slot.nav.reverseUntil = now + WTO_AI_PF_UNSTICK_REV_SEC @@ -123,7 +124,8 @@ def public wto_unstick_reversing(now : float; myPos : float3; var slot : WtoBotS let dir = wto_xz_normalize(nav.reverseTarget - myPos, -nav.steerDir) nav.steerDir = dir let mode = nav.unstickForward ? WTO_DRIVE_CRUISE : WTO_DRIVE_REVERSE - let speed = nav.unstickForward ? min(slot.spec.vMaxFwd, slot.spec.vMaxRev) : max(2.0, slot.spec.vMaxRev) + let axisCap = nav.unstickForward ? nav.frontTrafficSpeedCap : nav.rearTrafficSpeedCap + let speed = min(slot.spec.vMaxRev, axisCap) wto_drive_cmd_set(slot.driveCmd, mode, nav.reverseTarget, dir, speed, nav.frontClearM, nav.rearClearM) return true diff --git a/game-ai/ground/wto_ai_world_common.das b/game-ai/ground/wto_ai_world_common.das index 14b32e2..05ce8b8 100644 --- a/game-ai/ground/wto_ai_world_common.das +++ b/game-ai/ground/wto_ai_world_common.das @@ -154,7 +154,7 @@ def private wto_refresh_units(var snap : WtoWorldSnap&) let army = int(u.army) if army != 1 && army != 2 return - let isGround = gm != null && gm.moveSys != null && as_hv(u) != null + let isGround = gm != null && as_hv(u) != null let isAir = u.isFlightModelWrap if !isGround && !isAir return diff --git a/packages/patcher/src/ground-ai/ground-ai-config.ts b/packages/patcher/src/ground-ai/ground-ai-config.ts index 60ff06d..25b7479 100644 --- a/packages/patcher/src/ground-ai/ground-ai-config.ts +++ b/packages/patcher/src/ground-ai/ground-ai-config.ts @@ -251,6 +251,7 @@ export interface GroundAiConfig { readonly switchMargin: number; readonly scanArcDeg: number; readonly scanPeriodSec: number; + readonly fixedMountYawSpanDeg: number; }; readonly behavior: { readonly scoreIntervalSec: number; @@ -507,6 +508,7 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['WTO_AI_TURRET_SWITCH_MARGIN', 'float', c.turret.switchMargin], ['WTO_AI_TURRET_SCAN_ARC_DEG', 'float', c.turret.scanArcDeg], ['WTO_AI_TURRET_SCAN_PERIOD_SEC', 'float', c.turret.scanPeriodSec], + ['WTO_AI_TURRET_FIXED_MOUNT_SPAN_DEG', 'float', c.turret.fixedMountYawSpanDeg], ['WTO_AI_BHV_SCORE_SEC', 'float', c.behavior.scoreIntervalSec], ['WTO_AI_BHV_ADVANCE_HOLD_SEC', 'float', c.behavior.advanceHoldSec], ['WTO_AI_BHV_ENGAGE_HOLD_SEC', 'float', c.behavior.engageHoldSec], From 5786fee63b4bf40b6f867132c62ea7f16de97782 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sun, 6 Dec 2026 13:53:52 +0800 Subject: [PATCH 17/19] feat(ground-ai): add a replay trace and the AI lab viewer Battle behaviour could only be judged by watching one bot at a time. The AI now logs a replay trace and a local viewer plays it back on the map. Game scripts: - wto_ai_trace_common.das writes every diagnostics.traceIntervalSec the capture zones (WTO_AI|TRACE_CAP), every ground unit including players (TRACE_U) and each bot's decision state (TRACE_B: order, behavior, targets, what the turret looks at and why, barrel heading, fire denial, hit probability), plus part damage with its offender (HIT) and deaths (DEATH). It uses no engine module so a simulator can load it as is. - The turret state records the reason and world direction of each look. - New tuning diagnostics.trace and diagnostics.traceIntervalSec through server reader, patcher constants, launcher schema, fields and labels. packages/ground-sim: readers for the baked .wtonav pack (mesh polygons, cover points, tactical grid) and .pois.json, the trace parser and the names of the logged codes. apps/ai-lab: Vite viewer with a local API that lists nav packs and lab logs and decrypts a chosen .clog with wtotools. It draws the nav mesh, vehicles, barrels and wished turret directions, goals, target links, shots, hits and deaths over a timeline, with per-bot strips for behavior, fire denial and turret reason. Paths live in an untracked lab.local.json. The lab has its own tsconfig and stays out of the root typecheck. Root and launcher typechecks pass; the lab typechecks and replayed two lab battles. --- apps/ai-lab/.gitignore | 2 + apps/ai-lab/index.html | 12 + apps/ai-lab/lab.local.example.json | 5 + apps/ai-lab/package.json | 22 ++ apps/ai-lab/server/lab-api.ts | 118 +++++++++ apps/ai-lab/src/App.tsx | 139 +++++++++++ apps/ai-lab/src/Inspector.tsx | 94 ++++++++ apps/ai-lab/src/MapView.tsx | 87 +++++++ apps/ai-lab/src/Timeline.tsx | 86 +++++++ apps/ai-lab/src/data.ts | 48 ++++ apps/ai-lab/src/draw.ts | 168 +++++++++++++ apps/ai-lab/src/frames.ts | 73 ++++++ apps/ai-lab/src/labels.ts | 37 +++ apps/ai-lab/src/main.tsx | 7 + apps/ai-lab/src/mapLayer.ts | 88 +++++++ apps/ai-lab/src/style.css | 26 ++ apps/ai-lab/src/view.ts | 39 +++ apps/ai-lab/tsconfig.json | 23 ++ apps/ai-lab/vite.config.ts | 8 + .../src/renderer/src/i18n/locales/en.json | 4 +- .../src/renderer/src/i18n/locales/zh-CN.json | 4 +- .../src/pages/tuning/bot-tuning-fields.ts | 2 + apps/launcher/src/shared/schemas/tuning.ts | 2 + apps/server/src/tuning/ground-ai-tuning.ts | 2 + apps/server/tuning/ground-ai.jsonc | 7 +- game-ai/ground/wto_ai_combat_types_common.das | 13 +- game-ai/ground/wto_ai_fire_common.das | 2 + game-ai/ground/wto_ai_runtime.das | 10 + game-ai/ground/wto_ai_trace_common.das | 86 +++++++ game-ai/ground/wto_ai_turret_common.das | 6 + packages/ground-sim/package.json | 9 + packages/ground-sim/src/index.ts | 15 ++ packages/ground-sim/src/map/pois.ts | 51 ++++ packages/ground-sim/src/map/wtonav.ts | 226 ++++++++++++++++++ packages/ground-sim/src/trace/names.ts | 34 +++ packages/ground-sim/src/trace/parse.ts | 136 +++++++++++ packages/ground-sim/src/trace/types.ts | 90 +++++++ .../patcher/src/ground-ai/ground-ai-config.ts | 4 + tsconfig.json | 5 +- 39 files changed, 1784 insertions(+), 6 deletions(-) create mode 100644 apps/ai-lab/.gitignore create mode 100644 apps/ai-lab/index.html create mode 100644 apps/ai-lab/lab.local.example.json create mode 100644 apps/ai-lab/package.json create mode 100644 apps/ai-lab/server/lab-api.ts create mode 100644 apps/ai-lab/src/App.tsx create mode 100644 apps/ai-lab/src/Inspector.tsx create mode 100644 apps/ai-lab/src/MapView.tsx create mode 100644 apps/ai-lab/src/Timeline.tsx create mode 100644 apps/ai-lab/src/data.ts create mode 100644 apps/ai-lab/src/draw.ts create mode 100644 apps/ai-lab/src/frames.ts create mode 100644 apps/ai-lab/src/labels.ts create mode 100644 apps/ai-lab/src/main.tsx create mode 100644 apps/ai-lab/src/mapLayer.ts create mode 100644 apps/ai-lab/src/style.css create mode 100644 apps/ai-lab/src/view.ts create mode 100644 apps/ai-lab/tsconfig.json create mode 100644 apps/ai-lab/vite.config.ts create mode 100644 game-ai/ground/wto_ai_trace_common.das create mode 100644 packages/ground-sim/package.json create mode 100644 packages/ground-sim/src/index.ts create mode 100644 packages/ground-sim/src/map/pois.ts create mode 100644 packages/ground-sim/src/map/wtonav.ts create mode 100644 packages/ground-sim/src/trace/names.ts create mode 100644 packages/ground-sim/src/trace/parse.ts create mode 100644 packages/ground-sim/src/trace/types.ts diff --git a/apps/ai-lab/.gitignore b/apps/ai-lab/.gitignore new file mode 100644 index 0000000..2429ea8 --- /dev/null +++ b/apps/ai-lab/.gitignore @@ -0,0 +1,2 @@ +lab.local.json +.cache/ diff --git a/apps/ai-lab/index.html b/apps/ai-lab/index.html new file mode 100644 index 0000000..403ef2d --- /dev/null +++ b/apps/ai-lab/index.html @@ -0,0 +1,12 @@ + + + + + + WTOffline AI Lab + + +
+ + + diff --git a/apps/ai-lab/lab.local.example.json b/apps/ai-lab/lab.local.example.json new file mode 100644 index 0000000..8341569 --- /dev/null +++ b/apps/ai-lab/lab.local.example.json @@ -0,0 +1,5 @@ +{ + "mapsDir": "J:/GAME/WTOfflineProject-tank-ai/build/nav-stage2-fix/maps", + "logsDir": "J:/GAME/WTLab/client-2.61.0.58/.game_logs", + "python": "J:/GAME/WTOfflineProject/.venv/Scripts/python.exe" +} diff --git a/apps/ai-lab/package.json b/apps/ai-lab/package.json new file mode 100644 index 0000000..0330bcb --- /dev/null +++ b/apps/ai-lab/package.json @@ -0,0 +1,22 @@ +{ + "name": "@wto/ai-lab", + "version": "0.1.0", + "private": true, + "description": "Ground AI lab: replay viewer for battle traces and simulator runs.", + "type": "module", + "scripts": { + "dev": "vite", + "typecheck": "tsc --noEmit -p tsconfig.json" + }, + "dependencies": { + "@wto/ground-sim": "*", + "react": "^19.2.8", + "react-dom": "^19.2.8" + }, + "devDependencies": { + "@types/react": "^19.2.17", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^5.2.0", + "vite": "^7.3.6" + } +} diff --git a/apps/ai-lab/server/lab-api.ts b/apps/ai-lab/server/lab-api.ts new file mode 100644 index 0000000..78c31db --- /dev/null +++ b/apps/ai-lab/server/lab-api.ts @@ -0,0 +1,118 @@ +/** + * Dev-server API of the AI lab (local only): + * GET /api/maps levels that have a navigation pack in mapsDir + * GET /api/maps/file?name= a pack or POI file of mapsDir + * GET /api/logs game logs (.clog) in logsDir, newest first + * GET /api/logs/text?name= a log decrypted with wtotools (cached until the log changes) + * Paths come from lab.local.json next to this app (see lab.local.example.json). + */ +import { execFile } from 'node:child_process'; +import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync } from 'node:fs'; +import type { ServerResponse } from 'node:http'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import type { Connect, Plugin } from 'vite'; + +interface LabConfig { + readonly mapsDir: string; + readonly logsDir: string; + readonly python: string; +} + +const APP_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const CACHE_DIR = path.join(APP_DIR, '.cache'); +const SAFE_NAME = /^[\w.-]+$/; + +function loadConfig(): LabConfig { + const file = path.join(APP_DIR, 'lab.local.json'); + const raw = existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as Record) : {}; + const str = (key: string, fallback: string): string => (typeof raw[key] === 'string' ? (raw[key] as string) : fallback); + return { + mapsDir: str('mapsDir', path.resolve(APP_DIR, '../../build/nav-stage2-fix/maps')), + logsDir: str('logsDir', ''), + python: str('python', 'python'), + }; +} + +function sendJson(res: ServerResponse, status: number, body: unknown): void { + res.statusCode = status; + res.setHeader('Content-Type', 'application/json; charset=utf-8'); + res.end(JSON.stringify(body)); +} + +function sendFile(res: ServerResponse, file: string, type: string): void { + res.statusCode = 200; + res.setHeader('Content-Type', type); + createReadStream(file).pipe(res); +} + +function listMaps(cfg: LabConfig): { level: string; pois: boolean }[] { + if (!existsSync(cfg.mapsDir)) return []; + return readdirSync(cfg.mapsDir) + .filter((f) => f.endsWith('.wtonav')) + .map((f) => { + const level = f.slice(0, -'.wtonav'.length); + return { level, pois: existsSync(path.join(cfg.mapsDir, `${level}.pois.json`)) }; + }); +} + +function listLogs(cfg: LabConfig): { name: string; size: number; mtime: number }[] { + if (cfg.logsDir === '' || !existsSync(cfg.logsDir)) return []; + return readdirSync(cfg.logsDir) + .filter((f) => f.endsWith('.clog')) + .map((name) => { + const st = statSync(path.join(cfg.logsDir, name)); + return { name, size: st.size, mtime: st.mtimeMs }; + }) + .sort((a, b) => b.mtime - a.mtime); +} + +/** Decrypts `name` into the cache unless the cached text is newer than the log. */ +function decryptLog(cfg: LabConfig, name: string): Promise { + const source = path.join(cfg.logsDir, name); + const out = path.join(CACHE_DIR, `${name}.txt`); + mkdirSync(CACHE_DIR, { recursive: true }); + if (existsSync(out) && statSync(out).mtimeMs >= statSync(source).mtimeMs) return Promise.resolve(out); + return new Promise((resolve, reject) => { + execFile(cfg.python, ['-m', 'wtotools.cli', 'decrypt-clog', source, '--out', out], { timeout: 180_000 }, (err, _stdout, stderr) => { + if (err !== null) reject(new Error(`decrypt-clog failed: ${stderr || err.message}`)); + else resolve(out); + }); + }); +} + +async function handle(cfg: LabConfig, url: URL, res: ServerResponse): Promise { + const name = url.searchParams.get('name') ?? ''; + if (url.pathname === '/api/maps') { sendJson(res, 200, listMaps(cfg)); return true; } + if (url.pathname === '/api/logs') { sendJson(res, 200, listLogs(cfg)); return true; } + if (url.pathname !== '/api/maps/file' && url.pathname !== '/api/logs/text') return false; + if (!SAFE_NAME.test(name)) { sendJson(res, 400, { error: 'bad file name' }); return true; } + if (url.pathname === '/api/maps/file') { + const file = path.join(cfg.mapsDir, name); + if (!existsSync(file)) sendJson(res, 404, { error: `no ${name} in ${cfg.mapsDir}` }); + else sendFile(res, file, name.endsWith('.json') ? 'application/json' : 'application/octet-stream'); + return true; + } + if (!name.endsWith('.clog') || !existsSync(path.join(cfg.logsDir, name))) { + sendJson(res, 404, { error: `no log ${name}` }); + return true; + } + sendFile(res, await decryptLog(cfg, name), 'text/plain; charset=utf-8'); + return true; +} + +export function labApi(): Plugin { + return { + name: 'wto-ai-lab-api', + configureServer(server) { + const middleware: Connect.NextHandleFunction = (req, res, next) => { + const url = new URL(req.url ?? '/', 'http://localhost'); + if (!url.pathname.startsWith('/api/')) { next(); return; } + handle(loadConfig(), url, res) + .then((handled) => { if (!handled) sendJson(res, 404, { error: 'unknown endpoint' }); }) + .catch((err: unknown) => sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) })); + }; + server.middlewares.use(middleware); + }, + }; +} diff --git a/apps/ai-lab/src/App.tsx b/apps/ai-lab/src/App.tsx new file mode 100644 index 0000000..161f5cd --- /dev/null +++ b/apps/ai-lab/src/App.tsx @@ -0,0 +1,139 @@ +/** AI lab replay viewer: pick a game log, a battle in it, and play it back on the map. */ +import type { TraceBattle } from '@wto/ground-sim'; +import { useEffect, useMemo, useState } from 'react'; +import { fetchLogs, fetchMaps, loadLog, loadMap, type LogEntry, type MapData, type MapEntry } from './data.ts'; +import type { Layers } from './draw.ts'; +import { sceneAt } from './frames.ts'; +import { Inspector } from './Inspector.tsx'; +import { buildMapLayer } from './mapLayer.ts'; +import { MapView } from './MapView.tsx'; +import { Timeline } from './Timeline.tsx'; + +const LAYER_LABELS: Readonly> = { + goals: '目标点', links: '目标连线', cones: '炮塔视野', labels: '标签', events: '开火与受击', +}; + +function logLabel(l: LogEntry): string { + const when = new Date(l.mtime).toLocaleString(); + return `${l.name}(${(l.size / 1e6).toFixed(1)} MB,${when})`; +} + +export function App(): React.JSX.Element { + const [maps, setMaps] = useState([]); + const [logs, setLogs] = useState([]); + const [logName, setLogName] = useState(''); + const [battles, setBattles] = useState([]); + const [battleIdx, setBattleIdx] = useState(0); + const [mapData, setMapData] = useState(undefined); + const [exposure, setExposure] = useState(false); + const [covers, setCovers] = useState(false); + const [layers, setLayers] = useState({ goals: true, links: true, cones: false, labels: false, events: true }); + const [t, setT] = useState(0); + const [playing, setPlaying] = useState(false); + const [speed, setSpeed] = useState(4); + const [selected, setSelected] = useState(undefined); + const [status, setStatus] = useState(''); + + const refreshLogs = (): void => { fetchLogs().then(setLogs).catch((e: unknown) => setStatus(String(e))); }; + useEffect(() => { + fetchMaps().then(setMaps).catch((e: unknown) => setStatus(String(e))); + refreshLogs(); + }, []); + + const openLog = (name: string): void => { + setLogName(name); + setPlaying(false); + setStatus('正在解密和读取日志…'); + loadLog(name).then((list) => { + setBattles(list); + // The longest battle that has bots in its trace; a battle left right after loading has none. + let pick = list.length - 1; + let best = 0; + list.forEach((b, i) => { + const withBots = b.frames.filter((f) => f.bots.size > 0).length; + if (withBots > best) { best = withBots; pick = i; } + }); + setBattleIdx(Math.max(0, pick)); + setStatus(list.length === 0 ? '这份日志里没有对局。' : ''); + }).catch((e: unknown) => setStatus(String(e))); + }; + + const battle = battles[battleIdx]; + const level = battle?.level; + useEffect(() => { + setT(battle?.startT ?? 0); + setSelected(undefined); + }, [battle]); + useEffect(() => { + const entry = maps.find((m) => m.level === level); + setMapData(undefined); + if (entry === undefined) return; + loadMap(entry).then(setMapData).catch((e: unknown) => setStatus(String(e))); + }, [level, maps]); + + const mapLayer = useMemo( + () => (mapData === undefined ? undefined : buildMapLayer(mapData.pack, { tier: 1, exposure, covers })), + [mapData, exposure, covers], + ); + const bounds = useMemo((): readonly [number, number, number, number] | undefined => { + if (mapData === undefined) return undefined; + const p = mapData.pois; + if (p !== undefined) return [p.boundsMin[0], p.boundsMin[1], p.boundsMax[0], p.boundsMax[1]]; + return [mapData.pack.header.bmin[0], mapData.pack.header.bmin[2], mapData.pack.header.bmax[0], mapData.pack.header.bmax[2]]; + }, [mapData]); + + useEffect(() => { + if (!playing || battle === undefined) return; + let last = performance.now(); + let handle = requestAnimationFrame(function step(now) { + const dt = (now - last) / 1000; + last = now; + setT((cur) => { + const next = cur + dt * speed; + if (next >= battle.endT) { setPlaying(false); return battle.endT; } + return next; + }); + handle = requestAnimationFrame(step); + }); + return () => cancelAnimationFrame(handle); + }, [playing, speed, battle]); + + const scene = useMemo(() => (battle === undefined ? undefined : sceneAt(battle, t)), [battle, t]); + + return ( +
+
+ + + {battles.length > 1 && ( + + )} + {(Object.keys(LAYER_LABELS) as (keyof Layers)[]).map((k) => ( + + ))} + + + {status !== '' && {status}} + {battle !== undefined && battle.frames.length === 0 && 这一局没有轨迹(游戏里没开 diagnostics.trace)。} +
+
+ + {battle !== undefined && } +
+ {battle !== undefined && ( + + )} +
+ ); +} diff --git a/apps/ai-lab/src/Inspector.tsx b/apps/ai-lab/src/Inspector.tsx new file mode 100644 index 0000000..a0d6c88 --- /dev/null +++ b/apps/ai-lab/src/Inspector.tsx @@ -0,0 +1,94 @@ +/** Details of the selected vehicle at the current time, its recent log events, and the legends. */ +import type { TraceBattle, TraceEvent } from '@wto/ground-sim'; +import { eventsBetween, type SceneAt } from './frames.ts'; +import { + BEHAVIOR_COLORS, BEHAVIOR_ZH, CLASS_ZH, COMMAND_ZH, DENY_COLORS, DENY_ZH, LANE_ZH, LOOK_COLORS, LOOK_ZH, + STATE_ZH, URGENCY_ZH, zh, +} from './labels.ts'; + +interface Props { + readonly battle: TraceBattle; + readonly scene: SceneAt | undefined; + readonly selected: string | undefined; +} + +const RECENT_SEC = 20; + +function angleDiff(a: number, b: number): number { + return Math.abs(((((a - b) % 360) + 540) % 360) - 180); +} + +function involves(e: TraceEvent, eid: string): boolean { + return e.eid === eid || e.fields['tgt'] === eid || e.fields['off'] === eid || e.fields['target'] === eid; +} + +function eventText(e: TraceEvent): string { + return Object.entries(e.fields) + .filter(([k]) => k !== 't' && k !== 'eid') + .map(([k, v]) => `${k}=${v}`) + .join(' '); +} + +function Legend({ names, colors }: { names: readonly string[]; colors: readonly string[] }): React.JSX.Element { + return ( +
+ {names.map((n, i) => ( + {n} + ))} +
+ ); +} + +function Row({ k, v }: { k: string; v: string }): React.JSX.Element { + return {k}{v}; +} + +export function Inspector({ battle, scene, selected }: Props): React.JSX.Element { + const u = selected !== undefined ? scene?.units.get(selected) : undefined; + const b = u?.bot; + const recent = selected !== undefined && scene !== undefined + ? eventsBetween(battle, scene.t - RECENT_SEC, scene.t).filter((e) => involves(e, selected)).reverse() + : []; + return ( + + ); +} diff --git a/apps/ai-lab/src/MapView.tsx b/apps/ai-lab/src/MapView.tsx new file mode 100644 index 0000000..14e3b67 --- /dev/null +++ b/apps/ai-lab/src/MapView.tsx @@ -0,0 +1,87 @@ +/** The battle map: drag to pan, wheel to zoom, click a vehicle to select it. */ +import type { TraceBattle } from '@wto/ground-sim'; +import { useEffect, useRef, useState } from 'react'; +import { drawScene, type Layers } from './draw.ts'; +import type { SceneAt } from './frames.ts'; +import type { MapLayer } from './mapLayer.ts'; +import { fitView, toScreen, zoomAt, type View } from './view.ts'; + +interface Props { + readonly map: MapLayer | undefined; + readonly bounds: readonly [number, number, number, number] | undefined; + readonly battle: TraceBattle | undefined; + readonly scene: SceneAt | undefined; + readonly selected: string | undefined; + readonly layers: Layers; + readonly onSelect: (eid: string | undefined) => void; +} + +const PICK_PX = 14; + +export function MapView({ map, bounds, battle, scene, selected, layers, onSelect }: Props): React.JSX.Element { + const canvasRef = useRef(null); + const [view, setView] = useState({ cx: 0, cz: 0, scale: 1, w: 800, h: 600 }); + const drag = useRef<{ x: number; y: number; moved: boolean } | undefined>(undefined); + + useEffect(() => { + const canvas = canvasRef.current; + if (canvas === null) return; + const resize = (): void => { + const r = canvas.getBoundingClientRect(); + canvas.width = Math.max(1, Math.floor(r.width)); + canvas.height = Math.max(1, Math.floor(r.height)); + setView((v) => ({ ...v, w: canvas.width, h: canvas.height })); + }; + const obs = new ResizeObserver(resize); + obs.observe(canvas); + resize(); + return () => obs.disconnect(); + }, []); + + useEffect(() => { + if (bounds === undefined) return; + setView((v) => fitView(bounds[0], bounds[1], bounds[2], bounds[3], v.w, v.h)); + }, [bounds]); + + useEffect(() => { + const ctx = canvasRef.current?.getContext('2d'); + if (ctx === undefined || ctx === null) return; + drawScene(ctx, view, map, battle, scene, selected, layers); + }, [view, map, battle, scene, selected, layers]); + + const pick = (sx: number, sy: number): string | undefined => { + let best: string | undefined; + let bestD = PICK_PX * PICK_PX; + for (const u of scene?.units.values() ?? []) { + const [x, y] = toScreen(view, u.x, u.z); + const d = (x - sx) ** 2 + (y - sy) ** 2; + if (d < bestD) { bestD = d; best = u.unit.eid; } + } + return best; + }; + + return ( + setView((v) => zoomAt(v, e.nativeEvent.offsetX, e.nativeEvent.offsetY, e.deltaY < 0 ? 1.2 : 1 / 1.2))} + onMouseDown={(e) => { drag.current = { x: e.clientX, y: e.clientY, moved: false }; }} + onMouseMove={(e) => { + const d = drag.current; + if (d === undefined) return; + const dx = e.clientX - d.x; + const dy = e.clientY - d.y; + if (Math.abs(dx) + Math.abs(dy) > 2) d.moved = true; + d.x = e.clientX; + d.y = e.clientY; + setView((v) => ({ ...v, cx: v.cx - dx / v.scale, cz: v.cz + dy / v.scale })); + }} + onMouseUp={(e) => { + const d = drag.current; + drag.current = undefined; + if (d !== undefined && !d.moved) onSelect(pick(e.nativeEvent.offsetX, e.nativeEvent.offsetY)); + }} + onMouseLeave={() => { drag.current = undefined; }} + /> + ); +} diff --git a/apps/ai-lab/src/Timeline.tsx b/apps/ai-lab/src/Timeline.tsx new file mode 100644 index 0000000..ad19e4a --- /dev/null +++ b/apps/ai-lab/src/Timeline.tsx @@ -0,0 +1,86 @@ +/** + * Playback controls and, for the selected bot, three strips over the whole battle: its behavior, + * the reason it did not fire, and why its turret pointed where it did. Click a strip to seek. + */ +import type { TraceBattle } from '@wto/ground-sim'; +import { useEffect, useRef } from 'react'; +import { BEHAVIOR_COLORS, DENY_COLORS, LOOK_COLORS } from './labels.ts'; + +interface Props { + readonly battle: TraceBattle; + readonly t: number; + readonly playing: boolean; + readonly speed: number; + readonly selected: string | undefined; + readonly onSeek: (t: number) => void; + readonly onPlaying: (playing: boolean) => void; + readonly onSpeed: (speed: number) => void; +} + +const SPEEDS = [0.5, 1, 2, 4, 8, 16]; +const STRIP_H = 10; + +function drawStrips(canvas: HTMLCanvasElement, battle: TraceBattle, eid: string | undefined, t: number): void { + const ctx = canvas.getContext('2d'); + if (ctx === null) return; + const w = canvas.width; + const span = Math.max(1, battle.endT - battle.startT); + ctx.fillStyle = '#16181a'; + ctx.fillRect(0, 0, w, canvas.height); + if (eid !== undefined) { + const frames = battle.frames; + for (let i = 0; i < frames.length; i++) { + const f = frames[i]; + const bot = f?.bots.get(eid); + if (f === undefined || bot === undefined) continue; + const x0 = ((f.t - battle.startT) / span) * w; + const x1 = (((frames[i + 1]?.t ?? f.t + 0.5) - battle.startT) / span) * w; + const bw = Math.max(1, x1 - x0); + ctx.fillStyle = BEHAVIOR_COLORS[bot.behavior] ?? '#444'; + ctx.fillRect(x0, 0, bw, STRIP_H); + ctx.fillStyle = DENY_COLORS[bot.deny] ?? '#444'; + ctx.fillRect(x0, STRIP_H + 2, bw, STRIP_H); + ctx.fillStyle = LOOK_COLORS[bot.lookReason] ?? '#444'; + ctx.fillRect(x0, 2 * (STRIP_H + 2), bw, STRIP_H); + } + } + const cx = ((t - battle.startT) / span) * w; + ctx.fillStyle = '#fff'; + ctx.fillRect(cx - 1, 0, 2, canvas.height); +} + +export function Timeline({ battle, t, playing, speed, selected, onSeek, onPlaying, onSpeed }: Props): React.JSX.Element { + const stripRef = useRef(null); + useEffect(() => { + const c = stripRef.current; + if (c === null) return; + c.width = Math.max(1, Math.floor(c.getBoundingClientRect().width)); + drawStrips(c, battle, selected, t); + }, [battle, selected, t]); + + return ( +
+
+ + + {t.toFixed(1)} s / {battle.endT.toFixed(0)} s + onSeek(Number(e.target.value))} + /> +
+
行为拒绝开火炮塔依据
+ { + const w = e.currentTarget.width; + onSeek(battle.startT + (e.nativeEvent.offsetX / w) * (battle.endT - battle.startT)); + }} + /> +
+ ); +} diff --git a/apps/ai-lab/src/data.ts b/apps/ai-lab/src/data.ts new file mode 100644 index 0000000..7bd8a73 --- /dev/null +++ b/apps/ai-lab/src/data.ts @@ -0,0 +1,48 @@ +/** Loading maps and logs through the lab's dev-server API (server/lab-api.ts). */ +import { parsePois, parseTraceLog, readNavPack, type MapPois, type NavPack, type TraceBattle } from '@wto/ground-sim'; + +export interface LogEntry { + readonly name: string; + readonly size: number; + readonly mtime: number; +} + +export interface MapEntry { + readonly level: string; + readonly pois: boolean; +} + +export interface MapData { + readonly pack: NavPack; + readonly pois: MapPois | undefined; +} + +async function get(url: string): Promise { + const res = await fetch(url); + if (!res.ok) { + const body = await res.text(); + throw new Error(`${url}: ${res.status} ${body}`); + } + return res; +} + +export async function fetchMaps(): Promise { + return (await (await get('/api/maps')).json()) as MapEntry[]; +} + +export async function fetchLogs(): Promise { + return (await (await get('/api/logs')).json()) as LogEntry[]; +} + +export async function loadLog(name: string): Promise { + const text = await (await get(`/api/logs/text?name=${encodeURIComponent(name)}`)).text(); + return parseTraceLog(text); +} + +export async function loadMap(entry: MapEntry): Promise { + const bytes = new Uint8Array(await (await get(`/api/maps/file?name=${encodeURIComponent(`${entry.level}.wtonav`)}`)).arrayBuffer()); + const pois = entry.pois + ? parsePois(await (await get(`/api/maps/file?name=${encodeURIComponent(`${entry.level}.pois.json`)}`)).text()) + : undefined; + return { pack: readNavPack(bytes), pois }; +} diff --git a/apps/ai-lab/src/draw.ts b/apps/ai-lab/src/draw.ts new file mode 100644 index 0000000..e1313e4 --- /dev/null +++ b/apps/ai-lab/src/draw.ts @@ -0,0 +1,168 @@ +/** Everything drawn over the static map for one moment of the replay. */ +import { BEHAVIOR_NAMES, type TraceBattle } from '@wto/ground-sim'; +import { eventsBetween, type SceneAt, type UnitAt } from './frames.ts'; +import type { MapLayer } from './mapLayer.ts'; +import { screenDir, toScreen, type View } from './view.ts'; + +export interface Layers { + readonly goals: boolean; + readonly links: boolean; + readonly cones: boolean; + readonly labels: boolean; + readonly events: boolean; +} + +export const ARMY_COLORS: Readonly> = { 1: '#4aa3ff', 2: '#ff5c5c' }; + +const GUN_FOV_HALF_DEG = 30; +const CONE_M = 120; +const EVENT_WINDOW_SEC = 2; + +function line(ctx: CanvasRenderingContext2D, ax: number, ay: number, bx: number, by: number): void { + ctx.beginPath(); + ctx.moveTo(ax, ay); + ctx.lineTo(bx, by); + ctx.stroke(); +} + +function drawHull(ctx: CanvasRenderingContext2D, v: View, u: UnitAt, selected: boolean): void { + const [sx, sy] = toScreen(v, u.x, u.z); + const [dx, dy] = screenDir(u.yaw); + const len = Math.max(5, (u.unit.light ? 3 : 3.6) * v.scale); + const wid = Math.max(3, 1.7 * v.scale); + ctx.save(); + ctx.translate(sx, sy); + ctx.rotate(Math.atan2(dy, dx)); + ctx.fillStyle = u.unit.alive ? (ARMY_COLORS[u.unit.army] ?? '#ccc') : '#555'; + ctx.fillRect(-len, -wid, len * 2, wid * 2); + ctx.fillStyle = '#fff'; + ctx.fillRect(len * 0.6, -wid * 0.5, len * 0.4, wid); + if (u.unit.human || selected) { + ctx.strokeStyle = selected ? '#ffe14a' : '#fff'; + ctx.lineWidth = selected ? 3 : 1.5; + ctx.strokeRect(-len - 2, -wid - 2, len * 2 + 4, wid * 2 + 4); + } + ctx.restore(); +} + +function drawBotIntent(ctx: CanvasRenderingContext2D, v: View, u: UnitAt, scene: SceneAt, layers: Layers): void { + const bot = u.bot; + if (bot === undefined || !u.unit.alive) return; + const [sx, sy] = toScreen(v, u.x, u.z); + if (layers.goals && bot.hasOrder) { + const [gx, gy] = toScreen(v, bot.goalX, bot.goalZ); + ctx.setLineDash([4, 6]); + ctx.strokeStyle = 'rgba(255,255,255,0.25)'; + ctx.lineWidth = 1; + line(ctx, sx, sy, gx, gy); + ctx.setLineDash([]); + } + if (bot.gunYaw !== undefined) { + const [dx, dy] = screenDir(bot.gunYaw); + if (layers.cones) { + const r = CONE_M * v.scale; + const a = Math.atan2(dy, dx); + const half = (GUN_FOV_HALF_DEG * Math.PI) / 180; + ctx.fillStyle = 'rgba(255,255,200,0.07)'; + ctx.beginPath(); + ctx.moveTo(sx, sy); + ctx.arc(sx, sy, r, a - half, a + half); + ctx.closePath(); + ctx.fill(); + } + const gl = Math.max(14, 8 * v.scale); + ctx.strokeStyle = '#fff'; + ctx.lineWidth = 2; + line(ctx, sx, sy, sx + dx * gl, sy + dy * gl); + } + const [wx, wy] = screenDir(bot.wishYaw); + const wl = Math.max(22, 14 * v.scale); + ctx.setLineDash([2, 3]); + ctx.strokeStyle = 'rgba(255,225,74,0.8)'; + ctx.lineWidth = 1; + line(ctx, sx, sy, sx + wx * wl, sy + wy * wl); + ctx.setLineDash([]); + if (!layers.links) return; + const target = scene.units.get(bot.target); + if (target !== undefined && bot.target !== '0') { + const [tx, ty] = toScreen(v, target.x, target.z); + ctx.strokeStyle = bot.targetInSight ? 'rgba(255,70,70,0.85)' : 'rgba(255,70,70,0.3)'; + ctx.lineWidth = 1.5; + line(ctx, sx, sy, tx, ty); + } + const look = scene.units.get(bot.lookAt); + if (look !== undefined && bot.lookAt !== bot.target) { + const [lx, ly] = toScreen(v, look.x, look.z); + ctx.strokeStyle = 'rgba(255,160,40,0.85)'; + ctx.lineWidth = 1.5; + line(ctx, sx, sy, lx, ly); + } +} + +function drawLabel(ctx: CanvasRenderingContext2D, v: View, u: UnitAt): void { + const [sx, sy] = toScreen(v, u.x, u.z); + const name = u.bot !== undefined ? (BEHAVIOR_NAMES[u.bot.behavior] ?? '?') : u.unit.human ? 'player' : ''; + ctx.fillStyle = 'rgba(255,255,255,0.85)'; + ctx.font = '11px sans-serif'; + ctx.fillText(`${u.unit.eid.replace(/^0x/, '')} ${name}`, sx + 8, sy - 8); +} + +function drawEvents(ctx: CanvasRenderingContext2D, v: View, battle: TraceBattle, scene: SceneAt): void { + for (const e of eventsBetween(battle, scene.t - EVENT_WINDOW_SEC, scene.t)) { + const fade = 1 - (scene.t - e.t) / EVENT_WINDOW_SEC; + if (e.kind === 'SHOT' && e.eid !== undefined) { + const from = scene.units.get(e.eid); + const to = scene.units.get(e.fields['tgt'] ?? ''); + if (from === undefined || to === undefined) continue; + const [ax, ay] = toScreen(v, from.x, from.z); + const [bx, by] = toScreen(v, to.x, to.z); + ctx.strokeStyle = `rgba(255,255,120,${fade})`; + ctx.lineWidth = 2; + line(ctx, ax, ay, bx, by); + } else if (e.kind === 'HIT') { + const [hx, hy] = toScreen(v, Number(e.fields['x']), Number(e.fields['z'])); + ctx.fillStyle = e.fields['drop'] === '1' ? `rgba(255,60,60,${fade})` : `rgba(200,200,200,${fade})`; + ctx.beginPath(); + ctx.arc(hx, hy, 4, 0, Math.PI * 2); + ctx.fill(); + } + } +} + +function drawDeaths(ctx: CanvasRenderingContext2D, v: View, battle: TraceBattle, t: number): void { + ctx.lineWidth = 2; + for (const e of eventsBetween(battle, battle.startT, t)) { + if (e.kind !== 'DEATH') continue; + const [x, y] = toScreen(v, Number(e.fields['x']), Number(e.fields['z'])); + ctx.strokeStyle = e.fields['army'] === '1' ? 'rgba(74,163,255,0.6)' : 'rgba(255,92,92,0.6)'; + line(ctx, x - 5, y - 5, x + 5, y + 5); + line(ctx, x - 5, y + 5, x + 5, y - 5); + } +} + +export function drawScene(ctx: CanvasRenderingContext2D, v: View, map: MapLayer | undefined, battle: TraceBattle | undefined, + scene: SceneAt | undefined, selected: string | undefined, layers: Layers): void { + ctx.fillStyle = '#0b0c0d'; + ctx.fillRect(0, 0, v.w, v.h); + if (map !== undefined) { + const [mx, my] = toScreen(v, map.x0, map.z1); + const k = v.scale / map.pxPerM; + ctx.imageSmoothingEnabled = k < 1; + ctx.drawImage(map.canvas, mx, my, map.canvas.width * k, map.canvas.height * k); + } + if (battle === undefined || scene === undefined) return; + for (const cap of scene.caps) { + const [cx, cy] = toScreen(v, cap.x, cap.z); + ctx.strokeStyle = ARMY_COLORS[cap.owner] ?? '#ddd'; + ctx.lineWidth = 2; + ctx.beginPath(); + ctx.arc(cx, cy, Math.max(4, cap.r * v.scale), 0, Math.PI * 2); + ctx.stroke(); + } + drawDeaths(ctx, v, battle, scene.t); + const units = [...scene.units.values()]; + for (const u of units) drawBotIntent(ctx, v, u, scene, layers); + if (layers.events) drawEvents(ctx, v, battle, scene); + for (const u of units) drawHull(ctx, v, u, u.unit.eid === selected); + if (layers.labels) for (const u of units) if (u.unit.alive) drawLabel(ctx, v, u); +} diff --git a/apps/ai-lab/src/frames.ts b/apps/ai-lab/src/frames.ts new file mode 100644 index 0000000..ce5f04f --- /dev/null +++ b/apps/ai-lab/src/frames.ts @@ -0,0 +1,73 @@ +/** Looking up the battle state at any time between two trace samples. */ +import type { BotSample, CapSample, TraceBattle, TraceEvent, UnitSample } from '@wto/ground-sim'; + +export interface UnitAt { + readonly unit: UnitSample; + /** Interpolated position and heading. */ + readonly x: number; + readonly z: number; + readonly yaw: number; + /** Decision state of the sample at or before the time; undefined for players. */ + readonly bot: BotSample | undefined; +} + +export interface SceneAt { + readonly t: number; + readonly units: Map; + readonly caps: CapSample[]; +} + +/** Index of the last frame at or before `t` (-1 before the first). */ +export function frameIndexAt(battle: TraceBattle, t: number): number { + let lo = 0; + let hi = battle.frames.length - 1; + let found = -1; + while (lo <= hi) { + const mid = (lo + hi) >> 1; + if ((battle.frames[mid]?.t ?? Infinity) <= t) { found = mid; lo = mid + 1; } else hi = mid - 1; + } + return found; +} + +function lerpYaw(a: number, b: number, k: number): number { + const d = ((((b - a) % 360) + 540) % 360) - 180; + return a + d * k; +} + +export function sceneAt(battle: TraceBattle, t: number): SceneAt { + const i = Math.max(0, frameIndexAt(battle, t)); + const a = battle.frames[i]; + const b = battle.frames[i + 1]; + const units = new Map(); + if (a === undefined) return { t, units, caps: [] }; + const k = b !== undefined && b.t > a.t ? Math.min(1, Math.max(0, (t - a.t) / (b.t - a.t))) : 0; + for (const [eid, ua] of a.units) { + const ub = b?.units.get(eid); + const move = ub !== undefined && ua.alive && ub.alive ? k : 0; + units.set(eid, { + unit: ua, + x: ua.x + ((ub?.x ?? ua.x) - ua.x) * move, + z: ua.z + ((ub?.z ?? ua.z) - ua.z) * move, + yaw: lerpYaw(ua.yaw, ub?.yaw ?? ua.yaw, move), + bot: a.bots.get(eid), + }); + } + return { t, units, caps: a.caps }; +} + +/** Events with time in [from, to], from the sorted event list. */ +export function eventsBetween(battle: TraceBattle, from: number, to: number): TraceEvent[] { + let lo = 0; + let hi = battle.events.length; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if ((battle.events[mid]?.t ?? Infinity) < from) lo = mid + 1; else hi = mid; + } + const out: TraceEvent[] = []; + for (let i = lo; i < battle.events.length; i++) { + const e = battle.events[i]; + if (e === undefined || e.t > to) break; + out.push(e); + } + return out; +} diff --git a/apps/ai-lab/src/labels.ts b/apps/ai-lab/src/labels.ts new file mode 100644 index 0000000..b3fde12 --- /dev/null +++ b/apps/ai-lab/src/labels.ts @@ -0,0 +1,37 @@ +/** Chinese display names for the trace codes (the codes themselves are in @wto/ground-sim). */ + +export const BEHAVIOR_ZH = ['推进', '交战推进', '短停', '回掩体', '换位', '守位', '疏散', '撤回', '维修'] as const; + +export const BEHAVIOR_COLORS = ['#6c8ebf', '#e0884a', '#e5d34a', '#8fbf6c', '#b07cc6', '#5fb8b0', '#9a9a9a', '#c65f5f', '#7a5a3a'] as const; + +export const STATE_ZH: Readonly> = { + 0: '行军', 1: '行进交战', 3: '短停', 4: '退入掩体', 5: '掩体装填', 7: '原地守位', 8: '换位', + 9: '失能', 10: '疏散', 11: '坡脊撤回', +}; + +export const DENY_ZH = [ + '放行', '无目标', '炮未就绪', '命中概率不足', '远距窗口不足', '瞄准误差', '等待炮管稳定', '检查预算', + '炮口有硬物', '弹道有硬物', '友军', '多炮检查', '射界外', '点射间歇', +] as const; + +export const DENY_COLORS = [ + '#4caf50', '#333', '#666', '#e53935', '#8e24aa', '#fb8c00', '#fdd835', '#90a4ae', + '#6d4c41', '#795548', '#03a9f4', '#9e9e9e', '#d81b60', '#26a69a', +] as const; + +export const LOOK_ZH = ['—', '交战目标', '威胁', '目标消失处', '记忆位置', '线索', '扫视'] as const; + +export const LOOK_COLORS = ['#333', '#e53935', '#fb8c00', '#fdd835', '#8e24aa', '#03a9f4', '#607d8b'] as const; + +export const COMMAND_ZH = ['主攻', '侧翼', '架枪', '防守', '预备', '防空'] as const; + +export const URGENCY_ZH = ['低', '中', '高'] as const; + +export const LANE_ZH = ['中路', '左翼', '右翼'] as const; + +export const CLASS_ZH = ['中坦', '轻坦', '重坦', '歼击车', '防空'] as const; + +export function zh(names: readonly string[] | Readonly>, code: number): string { + const name = Array.isArray(names) ? names[code] : (names as Readonly>)[code]; + return name ?? String(code); +} diff --git a/apps/ai-lab/src/main.tsx b/apps/ai-lab/src/main.tsx new file mode 100644 index 0000000..90c7cf0 --- /dev/null +++ b/apps/ai-lab/src/main.tsx @@ -0,0 +1,7 @@ +import { StrictMode } from 'react'; +import { createRoot } from 'react-dom/client'; +import { App } from './App.tsx'; +import './style.css'; + +const root = document.getElementById('root'); +if (root !== null) createRoot(root).render(); diff --git a/apps/ai-lab/src/mapLayer.ts b/apps/ai-lab/src/mapLayer.ts new file mode 100644 index 0000000..de2a125 --- /dev/null +++ b/apps/ai-lab/src/mapLayer.ts @@ -0,0 +1,88 @@ +/** + * The static map drawn once into an offscreen canvas: walkable polygons of one mesh tier coloured + * by surface, optionally the tactical grid's exposure and the baked cover points. + */ +import { NAV_AREA_NAMES, type NavPack } from '@wto/ground-sim'; + +export interface MapLayer { + readonly canvas: HTMLCanvasElement; + /** World x of the canvas's left edge and world z of its top edge. */ + readonly x0: number; + readonly z1: number; + readonly pxPerM: number; +} + +export interface MapLayerOptions { + readonly tier: number; + readonly exposure: boolean; + readonly covers: boolean; +} + +const AREA_COLORS: Readonly> = { + road: '#77786a', bridge: '#a0a090', ground: '#3d4a33', rough: '#5a4d34', forest: '#29402a', + crushable: '#4f5f35', shallowWater: '#35607a', chokepoint: '#7a6a35', exposed: '#5f5f33', + deepWater: '#1d3a66', noGo: '#3a2626', +}; + +export function buildMapLayer(pack: NavPack, opts: MapLayerOptions): MapLayer { + const [x0, , z0] = pack.header.bmin; + const [x1, , z1] = pack.header.bmax; + const pxPerM = Math.min(2, 4096 / Math.max(x1 - x0, z1 - z0)); + const canvas = document.createElement('canvas'); + canvas.width = Math.ceil((x1 - x0) * pxPerM); + canvas.height = Math.ceil((z1 - z0) * pxPerM); + const ctx = canvas.getContext('2d'); + if (ctx === null) return { canvas, x0, z1, pxPerM }; + ctx.fillStyle = '#121416'; + ctx.fillRect(0, 0, canvas.width, canvas.height); + const tier = pack.tiers[opts.tier] ?? pack.tiers[1]; + if (tier !== undefined) { + for (let area = 1; area < NAV_AREA_NAMES.length; area++) { + ctx.beginPath(); + for (let i = 0; i < tier.polyCount; i++) { + if (tier.areas[i] !== area) continue; + const ring = tier.rings[i]; + if (ring === undefined) continue; + for (let k = 0; k < ring.length; k += 2) { + const px = ((ring[k] ?? 0) - x0) * pxPerM; + const py = (z1 - (ring[k + 1] ?? 0)) * pxPerM; + if (k === 0) ctx.moveTo(px, py); + else ctx.lineTo(px, py); + } + ctx.closePath(); + } + ctx.fillStyle = AREA_COLORS[NAV_AREA_NAMES[area] ?? ''] ?? '#444'; + ctx.fill(); + } + } + if (opts.exposure) drawExposure(ctx, pack, x0, z1, pxPerM); + if (opts.covers) drawCovers(ctx, pack, x0, z1, pxPerM); + return { canvas, x0, z1, pxPerM }; +} + +function drawExposure(ctx: CanvasRenderingContext2D, pack: NavPack, x0: number, z1: number, pxPerM: number): void { + const g = pack.tactical; + const cell = g.cellM * pxPerM; + for (let r = 0; r < g.rows; r++) { + for (let c = 0; c < g.cols; c++) { + const e = g.exposure[r * g.cols + c] ?? 0; + if (e < 16) continue; + ctx.fillStyle = `rgba(255, 80, 40, ${(e / 255) * 0.45})`; + const wx = g.origin[0] + c * g.cellM; + const wz = g.origin[1] + r * g.cellM; + ctx.fillRect((wx - x0) * pxPerM, (z1 - wz - g.cellM) * pxPerM, cell, cell); + } + } +} + +function drawCovers(ctx: CanvasRenderingContext2D, pack: NavPack, x0: number, z1: number, pxPerM: number): void { + for (const cv of pack.covers) { + const px = (cv.pos[0] - x0) * pxPerM; + const py = (z1 - cv.pos[2]) * pxPerM; + ctx.strokeStyle = cv.kind === 1 ? 'rgba(120, 220, 255, 0.8)' : 'rgba(255, 230, 120, 0.8)'; + ctx.beginPath(); + ctx.moveTo(px, py); + ctx.lineTo(px + cv.coverDir[0] * 6 * pxPerM, py - cv.coverDir[1] * 6 * pxPerM); + ctx.stroke(); + } +} diff --git a/apps/ai-lab/src/style.css b/apps/ai-lab/src/style.css new file mode 100644 index 0000000..7e1c828 --- /dev/null +++ b/apps/ai-lab/src/style.css @@ -0,0 +1,26 @@ +* { box-sizing: border-box; } +html, body, #root { margin: 0; height: 100%; background: #0b0c0d; color: #ddd; font: 13px/1.4 system-ui, 'Microsoft YaHei', sans-serif; } +.app { display: flex; flex-direction: column; height: 100%; } +header { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; padding: 6px 10px; background: #16181a; border-bottom: 1px solid #2a2d30; } +header select { max-width: 420px; } +header label { display: inline-flex; align-items: center; gap: 3px; } +.status { color: #ffb74d; } +main { flex: 1; display: flex; min-height: 0; } +canvas.map { flex: 1; min-width: 0; height: 100%; cursor: grab; display: block; } +.inspector { width: 360px; overflow-y: auto; padding: 8px 10px; background: #121416; border-left: 1px solid #2a2d30; } +.inspector table { width: 100%; border-collapse: collapse; } +.inspector th { text-align: left; color: #999; font-weight: normal; padding: 2px 8px 2px 0; white-space: nowrap; vertical-align: top; } +.inspector td { padding: 2px 0; } +.inspector h4 { margin: 12px 0 4px; color: #aaa; font-weight: normal; } +.hint { color: #999; } +.events { font-size: 12px; } +.events div { padding: 1px 0; border-bottom: 1px solid #1d2023; word-break: break-all; } +.events span { color: #999; } +.legend { display: flex; flex-wrap: wrap; gap: 4px 10px; font-size: 12px; } +.legend i { display: inline-block; width: 10px; height: 10px; margin-right: 3px; vertical-align: -1px; } +.timeline { padding: 6px 10px; background: #16181a; border-top: 1px solid #2a2d30; } +.controls { display: flex; gap: 8px; align-items: center; } +.controls input[type='range'] { flex: 1; } +.time { min-width: 120px; font-variant-numeric: tabular-nums; } +.strip-labels { display: flex; gap: 12px; font-size: 11px; color: #888; margin-top: 4px; } +canvas.strips { width: 100%; height: 36px; display: block; cursor: pointer; } diff --git a/apps/ai-lab/src/view.ts b/apps/ai-lab/src/view.ts new file mode 100644 index 0000000..6bfe133 --- /dev/null +++ b/apps/ai-lab/src/view.ts @@ -0,0 +1,39 @@ +/** + * Top-down view of the battle: world x to the right, world z up (Dagor is Y-up). Headings are + * degrees of atan2(z, x), as the trace writes them. + */ +export interface View { + /** World point at the centre of the canvas. */ + readonly cx: number; + readonly cz: number; + /** Screen pixels per world metre. */ + readonly scale: number; + readonly w: number; + readonly h: number; +} + +export function toScreen(v: View, x: number, z: number): [number, number] { + return [v.w / 2 + (x - v.cx) * v.scale, v.h / 2 - (z - v.cz) * v.scale]; +} + +export function toWorld(v: View, sx: number, sy: number): [number, number] { + return [v.cx + (sx - v.w / 2) / v.scale, v.cz - (sy - v.h / 2) / v.scale]; +} + +/** Screen direction (unit vector) of a world heading. */ +export function screenDir(yawDeg: number): [number, number] { + const r = (yawDeg * Math.PI) / 180; + return [Math.cos(r), -Math.sin(r)]; +} + +export function fitView(minX: number, minZ: number, maxX: number, maxZ: number, w: number, h: number): View { + const scale = Math.min(w / Math.max(1, maxX - minX), h / Math.max(1, maxZ - minZ)) * 0.95; + return { cx: (minX + maxX) / 2, cz: (minZ + maxZ) / 2, scale, w, h }; +} + +/** Zoom by `factor` keeping the world point under the screen point (sx, sy) in place. */ +export function zoomAt(v: View, sx: number, sy: number, factor: number): View { + const [wx, wz] = toWorld(v, sx, sy); + const scale = Math.min(40, Math.max(0.05, v.scale * factor)); + return { ...v, scale, cx: wx - (sx - v.w / 2) / scale, cz: wz + (sy - v.h / 2) / scale }; +} diff --git a/apps/ai-lab/tsconfig.json b/apps/ai-lab/tsconfig.json new file mode 100644 index 0000000..1cb6c15 --- /dev/null +++ b/apps/ai-lab/tsconfig.json @@ -0,0 +1,23 @@ +{ + // The lab is a Vite page plus its dev-server API (server/), so it has its own settings and stays + // out of the root typecheck, like the launcher. + "compilerOptions": { + "target": "ES2023", + "module": "ESNext", + "moduleResolution": "bundler", + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "types": ["node"], + "jsx": "react-jsx", + "strict": true, + "noUncheckedIndexedAccess": true, + "noImplicitOverride": true, + "exactOptionalPropertyTypes": true, + "verbatimModuleSyntax": true, + "allowImportingTsExtensions": true, + "noEmit": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "useDefineForClassFields": true + }, + "include": ["src/**/*.ts", "src/**/*.tsx", "server/**/*.ts", "vite.config.ts"] +} diff --git a/apps/ai-lab/vite.config.ts b/apps/ai-lab/vite.config.ts new file mode 100644 index 0000000..9df6a8a --- /dev/null +++ b/apps/ai-lab/vite.config.ts @@ -0,0 +1,8 @@ +import react from '@vitejs/plugin-react'; +import { defineConfig } from 'vite'; +import { labApi } from './server/lab-api.ts'; + +export default defineConfig({ + plugins: [react(), labApi()], + server: { host: '127.0.0.1', port: 47180, strictPort: false }, +}); diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index be4ecb9..5ae089d 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -881,7 +881,9 @@ "statsLogIntervalSec": "Battle statistics logging interval", "statsSampleSec": "Statistics sampling interval per bot", "statsSampleRangeM": "Range of the nearest-enemy statistics sample", - "statsRearArcDeg": "Rear arc counted as showing the rear" + "statsRearArcDeg": "Rear arc counted as showing the rear", + "trace": "Log the AI replay trace", + "traceIntervalSec": "AI replay trace sampling interval" } }, "shared": "These settings apply to all saves in this client.", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index 612b6cb..c434dfb 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -881,7 +881,9 @@ "statsLogIntervalSec": "每局统计的输出间隔", "statsSampleSec": "每辆车的统计抽查间隔", "statsSampleRangeM": "统计抽查最近敌人的范围", - "statsRearArcDeg": "算作车尾对敌的后方扇区角度" + "statsRearArcDeg": "算作车尾对敌的后方扇区角度", + "trace": "输出 AI 回放轨迹", + "traceIntervalSec": "回放轨迹的采样间隔" } }, "shared": "这些数值适用于此客户端的全部存档。", diff --git a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts index 5ed854e..f66dd1d 100644 --- a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts +++ b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts @@ -466,6 +466,8 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [ num('diagnostics', 'statsSampleSec', 0.2, 5, 's'), num('diagnostics', 'statsSampleRangeM', 50, 1000, 'm'), num('diagnostics', 'statsRearArcDeg', 30, 180, '°'), + { id: 'groundAi.diagnostics.trace', section: 'diagnostics', field: 'trace', kind: 'bool' }, + num('diagnostics', 'traceIntervalSec', 0.1, 5, 's'), ], }, ]; diff --git a/apps/launcher/src/shared/schemas/tuning.ts b/apps/launcher/src/shared/schemas/tuning.ts index 402b07f..d19d88f 100644 --- a/apps/launcher/src/shared/schemas/tuning.ts +++ b/apps/launcher/src/shared/schemas/tuning.ts @@ -329,6 +329,8 @@ const GroundAiDiagnosticsSchema = z.object({ statsSampleSec: z.number().min(0.2).max(5), statsSampleRangeM: z.number().min(50).max(1000), statsRearArcDeg: z.number().min(30).max(180), + trace: z.boolean(), + traceIntervalSec: z.number().min(0.1).max(5), }); export const GroundAiTuningSchema = z.object({ diff --git a/apps/server/src/tuning/ground-ai-tuning.ts b/apps/server/src/tuning/ground-ai-tuning.ts index 2da0bca..6871479 100644 --- a/apps/server/src/tuning/ground-ai-tuning.ts +++ b/apps/server/src/tuning/ground-ai-tuning.ts @@ -69,6 +69,8 @@ export function readGroundAiTuning(reader: TuningReader): GroundAiTuning { statsSampleSec: diag.number('statsSampleSec', { min: 0.2, max: 5 }), statsSampleRangeM: diag.number('statsSampleRangeM', { min: 50, max: 1000 }), statsRearArcDeg: diag.number('statsRearArcDeg', { min: 30, max: 180 }), + trace: diag.bool('trace'), + traceIntervalSec: diag.number('traceIntervalSec', { min: 0.1, max: 5 }), }, }; } diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index c7f96cf..7240d18 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -458,6 +458,11 @@ "statsLogIntervalSec": 60.0, "statsSampleSec": 1.0, "statsSampleRangeM": 300.0, - "statsRearArcDeg": 120.0 + "statsRearArcDeg": 120.0, + // Replay trace for the AI viewer (WTO_AI|TRACE_*, HIT, DEATH): every traceIntervalSec the + // capture zones, every ground unit and every bot's decision state. About 10 MB of log for + // 32 bots over 15 minutes at 0.5 s. + "trace": true, + "traceIntervalSec": 0.5 } } diff --git a/game-ai/ground/wto_ai_combat_types_common.das b/game-ai/ground/wto_ai_combat_types_common.das index f2cbd77..9174bb9 100644 --- a/game-ai/ground/wto_ai_combat_types_common.das +++ b/game-ai/ground/wto_ai_combat_types_common.das @@ -112,12 +112,23 @@ struct public WtoThreatTable topIdx : int = -1 topVisibleIdx : int = -1 +// Why the turret points where it does this frame (WtoTurretState.lookReason, replay trace). +let public WTO_LOOK_NONE = 0 +let public WTO_LOOK_ENGAGE = 1 +let public WTO_LOOK_THREAT = 2 +let public WTO_LOOK_WATCH = 3 +let public WTO_LOOK_MEMORY = 4 +let public WTO_LOOK_CUE = 5 +let public WTO_LOOK_SCAN = 6 + // Turret channel (decision layer design, section 5): the threat it is looking at and until when -// that look is held. +// that look is held, plus the world direction it was asked for this frame and why. [safe_when_uninitialized] struct public WtoTurretState lookEid : EntityId = INVALID_ENTITY_ID holdUntil : float = -100.0 + lookReason : int = 0 + wishDir : float3 = float3(1.0, 0.0, 0.0) [safe_when_uninitialized] struct public WtoWeaponBurst diff --git a/game-ai/ground/wto_ai_fire_common.das b/game-ai/ground/wto_ai_fire_common.das index 4bcf52b..1213d5d 100644 --- a/game-ai/ground/wto_ai_fire_common.das +++ b/game-ai/ground/wto_ai_fire_common.das @@ -272,8 +272,10 @@ def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; classN let aimBase = slot.perceive.visibleAimPt distToTgt = wto_solve_ballistic_aim(muzzlePos, unit.vel, aimBase, slot.fire.activeSpeedMps, slot.fire.activeDragCx, slot.fire.activeMassKg, slot.fire.activeCaliberM, slot, aimPt, wishWorldDir) auxAimed = wto_fire_aux_aim(unit, className, dt, distXZ, slot) + slot.turret.lookReason = WTO_LOOK_ENGAGE else wishWorldDir = wto_turret_look_dir(now, muzzlePos, unit.pos, hFwd, slot) + slot.turret.wishDir = wishWorldDir var wishYaw = 0.0 var wishPitch = 0.0 wto_world_to_hull_deg(wishWorldDir, hFwd, unit.unitTm[1], unit.unitTm[2], wishYaw, wishPitch) diff --git a/game-ai/ground/wto_ai_runtime.das b/game-ai/ground/wto_ai_runtime.das index a25c5f9..7fcefd5 100644 --- a/game-ai/ground/wto_ai_runtime.das +++ b/game-ai/ground/wto_ai_runtime.das @@ -43,6 +43,7 @@ require %appGame.wtoai.wto_ai_diag_common require %appGame.wtoai.wto_ai_stats_common require %appGame.wtoai.wto_ai_slots_common require %appGame.wtoai.wto_ai_threat_common +require %appGame.wtoai.wto_ai_trace_common var private @safe_when_uninitialized g_world : WtoWorldSnap var private @safe_when_uninitialized g_crowd : WtoCrowdSummary @@ -57,6 +58,8 @@ var private g_fire_budget : int = 0 var private g_next_diag_at : float = 0.0 var private @safe_when_uninitialized g_navmesh : WtoNavmeshBattle var private @safe_when_uninitialized g_stats : WtoBattleStats +var private g_next_trace_at : float = 0.0 +var private g_trace_due : bool = false // Custom ground AI must only run inside a real multiplayer battle. Single-player test // drives also dispatch tag=server ECS, but their target vehicles must never be taken over. @@ -81,6 +84,8 @@ def private wto_reset_runtime() g_cmd_dirty = true g_last_zone_ver = -1 g_next_diag_at = 0.0 + g_next_trace_at = 0.0 + g_trace_due = false wto_navmesh_battle_reset(g_navmesh) wto_slots_reset_all(g_bots) @@ -109,6 +114,7 @@ def wto_ai_unit_dead_es(evt : Event; eid : EntityId; unit__ref : UnitRef) if u != null && as_gm(u) != null && (int(u.army) == 1 || int(u.army) == 2) let now = float(get_app().usefulTotalTime) wto_world_record_death(g_world, eid, int(u.army), u.pos, now) + wto_trace_death(now, eid, int(u.army), u.pos) wto_route_report_wreck(g_navmesh.state, now, u.pos, g_bots) if wto_slots_forget(g_bots, eid) g_cmd_dirty = true @@ -127,6 +133,7 @@ def wto_ai_unit_damage_es(evt : EventUnitDamage; eid : EntityId; unit__ref : Uni if u == null || !offEid || offEid == eid return let hpDropped = uint(evt.hpFixed) < uint(evt.prevHpFixed) + wto_trace_hit(float(get_app().usefulTotalTime), eid, offEid, evt.pos, evt.damage, evt.damageTypeId, hpDropped) wto_slots_on_damage(g_world, g_bots, eid, offEid, u, evt.pos, hpDropped, float(get_app().usefulTotalTime)) [es(tag=server, before=wto_ai_pipeline_es)] @@ -166,6 +173,7 @@ def wto_ai_world_tick_es(act : UpdateStageInfoAct) g_next_diag_at = now + WTO_AI_DIAG_INTERVAL_SEC wto_diag_log_telemetry(g_world, now, g_bots, g_crowd) wto_navmesh_log_stats(g_navmesh) + g_trace_due = wto_trace_tick(g_world, now, g_bots, g_next_trace_at) wto_stats_tick(now, g_stats) [es(tag=server, before=wto_ai_pipeline_es)] @@ -218,6 +226,8 @@ def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : slot.nextNavAt = now + WTO_AI_NAV_TICK_SEC wto_nav_update(g_world, g_navmesh.state, idx, now, unit.pos, unit.unitTm[0], slot) wto_stats_bot_frame(g_world, now, act.dt, unit.pos, unit.unitTm[0], slot, g_stats) + if g_trace_due + wto_trace_bot(now, slot) [es(tag=server, after=wto_ai_pipeline_es)] def wto_ai_phys_tick_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&; diff --git a/game-ai/ground/wto_ai_trace_common.das b/game-ai/ground/wto_ai_trace_common.das new file mode 100644 index 0000000..c6bfb2c --- /dev/null +++ b/game-ai/ground/wto_ai_trace_common.das @@ -0,0 +1,86 @@ +// Replay trace for the ground AI viewer (apps/ai-lab), written every diagnostics.traceIntervalSec: +// WTO_AI|TRACE_CAP capture zones (position, radius, owner, progress) +// WTO_AI|TRACE_U every ground unit, bots and players alike (position, hull heading, speed) +// WTO_AI|TRACE_B every bot's decision state (order, behavior, targets, turret, trigger) +// and as they happen: WTO_AI|HIT (part damage with its offender) and WTO_AI|DEATH. +// Positions are whole metres, headings whole degrees of atan2(z, x) in world space. +// The simulator writes the same lines, so this module uses no engine module. +options indenting = 2 +options no_global_heap = true +module wto_ai_trace_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common + +def private wto_tr_m(v : float) : int + return int(floor(v + 0.5)) + +def private wto_tr_yaw(dir : float3) : int + return int(floor(atan2(dir.z, dir.x) * WTO_RAD_TO_DEG + 0.5)) + +def private wto_tr_b(flag : bool) : int + return flag ? 1 : 0 + +def private wto_tr_is_bot(bots : WtoBotSlot[64] const&; eid : EntityId) : int + for i in range(WTO_MAX_BOTS) + if bots[i].used && bots[i].eid == eid + return 1 + return 0 + +// True when this frame writes a trace sample; then the capture zones and all ground units are +// written at once, and the pipeline adds one TRACE_B line per bot. +[never_inline] +def public wto_trace_tick(world : WtoWorldSnap const&; now : float; bots : WtoBotSlot[64] const&; + var nextAt : float&) : bool + if !WTO_AI_TRACE_ENABLED || now < nextAt + return false + nextAt = now + WTO_AI_TRACE_SEC + for c in range(world.capCount) + assume z = world.caps[c] + print("WTO_AI|TRACE_CAP|t={now}|idx={c}|x={wto_tr_m(z.center.x)}|z={wto_tr_m(z.center.z)}|r={wto_tr_m(z.radius)}|owner={z.ownerArmy}|prog={z.progress}\n") + for i in range(world.unitCount) + assume u = world.units[i] + if !u.isGround + continue + let bot = wto_tr_is_bot(bots, u.eid) + print("WTO_AI|TRACE_U|t={now}|eid={uint(u.eid)}|army={u.army}|bot={bot}|human={wto_tr_b(u.isHuman)}|alive={wto_tr_b(u.isAlive)}|x={wto_tr_m(u.pos.x)}|y={wto_tr_m(u.pos.y)}|z={wto_tr_m(u.pos.z)}|yaw={wto_tr_yaw(u.hullFwd)}|v={length(u.vel)}|shoot={wto_tr_b(u.isShooting)}|light={wto_tr_b(u.isLightTag)}\n") + return true + +def private wto_tr_threat_eid(slot : WtoBotSlot const&; idx : int) : uint + return idx >= 0 && idx < slot.threat.count ? uint(slot.threat.entries[idx].eid) : 0u + +// The thing the turret aims at: the engaged target or the threat it looks at; 0 otherwise. +def private wto_tr_look_eid(slot : WtoBotSlot const&) : uint + let why = slot.turret.lookReason + if why == WTO_LOOK_ENGAGE + return uint(slot.perceive.targetEid) + if why == WTO_LOOK_THREAT + return uint(slot.turret.lookEid) + return 0u + +[never_inline] +def public wto_trace_bot(now : float; slot : WtoBotSlot const&) + assume o = slot.order + assume tac = slot.tactics + assume p = slot.perceive + assume tr = slot.trigger + let gx = o.valid ? wto_tr_m(o.goalPos.x) : 0 + let gz = o.valid ? wto_tr_m(o.goalPos.z) : 0 + let gun = slot.fire.hasBarrelSight ? wto_tr_yaw(slot.fire.barrelSight) : 9999 + let topEid = wto_tr_threat_eid(slot, slot.threat.topIdx) + let topVis = wto_tr_threat_eid(slot, slot.threat.topVisibleIdx) + print("WTO_AI|TRACE_B|t={now}|eid={uint(slot.eid)}|cls={slot.spec.role}|ord={wto_tr_b(o.valid)}|cmd={o.role}|urg={o.urgency}|cap={o.capIndex}|lane={o.laneId}|gx={gx}|gz={gz}|bhv={tac.behavior}|bs={tac.behaviorScore}|st={tac.state}|wantV={tac.desiredSpeedMps}|vf={slot.drive.lastVFwd}|rev={wto_tr_b(tac.reverseTravel)}|tgt={uint(p.targetEid)}|los={wto_tr_b(p.hasClearLos)}|threats={slot.threat.count}|top={topEid}|topVis={topVis}|look={wto_tr_look_eid(slot)}|why={slot.turret.lookReason}|wish={wto_tr_yaw(slot.turret.wishDir)}|gun={gun}|ready={wto_tr_b(slot.fire.gunReady)}|reload={wto_tr_b(slot.fire.reloading)}|deny={slot.fire.lastDenyReason}|p={tr.hitProb}|thr={tr.threshold}|reqV={tr.wantSpeedMps}\n") + +// Part damage on any unit with its offender, so the viewer can draw who hit whom and the last +// offender before a death. `dropped` tells whether the part lost hit points. +def public wto_trace_hit(now : float; victim, offender : EntityId; pos : float3; damage : float; damageType : int; dropped : bool) + if WTO_AI_TRACE_ENABLED + print("WTO_AI|HIT|t={now}|eid={uint(victim)}|off={uint(offender)}|x={wto_tr_m(pos.x)}|z={wto_tr_m(pos.z)}|dmg={damage}|type={damageType}|drop={wto_tr_b(dropped)}\n") + +def public wto_trace_death(now : float; eid : EntityId; army : int; pos : float3) + if WTO_AI_TRACE_ENABLED + print("WTO_AI|DEATH|t={now}|eid={uint(eid)}|army={army}|x={wto_tr_m(pos.x)}|z={wto_tr_m(pos.z)}\n") diff --git a/game-ai/ground/wto_ai_turret_common.das b/game-ai/ground/wto_ai_turret_common.das index 7db5a26..6084464 100644 --- a/game-ai/ground/wto_ai_turret_common.das +++ b/game-ai/ground/wto_ai_turret_common.das @@ -60,13 +60,19 @@ def private wto_turret_scan_dir(now : float; myPos, hullFwd : float3; slot : Wto [never_inline] def public wto_turret_look_dir(now : float; muzzlePos, myPos, hullFwd : float3; var slot : WtoBotSlot&) : float3 assume p = slot.perceive + assume tr = slot.turret let threat = wto_turret_pick_threat(now, slot) if threat >= 0 + tr.lookReason = WTO_LOOK_THREAT return normalize((slot.threat.entries[threat].pos + float3(0.0, 1.4, 0.0)) - muzzlePos) if now < p.watchUntil + tr.lookReason = WTO_LOOK_WATCH return normalize(p.watchPos - muzzlePos) if !!p.targetEid && (now - p.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC + tr.lookReason = WTO_LOOK_MEMORY return normalize((p.knownPos + float3(0.0, 1.4, 0.0)) - muzzlePos) if now < p.alertUntil + tr.lookReason = WTO_LOOK_CUE return float3(cos(p.alertYawRad), 0.0, sin(p.alertYawRad)) + tr.lookReason = WTO_LOOK_SCAN return wto_turret_scan_dir(now, myPos, hullFwd, slot) diff --git a/packages/ground-sim/package.json b/packages/ground-sim/package.json new file mode 100644 index 0000000..f10191f --- /dev/null +++ b/packages/ground-sim/package.json @@ -0,0 +1,9 @@ +{ + "name": "@wto/ground-sim", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts" + } +} diff --git a/packages/ground-sim/src/index.ts b/packages/ground-sim/src/index.ts new file mode 100644 index 0000000..c769fef --- /dev/null +++ b/packages/ground-sim/src/index.ts @@ -0,0 +1,15 @@ +/** + * Ground AI lab: map data readers and the replay trace shared by the replay viewer (apps/ai-lab) + * and the simulator (docs: tank-ai-revision-plan, section 3). + */ +export { + NAV_AREA_NAMES, NAV_FLAG, NAV_TIER_NAMES, NavPackError, readNavPack, + type NavCover, type NavHeader, type NavPack, type NavTactical, type NavTier, +} from './map/wtonav.ts'; +export { parsePois, type MapPoint, type MapPois } from './map/pois.ts'; +export { + BEHAVIOR_NAMES, BLOCK_NAMES, COMMAND_NAMES, DENY_NAMES, LANE_NAMES, LOOK_NAMES, STATE_NAMES, + URGENCY_NAMES, VEHICLE_CLASS_NAMES, nameOf, +} from './trace/names.ts'; +export { parseTraceLog } from './trace/parse.ts'; +export type { BotSample, CapSample, TraceBattle, TraceEvent, TraceFrame, UnitSample } from './trace/types.ts'; diff --git a/packages/ground-sim/src/map/pois.ts b/packages/ground-sim/src/map/pois.ts new file mode 100644 index 0000000..e2f4293 --- /dev/null +++ b/packages/ground-sim/src/map/pois.ts @@ -0,0 +1,51 @@ +/** + * Points of interest written next to each navigation pack (`.pois.json`, tools/navgen): + * battle bounds, and per mission the team spawns and the capture zones. + */ + +export interface MapPoint { + readonly name: string; + readonly x: number; + readonly y: number; + readonly z: number; + readonly radius: number; + readonly mission: string; +} + +export interface MapPois { + readonly level: string; + readonly missions: string[]; + readonly boundsMin: readonly [number, number]; + readonly boundsMax: readonly [number, number]; + readonly team1Spawns: MapPoint[]; + readonly team2Spawns: MapPoint[]; + readonly captureZones: MapPoint[]; +} + +function points(value: unknown): MapPoint[] { + if (!Array.isArray(value)) return []; + return value.flatMap((p: unknown): MapPoint[] => { + if (typeof p !== 'object' || p === null) return []; + const r = p as Record; + const n = (k: string): number => (typeof r[k] === 'number' ? (r[k] as number) : 0); + return [{ name: String(r['name'] ?? ''), x: n('x'), y: n('y'), z: n('z'), radius: n('radius'), mission: String(r['mission'] ?? '') }]; + }); +} + +function pair(value: unknown): readonly [number, number] { + return Array.isArray(value) && typeof value[0] === 'number' && typeof value[1] === 'number' ? [value[0], value[1]] : [0, 0]; +} + +/** Parses the text of a `.pois.json` file. */ +export function parsePois(text: string): MapPois { + const raw = JSON.parse(text) as Record; + return { + level: String(raw['level'] ?? ''), + missions: Array.isArray(raw['missions']) ? raw['missions'].map(String) : [], + boundsMin: pair(raw['boundsMin']), + boundsMax: pair(raw['boundsMax']), + team1Spawns: points(raw['team1Spawns']), + team2Spawns: points(raw['team2Spawns']), + captureZones: points(raw['captureZones']), + }; +} diff --git a/packages/ground-sim/src/map/wtonav.ts b/packages/ground-sim/src/map/wtonav.ts new file mode 100644 index 0000000..438ac89 --- /dev/null +++ b/packages/ground-sim/src/map/wtonav.ts @@ -0,0 +1,226 @@ +/** + * Reader for the baked `.wtonav` navigation pack (native/wto-nav/wto_nav_format.h): the header, + * the walkable polygons of each mesh tier (upstream Detour tile data), the cover points and the + * 8 m tactical grid. Only plain views over the bytes, so it runs in Node and in the browser. + */ + +export const NAV_TIER_NAMES = ['narrow', 'standard', 'wide'] as const; + +/** Detour polygon area ids written by the baker (WtoPolyArea). */ +export const NAV_AREA_NAMES = [ + 'unwalkable', 'road', 'bridge', 'ground', 'rough', 'forest', 'crushable', + 'shallowWater', 'chokepoint', 'exposed', 'deepWater', 'noGo', +] as const; + +/** Detour polygon flags (WtoPolyFlag). */ +export const NAV_FLAG = { + walk: 0x01, shallowWater: 0x02, deepWater: 0x04, chokepoint: 0x08, + blocked: 0x10, road: 0x20, downhill: 0x40, platform: 0x80, +} as const; + +export interface NavHeader { + readonly version: number; + readonly flags: number; + readonly everSha1: string; + readonly bmin: readonly [number, number, number]; + readonly bmax: readonly [number, number, number]; + readonly waterLevel: number; + readonly coverCount: number; + readonly tacCols: number; + readonly tacRows: number; + readonly tacCellM: number; + readonly tacOrigin: readonly [number, number]; +} + +/** + * Every ground polygon of one tier. `ring[i]` is the polygon's outline as x, z pairs in world + * metres; `y[i]` the mean height of its corners. + */ +export interface NavTier { + readonly polyCount: number; + readonly rings: Float32Array[]; + readonly heights: Float32Array; + readonly areas: Uint8Array; + readonly flags: Uint16Array; +} + +export interface NavCover { + readonly pos: readonly [number, number, number]; + readonly coverDir: readonly [number, number]; + readonly retreatDir: readonly [number, number]; + readonly halfAngleDeg: number; + readonly heightM: number; + readonly widthM: number; + /** 1 full cover, 2 hull-down. */ + readonly kind: number; +} + +/** Tactical grid, row-major from tacOrigin: each cell is exposure, clearance, team 1 and 2 priors. */ +export interface NavTactical { + readonly cols: number; + readonly rows: number; + readonly cellM: number; + readonly origin: readonly [number, number]; + readonly exposure: Uint8Array; + readonly clearanceHalfM: Uint8Array; +} + +export interface NavPack { + readonly header: NavHeader; + readonly tiers: NavTier[]; + readonly covers: NavCover[]; + readonly tactical: NavTactical; +} + +export class NavPackError extends Error {} + +const NAV_MAGIC = 'WTONAV\0\x01'; +const NAV_VERSION = 1; +const TIER_COUNT = 3; +const HEADER_BYTES = 124; +const COVER_BYTES = 68; +const NAV_PARAMS_BYTES = 28; +const TILE_HEADER_BYTES = 100; +const POLY_BYTES = 32; +const VERTS_PER_POLY = 6; +const DT_NULL_IDX = 0xffff; +const DT_POLYTYPE_GROUND = 0; + +function align4(n: number): number { + return (n + 3) & ~3; +} + +function readHeader(view: DataView): NavHeader & { tierOffsets: number[]; tierSizes: number[]; coverOffset: number; tacOffset: number } { + if (view.byteLength < HEADER_BYTES) throw new NavPackError('file shorter than the pack header'); + let magic = ''; + for (let i = 0; i < 8; i++) magic += String.fromCharCode(view.getUint8(i)); + const version = view.getUint32(8, true); + if (magic !== NAV_MAGIC || version !== NAV_VERSION || view.getUint32(64, true) !== TIER_COUNT) { + throw new NavPackError(`not a version ${NAV_VERSION} navigation pack`); + } + let sha = ''; + for (let i = 0; i < 20; i++) sha += view.getUint8(16 + i).toString(16).padStart(2, '0'); + const f = (at: number): number => view.getFloat32(at, true); + const u = (at: number): number => view.getUint32(at, true); + return { + version, + flags: u(12), + everSha1: sha, + bmin: [f(36), f(40), f(44)], + bmax: [f(48), f(52), f(56)], + waterLevel: f(60), + tierOffsets: [u(68), u(72), u(76)], + tierSizes: [u(80), u(84), u(88)], + coverOffset: u(92), + coverCount: u(96), + tacOffset: u(100), + tacCols: u(104), + tacRows: u(108), + tacCellM: f(112), + tacOrigin: [f(116), f(120)], + }; +} + +interface TierBuilder { + rings: Float32Array[]; + heights: number[]; + areas: number[]; + flags: number[]; +} + +function readTile(view: DataView, at: number, size: number, out: TierBuilder): void { + if (size < TILE_HEADER_BYTES) throw new NavPackError('Detour tile shorter than its header'); + const polyCount = view.getInt32(at + 24, true); + const vertCount = view.getInt32(at + 28, true); + const vertsAt = at + align4(TILE_HEADER_BYTES); + const polysAt = vertsAt + align4(vertCount * 12); + if (polysAt + polyCount * POLY_BYTES > at + size) throw new NavPackError('Detour tile polygons truncated'); + for (let p = 0; p < polyCount; p++) { + const pa = polysAt + p * POLY_BYTES; + const n = view.getUint8(pa + 30); + const areaAndType = view.getUint8(pa + 31); + if (areaAndType >> 6 !== DT_POLYTYPE_GROUND || n < 3) continue; + const ring = new Float32Array(n * 2); + let ySum = 0; + for (let k = 0; k < n && k < VERTS_PER_POLY; k++) { + const vi = view.getUint16(pa + 4 + k * 2, true); + if (vi === DT_NULL_IDX || vi >= vertCount) throw new NavPackError('Detour polygon vertex out of range'); + const va = vertsAt + vi * 12; + ring[k * 2] = view.getFloat32(va, true); + ySum += view.getFloat32(va + 4, true); + ring[k * 2 + 1] = view.getFloat32(va + 8, true); + } + out.rings.push(ring); + out.heights.push(ySum / n); + out.areas.push(areaAndType & 0x3f); + out.flags.push(view.getUint16(pa + 28, true)); + } +} + +function readTier(view: DataView, offset: number, size: number): NavTier { + if (offset + size > view.byteLength || size < NAV_PARAMS_BYTES + 4) throw new NavPackError('tier outside the file'); + const end = offset + size; + const tileCount = view.getUint32(offset + NAV_PARAMS_BYTES, true); + let at = offset + NAV_PARAMS_BYTES + 4; + const out: TierBuilder = { rings: [], heights: [], areas: [], flags: [] }; + for (let t = 0; t < tileCount; t++) { + if (at + 4 > end) throw new NavPackError(`tile ${t} header truncated`); + const tileSize = view.getUint32(at, true); + at += 4; + if (tileSize === 0 || at + tileSize > end) throw new NavPackError(`tile ${t} truncated`); + readTile(view, at, tileSize, out); + at += tileSize; + } + return { + polyCount: out.rings.length, + rings: out.rings, + heights: Float32Array.from(out.heights), + areas: Uint8Array.from(out.areas), + flags: Uint16Array.from(out.flags), + }; +} + +function readCovers(view: DataView, offset: number, count: number): NavCover[] { + if (offset + count * COVER_BYTES > view.byteLength) throw new NavPackError('cover points outside the file'); + const covers: NavCover[] = []; + for (let i = 0; i < count; i++) { + const a = offset + i * COVER_BYTES; + const f = (k: number): number => view.getFloat32(a + k * 4, true); + covers.push({ + pos: [f(0), f(1), f(2)], + coverDir: [f(3), f(4)], + retreatDir: [f(5), f(6)], + halfAngleDeg: f(13), + heightM: f(14), + widthM: f(15), + kind: view.getUint8(a + 64), + }); + } + return covers; +} + +function readTactical(view: DataView, h: ReturnType): NavTactical { + const cells = h.tacCols * h.tacRows; + if (h.tacOffset + cells * 4 > view.byteLength) throw new NavPackError('tactical grid outside the file'); + const exposure = new Uint8Array(cells); + const clearance = new Uint8Array(cells); + for (let i = 0; i < cells; i++) { + exposure[i] = view.getUint8(h.tacOffset + i * 4); + clearance[i] = view.getUint8(h.tacOffset + i * 4 + 1); + } + return { cols: h.tacCols, rows: h.tacRows, cellM: h.tacCellM, origin: h.tacOrigin, exposure, clearanceHalfM: clearance }; +} + +/** Parses a whole `.wtonav` file. Throws NavPackError when the bytes are not a valid pack. */ +export function readNavPack(bytes: Uint8Array): NavPack { + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const h = readHeader(view); + const tiers: NavTier[] = []; + for (let t = 0; t < TIER_COUNT; t++) tiers.push(readTier(view, h.tierOffsets[t] ?? 0, h.tierSizes[t] ?? 0)); + const header: NavHeader = { + version: h.version, flags: h.flags, everSha1: h.everSha1, bmin: h.bmin, bmax: h.bmax, + waterLevel: h.waterLevel, coverCount: h.coverCount, tacCols: h.tacCols, tacRows: h.tacRows, + tacCellM: h.tacCellM, tacOrigin: h.tacOrigin, + }; + return { header, tiers, covers: readCovers(view, h.coverOffset, h.coverCount), tactical: readTactical(view, h) }; +} diff --git a/packages/ground-sim/src/trace/names.ts b/packages/ground-sim/src/trace/names.ts new file mode 100644 index 0000000..d8a5720 --- /dev/null +++ b/packages/ground-sim/src/trace/names.ts @@ -0,0 +1,34 @@ +/** + * Display names of the numeric codes the ground AI writes into its log lines. They mirror the + * `let public WTO_*` constants of game-ai/ground; index = code. + */ + +export const BEHAVIOR_NAMES = ['advance', 'engage', 'halt', 'cover', 'reposition', 'hold', 'disperse', 'withdraw', 'repair'] as const; + +export const STATE_NAMES: Readonly> = { + 0: 'march', 1: 'runAndGun', 3: 'shortHalt', 4: 'retreatCover', 5: 'coverReload', + 7: 'hullAngle', 8: 'reposition', 9: 'disabled', 10: 'disperse', 11: 'ridgeWithdraw', +}; + +export const DENY_NAMES = [ + 'ok', 'noTarget', 'notReady', 'hitProb', 'longWindow', 'aimErr', 'settle', 'budget', + 'muzzleHard', 'arcHard', 'friendly', 'multiGun', 'traverse', 'burstPause', +] as const; + +export const BLOCK_NAMES = ['none', 'terrain', 'object', 'wreck', 'vehicle', 'smoke', 'foliage'] as const; + +export const COMMAND_NAMES = ['assault', 'flank', 'overwatch', 'defend', 'reserve', 'spaa'] as const; + +export const URGENCY_NAMES = ['low', 'medium', 'high'] as const; + +export const LANE_NAMES = ['center', 'left', 'right'] as const; + +export const VEHICLE_CLASS_NAMES = ['medium', 'light', 'heavy', 'td', 'spaa'] as const; + +/** Why the turret points where it does (WTO_LOOK_*). */ +export const LOOK_NAMES = ['none', 'engage', 'threat', 'watch', 'memory', 'cue', 'scan'] as const; + +export function nameOf(names: readonly string[] | Readonly>, code: number): string { + const name = Array.isArray(names) ? names[code] : (names as Readonly>)[code]; + return name ?? String(code); +} diff --git a/packages/ground-sim/src/trace/parse.ts b/packages/ground-sim/src/trace/parse.ts new file mode 100644 index 0000000..899c89e --- /dev/null +++ b/packages/ground-sim/src/trace/parse.ts @@ -0,0 +1,136 @@ +/** + * Reads the ground AI replay trace out of a decrypted game log (wtotools decrypt-clog). Every + * `WTO_AI|` line is ` [D] WTO_AI|KIND|key=value|...`. A battle starts at + * RUNTIME_READY; lines before the first one (hangar) are skipped. TRACE_CAP, TRACE_U and TRACE_B + * lines with the same time form one frame; all other kinds become events. Lines without a `t` field get + * their mission time from the log clock, offset by the last line that had both. + */ +import type { BotSample, CapSample, TraceBattle, TraceEvent, TraceFrame, UnitSample } from './types.ts'; + +type Fields = Record; + +interface MutableBattle { + level: string | undefined; + frames: TraceFrame[]; + events: TraceEvent[]; +} + +const MARK = 'WTO_AI|'; + +function splitLine(line: string): { clock: number; kind: string; fields: Fields } | undefined { + const at = line.indexOf(MARK); + if (at < 0) return undefined; + const clock = Number.parseFloat(line); + const parts = line.slice(at + MARK.length).trimEnd().split('|'); + const kind = parts[0] ?? ''; + const fields: Fields = {}; + for (let i = 1; i < parts.length; i++) { + const part = parts[i] ?? ''; + const eq = part.indexOf('='); + if (eq > 0) fields[part.slice(0, eq)] = part.slice(eq + 1); + } + return { clock, kind, fields }; +} + +function num(f: Fields, key: string): number { + const v = Number(f[key]); + return Number.isFinite(v) ? v : 0; +} + +function flag(f: Fields, key: string): boolean { + return f[key] === '1'; +} + +function id(f: Fields, key: string): string { + return f[key] ?? '0'; +} + +function readCap(f: Fields): CapSample { + return { idx: num(f, 'idx'), x: num(f, 'x'), z: num(f, 'z'), r: num(f, 'r'), owner: num(f, 'owner'), progress: num(f, 'prog') }; +} + +function readUnit(f: Fields): UnitSample { + return { + eid: id(f, 'eid'), army: num(f, 'army'), bot: flag(f, 'bot'), human: flag(f, 'human'), alive: flag(f, 'alive'), + x: num(f, 'x'), y: num(f, 'y'), z: num(f, 'z'), yaw: num(f, 'yaw'), speed: num(f, 'v'), + shooting: flag(f, 'shoot'), light: flag(f, 'light'), + }; +} + +function readBot(f: Fields): BotSample { + const gun = num(f, 'gun'); + return { + eid: id(f, 'eid'), vehicleClass: num(f, 'cls'), hasOrder: flag(f, 'ord'), command: num(f, 'cmd'), + urgency: num(f, 'urg'), capIdx: num(f, 'cap'), lane: num(f, 'lane'), goalX: num(f, 'gx'), goalZ: num(f, 'gz'), + behavior: num(f, 'bhv'), behaviorScore: num(f, 'bs'), state: num(f, 'st'), wantSpeed: num(f, 'wantV'), + forwardSpeed: num(f, 'vf'), reverseTravel: flag(f, 'rev'), target: id(f, 'tgt'), targetInSight: flag(f, 'los'), + threatCount: num(f, 'threats'), topThreat: id(f, 'top'), topVisibleThreat: id(f, 'topVis'), + lookAt: id(f, 'look'), lookReason: num(f, 'why'), wishYaw: num(f, 'wish'), + gunYaw: gun === 9999 ? undefined : gun, gunReady: flag(f, 'ready'), reloading: flag(f, 'reload'), + deny: num(f, 'deny'), hitProb: num(f, 'p'), threshold: num(f, 'thr'), requestedSpeed: num(f, 'reqV'), + }; +} + +function frameAt(battle: MutableBattle, t: number): TraceFrame { + const last = battle.frames[battle.frames.length - 1]; + if (last !== undefined && last.t === t) return last; + const frame: TraceFrame = { t, caps: [], units: new Map(), bots: new Map() }; + battle.frames.push(frame); + return frame; +} + +function finish(b: MutableBattle): TraceBattle { + b.events.sort((a, c) => a.t - c.t); + const firstFrame = b.frames[0]; + const lastFrame = b.frames[b.frames.length - 1]; + const firstEvent = b.events[0]; + const lastEvent = b.events[b.events.length - 1]; + const startT = Math.min(firstFrame?.t ?? Infinity, firstEvent?.t ?? Infinity); + const endT = Math.max(lastFrame?.t ?? -Infinity, lastEvent?.t ?? -Infinity); + return { level: b.level, frames: b.frames, events: b.events, startT: Number.isFinite(startT) ? startT : 0, endT: Number.isFinite(endT) ? endT : 0 }; +} + +/** All battles of one decrypted log, in log order. Battles without any trace frame are kept. */ +export function parseTraceLog(text: string): TraceBattle[] { + const battles: TraceBattle[] = []; + let current: MutableBattle | undefined; + let pendingLevel: string | undefined; + let clockOffset: number | undefined; + const open = (): MutableBattle => { + if (current !== undefined) battles.push(finish(current)); + current = { level: pendingLevel, frames: [], events: [] }; + return current; + }; + for (const line of text.split('\n')) { + const parsed = splitLine(line); + if (parsed === undefined) continue; + const { clock, kind, fields } = parsed; + if (kind.startsWith('NAVMESH') && fields['level'] !== undefined && fields['level'] !== '') { + pendingLevel = fields['level']; + if (current !== undefined && current.level === undefined) current.level = pendingLevel; + } + if (kind === 'RUNTIME_READY') { + open(); + clockOffset = undefined; + continue; + } + const hasT = fields['t'] !== undefined; + let t: number; + if (hasT) { + t = num(fields, 't'); + if (Number.isFinite(clock)) clockOffset = clock - t; + } else if (clockOffset !== undefined && Number.isFinite(clock)) { + t = clock - clockOffset; + } else { + continue; + } + const battle: MutableBattle | undefined = current; + if (battle === undefined) continue; + if (kind === 'TRACE_CAP') frameAt(battle, t).caps.push(readCap(fields)); + else if (kind === 'TRACE_U') { const u = readUnit(fields); frameAt(battle, t).units.set(u.eid, u); } + else if (kind === 'TRACE_B') { const b = readBot(fields); frameAt(battle, t).bots.set(b.eid, b); } + else battle.events.push({ t, kind, eid: fields['eid'], fields }); + } + if (current !== undefined) battles.push(finish(current)); + return battles; +} diff --git a/packages/ground-sim/src/trace/types.ts b/packages/ground-sim/src/trace/types.ts new file mode 100644 index 0000000..f859b04 --- /dev/null +++ b/packages/ground-sim/src/trace/types.ts @@ -0,0 +1,90 @@ +/** + * One battle of the ground AI replay trace (game-ai/ground/wto_ai_trace_common.das), as read from + * a decrypted game log or written by the simulator. Times are mission seconds; positions world + * metres; headings degrees of atan2(z, x). Entity ids stay the strings the log prints. + */ + +export interface CapSample { + readonly idx: number; + readonly x: number; + readonly z: number; + readonly r: number; + readonly owner: number; + readonly progress: number; +} + +export interface UnitSample { + readonly eid: string; + readonly army: number; + readonly bot: boolean; + readonly human: boolean; + readonly alive: boolean; + readonly x: number; + readonly y: number; + readonly z: number; + readonly yaw: number; + readonly speed: number; + readonly shooting: boolean; + readonly light: boolean; +} + +export interface BotSample { + readonly eid: string; + readonly vehicleClass: number; + readonly hasOrder: boolean; + readonly command: number; + readonly urgency: number; + readonly capIdx: number; + readonly lane: number; + readonly goalX: number; + readonly goalZ: number; + readonly behavior: number; + readonly behaviorScore: number; + readonly state: number; + readonly wantSpeed: number; + readonly forwardSpeed: number; + readonly reverseTravel: boolean; + /** Perception target; "0" when none. */ + readonly target: string; + readonly targetInSight: boolean; + readonly threatCount: number; + readonly topThreat: string; + readonly topVisibleThreat: string; + /** What the turret aims at (engaged target or watched threat); "0" otherwise. */ + readonly lookAt: string; + readonly lookReason: number; + readonly wishYaw: number; + /** Live barrel heading; undefined when the barrel could not be sampled. */ + readonly gunYaw: number | undefined; + readonly gunReady: boolean; + readonly reloading: boolean; + readonly deny: number; + readonly hitProb: number; + readonly threshold: number; + readonly requestedSpeed: number; +} + +export interface TraceFrame { + readonly t: number; + readonly caps: CapSample[]; + readonly units: Map; + readonly bots: Map; +} + +/** Any other WTO_AI line of the battle (SHOT, HIT, DEATH, BEHAVIOR, DENY, TURRET_FOCUS, NAV_*...). */ +export interface TraceEvent { + readonly t: number; + readonly kind: string; + /** Entity the line is about (its `eid` field), when it has one. */ + readonly eid: string | undefined; + readonly fields: Readonly>; +} + +export interface TraceBattle { + /** Level name from the navigation pack line (e.g. avg_berlin), when logged. */ + readonly level: string | undefined; + readonly frames: TraceFrame[]; + readonly events: TraceEvent[]; + readonly startT: number; + readonly endT: number; +} diff --git a/packages/patcher/src/ground-ai/ground-ai-config.ts b/packages/patcher/src/ground-ai/ground-ai-config.ts index 25b7479..5c3e003 100644 --- a/packages/patcher/src/ground-ai/ground-ai-config.ts +++ b/packages/patcher/src/ground-ai/ground-ai-config.ts @@ -339,6 +339,8 @@ export interface GroundAiConfig { readonly statsSampleSec: number; readonly statsSampleRangeM: number; readonly statsRearArcDeg: number; + readonly trace: boolean; + readonly traceIntervalSec: number; }; } @@ -590,6 +592,8 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] { ['WTO_AI_STATS_SAMPLE_SEC', 'float', c.diagnostics.statsSampleSec], ['WTO_AI_STATS_RANGE_M', 'float', c.diagnostics.statsSampleRangeM], ['WTO_AI_STATS_REAR_ARC_DEG', 'float', c.diagnostics.statsRearArcDeg], + ['WTO_AI_TRACE_ENABLED', 'bool', c.diagnostics.trace], + ['WTO_AI_TRACE_SEC', 'float', c.diagnostics.traceIntervalSec], ]; } diff --git a/tsconfig.json b/tsconfig.json index a039a22..e5e004e 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -17,6 +17,7 @@ }, "include": ["apps/*/src/**/*.ts", "packages/*/src/**/*.ts", "scripts/**/*.ts"], // The launcher is an Electron app with a window: it has its own tsconfig.node.json and - // tsconfig.web.json and its own typecheck script. - "exclude": ["apps/launcher/**"] + // tsconfig.web.json and its own typecheck script. The AI lab (apps/ai-lab) is a Vite page with + // its own tsconfig.json and typecheck script too. + "exclude": ["apps/launcher/**", "apps/ai-lab/**"] } From f8bd79042bcd25a48eb139d7177ef86bbf8be712 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sun, 6 Dec 2026 13:53:52 +0800 Subject: [PATCH 18/19] fix(ground-ai): command the turret servo with the wished angle The turret command led the current yaw by one frame's traverse step, so the stock servo crawled: the replay trace measured about 4 deg/s relative to the hull while the barrel was more than 20 deg off, against a median stock traverse of 24 deg/s. Bots kept their barrels on the hull and were mostly denied by aim error at close range. yawLim and pitchLim now carry the wished angles, clipped to the mount's yaw arc and to the elevation sector the barrel is in. A full-traverse command leads the turret by at most 90 deg so it always turns the short way. Secondary mounts use the same command, and the unused frame time argument of their aiming path is dropped. In a lab battle the 90th percentile turret rate rose to 28 deg/s, the median aim error to target fell from 15-22 deg to 2 deg, and moving shots rose from under 20% to 49% of main gun shots. --- game-ai/ground/wto_ai_fire_aux_common.das | 4 +- game-ai/ground/wto_ai_fire_common.das | 2 +- game-ai/ground/wto_ai_traverse_common.das | 49 ++++++++++++----------- 3 files changed, 29 insertions(+), 26 deletions(-) diff --git a/game-ai/ground/wto_ai_fire_aux_common.das b/game-ai/ground/wto_ai_fire_aux_common.das index af55b90..2240389 100644 --- a/game-ai/ground/wto_ai_fire_aux_common.das +++ b/game-ai/ground/wto_ai_fire_aux_common.das @@ -27,7 +27,7 @@ def private wto_aux_group(groupNo : int) : bool return groupNo == int(WeaponTriggerGroups.TRIGGER_GROUP_SECONDARY) || groupNo == int(WeaponTriggerGroups.TRIGGER_GROUP_COAXIAL_GUN) [never_inline] -def public wto_fire_aux_aim(var unit : Unit?; className : string; dt, dist : float; var slot : WtoBotSlot&) : bool +def public wto_fire_aux_aim(var unit : Unit?; className : string; dist : float; var slot : WtoBotSlot&) : bool if !wto_aux_in_range(dist) return false var changed = false @@ -49,7 +49,7 @@ def public wto_fire_aux_aim(var unit : Unit?; className : string; dt, dist : flo var aimPt = base var direction = gunTm[0] let _range = wto_solve_ballistic_aim(gunTm[3], unit.vel, base, mount.shell.speedMps, mount.shell.dragCx, mount.shell.massKg, mount.shell.caliberM, slot, aimPt, direction) - if wto_aim_aux_mount(unit, className, dt, tIdx, direction, mount) + if wto_aim_aux_mount(unit, className, tIdx, direction, mount) changed = true return changed diff --git a/game-ai/ground/wto_ai_fire_common.das b/game-ai/ground/wto_ai_fire_common.das index 1213d5d..b91406a 100644 --- a/game-ai/ground/wto_ai_fire_common.das +++ b/game-ai/ground/wto_ai_fire_common.das @@ -271,7 +271,7 @@ def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; classN if engage let aimBase = slot.perceive.visibleAimPt distToTgt = wto_solve_ballistic_aim(muzzlePos, unit.vel, aimBase, slot.fire.activeSpeedMps, slot.fire.activeDragCx, slot.fire.activeMassKg, slot.fire.activeCaliberM, slot, aimPt, wishWorldDir) - auxAimed = wto_fire_aux_aim(unit, className, dt, distXZ, slot) + auxAimed = wto_fire_aux_aim(unit, className, distXZ, slot) slot.turret.lookReason = WTO_LOOK_ENGAGE else wishWorldDir = wto_turret_look_dir(now, muzzlePos, unit.pos, hFwd, slot) diff --git a/game-ai/ground/wto_ai_traverse_common.das b/game-ai/ground/wto_ai_traverse_common.das index d5b99bb..907ccb6 100644 --- a/game-ai/ground/wto_ai_traverse_common.das +++ b/game-ai/ground/wto_ai_traverse_common.das @@ -123,19 +123,25 @@ def public wto_hull_deg_to_world(yawDeg, pitchDeg : float; hullFwd, hullUp, hull let l = length(dir) return l > 1.0e-5 ? (dir / l) : hullFwd -def private wto_step_mounted_yaw(current, desired, step : float; arc : float2) : float - if wto_full_gun_traverse(arc) - return wto_wrap_deg(current + clamp(wto_wrap_deg(desired - current), -step, step)) - let clampedCurrent = clamp(wto_yaw_in_mount_coordinates(current, arc), arc.x, arc.y) - let clampedTarget = clamp(wto_yaw_in_mount_coordinates(desired, arc), arc.x, arc.y) - return clamp(clampedCurrent + clamp(clampedTarget - clampedCurrent, -step, step), arc.x, arc.y) +// A full-traverse command never leads the turret by more than this, so the stock servo always +// takes the short way round; any value below 180 keeps that, it does not set the speed. +let private WTO_SERVO_MAX_LEAD_DEG = 90.0 -def private wto_track_blocked_pitch(wishPitch, wishYaw, cmdYaw, dtStep : float; pitch : float2; var slot : WtoBotSlot&) +// Yaw command for the stock servo: the wished yaw itself, inside the mount's arc. The servo then +// turns at the vehicle's own traverse speed instead of being led one frame's step at a time. +def private wto_servo_yaw(current, desired : float; arc : float2) : float + if wto_full_gun_traverse(arc) + let lead = clamp(wto_wrap_deg(desired - current), -WTO_SERVO_MAX_LEAD_DEG, WTO_SERVO_MAX_LEAD_DEG) + return wto_wrap_deg(current + lead) + return clamp(wto_yaw_in_mount_coordinates(desired, arc), arc.x, arc.y) + +// `atYaw` is where the barrel points now: elevation counts as blocked only once it is there. +def private wto_track_blocked_pitch(wishPitch, wishYaw, atYaw, dtStep : float; pitch : float2; var slot : WtoBotSlot&) assume fc = slot.fire let pitchSpd = abs(fc.curPitchDeg - fc.prevPitchDeg) / dtStep fc.prevPitchDeg = fc.curPitchDeg let align = WTO_AI_FC_BASE_ALIGN_DEG - let aimedYaw = abs(wto_wrap_deg(cmdYaw - wishYaw)) <= align + let aimedYaw = abs(wto_wrap_deg(atYaw - wishYaw)) <= align let outside = wishPitch < pitch.x - align || wishPitch > pitch.y + align fc.pitchAtLimit = aimedYaw && wto_valid_angle_range(pitch) && outside if slot.perceive.hasClearLos && fc.pitchAtLimit && pitchSpd < 0.8 @@ -172,21 +178,19 @@ def public wto_drive_mounted_gun(var unit : Unit?; className : string; dt : floa if !fc.traverse.known return let yaw = fc.traverse.yaw - let maxYawStep = max(24.0, slot.spec.turretYawSpd * 1.1) * dtStep - let cmdYaw = wto_step_mounted_yaw(fc.curYawDeg, wishYawDeg, maxYawStep, yaw) - let maxPitchStep = max(10.0, slot.spec.turretPitchSpd * 1.1) * dtStep - let pitch = wto_gun_pitch_at_yaw(className, triggerNo, weaponIndex, cmdYaw, fc.traverse) - wto_track_blocked_pitch(wishPitchDeg, wishYawDeg, cmdYaw, dtStep, pitch, slot) - turret.yawLim = cmdYaw + // Elevation limits where the barrel is now; they change by sector as the turret turns. + let hereYaw = wto_yaw_in_mount_coordinates(fc.curYawDeg, yaw) + let pitch = wto_gun_pitch_at_yaw(className, triggerNo, weaponIndex, hereYaw, fc.traverse) + wto_track_blocked_pitch(wishPitchDeg, wishYawDeg, fc.curYawDeg, dtStep, pitch, slot) + turret.yawLim = wto_servo_yaw(fc.curYawDeg, wishYawDeg, yaw) if pitch.x <= pitch.y - let pitchDelta = clamp(wishPitchDeg - fc.curPitchDeg, -maxPitchStep, maxPitchStep) - turret.pitchLim = clamp(fc.curPitchDeg + pitchDelta, pitch.x, pitch.y) + turret.pitchLim = clamp(wishPitchDeg, pitch.x, pitch.y) break // Secondary mounts with their own limits can track independently. Coaxial mounts with no // limits follow the main turret through the stock weapon animation. [never_inline] -def public wto_aim_aux_mount(var unit : Unit?; className : string; dt : float; turretNo : int; +def public wto_aim_aux_mount(var unit : Unit?; className : string; turretNo : int; wishDir : float3; var cached : WtoMountFire&) : bool assume turret = unit.weap.turret[turretNo] let triggerNo = int(turret.triggerNo) @@ -199,13 +203,12 @@ def public wto_aim_aux_mount(var unit : Unit?; className : string; dt : float; t var wishYaw = 0.0 var wishPitch = 0.0 wto_world_to_hull_deg(wishDir, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2], wishYaw, wishPitch) - let step = clamp(dt, 0.005, 0.12) - let cmdYaw = wto_step_mounted_yaw(turret.currentState.yaw, wishYaw, step * 24.0, cached.traverse.yaw) - let pitch = wto_gun_pitch_at_yaw(className, triggerNo, weaponIndex, cmdYaw, cached.traverse) - turret.yawLim = cmdYaw + let arc = cached.traverse.yaw + let hereYaw = wto_yaw_in_mount_coordinates(turret.currentState.yaw, arc) + let pitch = wto_gun_pitch_at_yaw(className, triggerNo, weaponIndex, hereYaw, cached.traverse) + turret.yawLim = wto_servo_yaw(turret.currentState.yaw, wishYaw, arc) if pitch.x <= pitch.y - let pitchChange = clamp(wishPitch - turret.currentState.pitch, -step * 10.0, step * 10.0) - turret.pitchLim = clamp(turret.currentState.pitch + pitchChange, pitch.x, pitch.y) + turret.pitchLim = clamp(wishPitch, pitch.x, pitch.y) return true def public wto_apply_weapon_aim(var unit : Unit?; dt : float) From b276e686b0c8fd1877ea4892782a234ced6ed809 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sun, 6 Dec 2026 15:43:04 +0800 Subject: [PATCH 19/19] chore(ground-ai): checkpoint 3d replay and simulator work --- apps/ai-lab/lab.local.example.json | 1 + apps/ai-lab/package.json | 4 +- apps/ai-lab/server/lab-api.ts | 39 +- apps/ai-lab/src/App.tsx | 23 +- apps/ai-lab/src/Map3D.tsx | 179 +++++++ apps/ai-lab/src/MapView.tsx | 87 ---- apps/ai-lab/src/data.ts | 12 +- apps/ai-lab/src/draw.ts | 168 ------- apps/ai-lab/src/frames.ts | 30 +- apps/ai-lab/src/mapLayer.ts | 5 +- apps/ai-lab/src/style.css | 6 +- apps/ai-lab/src/three/cameraRig.ts | 119 +++++ apps/ai-lab/src/three/coords.ts | 18 + apps/ai-lab/src/three/mapMeshes.ts | 134 ++++++ apps/ai-lab/src/three/overlays.ts | 182 +++++++ apps/ai-lab/src/three/tanks.ts | 141 ++++++ apps/ai-lab/src/view.ts | 39 -- game-ai/ground/wto_ai_drive_common.das | 10 +- game-ai/ground/wto_ai_facing_common.das | 1 - game-ai/ground/wto_ai_fire_common.das | 50 +- game-ai/ground/wto_ai_fire_decide_common.das | 61 +++ game-ai/ground/wto_ai_follow_common.das | 11 + game-ai/ground/wto_ai_nav_common.das | 1 - game-ai/ground/wto_ai_runtime.das | 3 +- game-ai/ground/wto_ai_trace_common.das | 18 +- game-ai/ground/wto_ai_types_common.das | 4 + game-ai/ground/wto_ai_unit_pose_common.das | 30 ++ game-ai/ground/wto_ai_world_common.das | 88 +--- .../ground/wto_ai_world_refresh_common.das | 100 ++++ native/wto-ai-sim/build.ps1 | 58 +++ native/wto-ai-sim/module/.das_module | 9 + native/wto-ai-sim/module/.gitignore | 6 + native/wto-ai-sim/module/CMakeLists.txt | 49 ++ native/wto-ai-sim/module/src/sim_geo.cpp | 443 ++++++++++++++++++ native/wto-ai-sim/module/src/sim_geo.h | 42 ++ native/wto-ai-sim/module/src/sim_nav.cpp | 137 ++++++ native/wto-ai-sim/module/src/sim_nav.h | 15 + .../wto-ai-sim/module/src/wto_sim_module.cpp | 93 ++++ native/wto-nav/wto_nav_protocol.c | 247 ++++++++++ native/wto-nav/wto_nav_protocol.h | 49 ++ native/wto-net/build.ps1 | 2 +- native/wto-net/src/local_mp_nav.c | 254 +--------- packages/ground-sim/src/index.ts | 5 + packages/ground-sim/src/map/scene.ts | 214 +++++++++ packages/ground-sim/src/map/wtogeo.ts | 99 ++++ packages/ground-sim/src/trace/parse.ts | 9 + packages/ground-sim/src/trace/types.ts | 6 + 47 files changed, 2613 insertions(+), 688 deletions(-) create mode 100644 apps/ai-lab/src/Map3D.tsx delete mode 100644 apps/ai-lab/src/MapView.tsx delete mode 100644 apps/ai-lab/src/draw.ts create mode 100644 apps/ai-lab/src/three/cameraRig.ts create mode 100644 apps/ai-lab/src/three/coords.ts create mode 100644 apps/ai-lab/src/three/mapMeshes.ts create mode 100644 apps/ai-lab/src/three/overlays.ts create mode 100644 apps/ai-lab/src/three/tanks.ts delete mode 100644 apps/ai-lab/src/view.ts create mode 100644 game-ai/ground/wto_ai_fire_decide_common.das create mode 100644 game-ai/ground/wto_ai_unit_pose_common.das create mode 100644 game-ai/ground/wto_ai_world_refresh_common.das create mode 100644 native/wto-ai-sim/build.ps1 create mode 100644 native/wto-ai-sim/module/.das_module create mode 100644 native/wto-ai-sim/module/.gitignore create mode 100644 native/wto-ai-sim/module/CMakeLists.txt create mode 100644 native/wto-ai-sim/module/src/sim_geo.cpp create mode 100644 native/wto-ai-sim/module/src/sim_geo.h create mode 100644 native/wto-ai-sim/module/src/sim_nav.cpp create mode 100644 native/wto-ai-sim/module/src/sim_nav.h create mode 100644 native/wto-ai-sim/module/src/wto_sim_module.cpp create mode 100644 native/wto-nav/wto_nav_protocol.c create mode 100644 native/wto-nav/wto_nav_protocol.h create mode 100644 packages/ground-sim/src/map/scene.ts create mode 100644 packages/ground-sim/src/map/wtogeo.ts diff --git a/apps/ai-lab/lab.local.example.json b/apps/ai-lab/lab.local.example.json index 8341569..2ef08bd 100644 --- a/apps/ai-lab/lab.local.example.json +++ b/apps/ai-lab/lab.local.example.json @@ -1,5 +1,6 @@ { "mapsDir": "J:/GAME/WTOfflineProject-tank-ai/build/nav-stage2-fix/maps", + "geoDir": "J:/GAME/WTOfflineProject-tank-ai/build/nav-stage2-fix/work", "logsDir": "J:/GAME/WTLab/client-2.61.0.58/.game_logs", "python": "J:/GAME/WTOfflineProject/.venv/Scripts/python.exe" } diff --git a/apps/ai-lab/package.json b/apps/ai-lab/package.json index 0330bcb..19efe18 100644 --- a/apps/ai-lab/package.json +++ b/apps/ai-lab/package.json @@ -11,11 +11,13 @@ "dependencies": { "@wto/ground-sim": "*", "react": "^19.2.8", - "react-dom": "^19.2.8" + "react-dom": "^19.2.8", + "three": "^0.187.0" }, "devDependencies": { "@types/react": "^19.2.17", "@types/react-dom": "^19.2.3", + "@types/three": "^0.187.0", "@vitejs/plugin-react": "^5.2.0", "vite": "^7.3.6" } diff --git a/apps/ai-lab/server/lab-api.ts b/apps/ai-lab/server/lab-api.ts index 78c31db..f808bf4 100644 --- a/apps/ai-lab/server/lab-api.ts +++ b/apps/ai-lab/server/lab-api.ts @@ -4,17 +4,22 @@ * GET /api/maps/file?name= a pack or POI file of mapsDir * GET /api/logs game logs (.clog) in logsDir, newest first * GET /api/logs/text?name= a log decrypted with wtotools (cached until the log changes) + * GET /api/scene?name= the 3D map (.wtoscene) of a level, built from its .wtogeo in geoDir + * (cached until the geometry changes) * Paths come from lab.local.json next to this app (see lab.local.example.json). */ import { execFile } from 'node:child_process'; -import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync } from 'node:fs'; +import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'; import type { ServerResponse } from 'node:http'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; +import { buildMapScene, encodeMapScene, readGeo } from '@wto/ground-sim'; import type { Connect, Plugin } from 'vite'; interface LabConfig { readonly mapsDir: string; + /** Where the navigation bake left the levels' .wtogeo geometry. */ + readonly geoDir: string; readonly logsDir: string; readonly python: string; } @@ -27,8 +32,10 @@ function loadConfig(): LabConfig { const file = path.join(APP_DIR, 'lab.local.json'); const raw = existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as Record) : {}; const str = (key: string, fallback: string): string => (typeof raw[key] === 'string' ? (raw[key] as string) : fallback); + const mapsDir = str('mapsDir', path.resolve(APP_DIR, '../../build/nav-stage2-fix/maps')); return { - mapsDir: str('mapsDir', path.resolve(APP_DIR, '../../build/nav-stage2-fix/maps')), + mapsDir, + geoDir: str('geoDir', path.join(mapsDir, '..', 'work')), logsDir: str('logsDir', ''), python: str('python', 'python'), }; @@ -46,13 +53,17 @@ function sendFile(res: ServerResponse, file: string, type: string): void { createReadStream(file).pipe(res); } -function listMaps(cfg: LabConfig): { level: string; pois: boolean }[] { +function listMaps(cfg: LabConfig): { level: string; pois: boolean; scene: boolean }[] { if (!existsSync(cfg.mapsDir)) return []; return readdirSync(cfg.mapsDir) .filter((f) => f.endsWith('.wtonav')) .map((f) => { const level = f.slice(0, -'.wtonav'.length); - return { level, pois: existsSync(path.join(cfg.mapsDir, `${level}.pois.json`)) }; + return { + level, + pois: existsSync(path.join(cfg.mapsDir, `${level}.pois.json`)), + scene: existsSync(path.join(cfg.geoDir, `${level}.wtogeo`)), + }; }); } @@ -81,12 +92,30 @@ function decryptLog(cfg: LabConfig, name: string): Promise { }); } +/** Builds the level's 3D map into the cache unless the cached one is newer than its geometry. */ +function sceneFile(cfg: LabConfig, level: string): string | undefined { + const geo = path.join(cfg.geoDir, `${level}.wtogeo`); + if (!existsSync(geo)) return undefined; + const out = path.join(CACHE_DIR, `${level}.wtoscene`); + if (existsSync(out) && statSync(out).mtimeMs >= statSync(geo).mtimeMs) return out; + mkdirSync(CACHE_DIR, { recursive: true }); + writeFileSync(out, encodeMapScene(buildMapScene(readGeo(readFileSync(geo))))); + return out; +} + async function handle(cfg: LabConfig, url: URL, res: ServerResponse): Promise { const name = url.searchParams.get('name') ?? ''; if (url.pathname === '/api/maps') { sendJson(res, 200, listMaps(cfg)); return true; } if (url.pathname === '/api/logs') { sendJson(res, 200, listLogs(cfg)); return true; } - if (url.pathname !== '/api/maps/file' && url.pathname !== '/api/logs/text') return false; + const known = ['/api/maps/file', '/api/logs/text', '/api/scene']; + if (!known.includes(url.pathname)) return false; if (!SAFE_NAME.test(name)) { sendJson(res, 400, { error: 'bad file name' }); return true; } + if (url.pathname === '/api/scene') { + const file = sceneFile(cfg, name); + if (file === undefined) sendJson(res, 404, { error: `no ${name}.wtogeo in ${cfg.geoDir}` }); + else sendFile(res, file, 'application/octet-stream'); + return true; + } if (url.pathname === '/api/maps/file') { const file = path.join(cfg.mapsDir, name); if (!existsSync(file)) sendJson(res, 404, { error: `no ${name} in ${cfg.mapsDir}` }); diff --git a/apps/ai-lab/src/App.tsx b/apps/ai-lab/src/App.tsx index 161f5cd..c20616e 100644 --- a/apps/ai-lab/src/App.tsx +++ b/apps/ai-lab/src/App.tsx @@ -2,17 +2,20 @@ import type { TraceBattle } from '@wto/ground-sim'; import { useEffect, useMemo, useState } from 'react'; import { fetchLogs, fetchMaps, loadLog, loadMap, type LogEntry, type MapData, type MapEntry } from './data.ts'; -import type { Layers } from './draw.ts'; import { sceneAt } from './frames.ts'; import { Inspector } from './Inspector.tsx'; +import { Map3D, type MapLook } from './Map3D.tsx'; import { buildMapLayer } from './mapLayer.ts'; -import { MapView } from './MapView.tsx'; +import type { ViewMode } from './three/cameraRig.ts'; +import type { Layers } from './three/overlays.ts'; import { Timeline } from './Timeline.tsx'; const LAYER_LABELS: Readonly> = { goals: '目标点', links: '目标连线', cones: '炮塔视野', labels: '标签', events: '开火与受击', }; +const VIEW_LABELS: Readonly> = { top: '俯视', free: '自由', follow: '跟随选中车', gun: '炮口视角' }; + function logLabel(l: LogEntry): string { const when = new Date(l.mtime).toLocaleString(); return `${l.name}(${(l.size / 1e6).toFixed(1)} MB,${when})`; @@ -27,6 +30,7 @@ export function App(): React.JSX.Element { const [mapData, setMapData] = useState(undefined); const [exposure, setExposure] = useState(false); const [covers, setCovers] = useState(false); + const [look, setLook] = useState({ view: 'top', navImage: true, objects: true, crushable: true }); const [layers, setLayers] = useState({ goals: true, links: true, cones: false, labels: false, events: true }); const [t, setT] = useState(0); const [playing, setPlaying] = useState(false); @@ -75,12 +79,6 @@ export function App(): React.JSX.Element { () => (mapData === undefined ? undefined : buildMapLayer(mapData.pack, { tier: 1, exposure, covers })), [mapData, exposure, covers], ); - const bounds = useMemo((): readonly [number, number, number, number] | undefined => { - if (mapData === undefined) return undefined; - const p = mapData.pois; - if (p !== undefined) return [p.boundsMin[0], p.boundsMin[1], p.boundsMax[0], p.boundsMax[1]]; - return [mapData.pack.header.bmin[0], mapData.pack.header.bmin[2], mapData.pack.header.bmax[0], mapData.pack.header.bmax[2]]; - }, [mapData]); useEffect(() => { if (!playing || battle === undefined) return; @@ -121,13 +119,20 @@ export function App(): React.JSX.Element { {LAYER_LABELS[k]} ))} + + + + {status !== '' && {status}} {battle !== undefined && battle.frames.length === 0 && 这一局没有轨迹(游戏里没开 diagnostics.trace)。}
- + {battle !== undefined && }
{battle !== undefined && ( diff --git a/apps/ai-lab/src/Map3D.tsx b/apps/ai-lab/src/Map3D.tsx new file mode 100644 index 0000000..dfc8082 --- /dev/null +++ b/apps/ai-lab/src/Map3D.tsx @@ -0,0 +1,179 @@ +/** + * The battle in 3D: terrain and object collision shapes of the level, vehicles as simple shapes, + * and the replay's lines and markers. Left drag pans, right drag turns (except top-down), wheel + * zooms; a click on a vehicle selects it. + */ +import { BEHAVIOR_NAMES, type MapScene, type TraceBattle } from '@wto/ground-sim'; +import { useEffect, useRef } from 'react'; +import { AmbientLight, Color, DirectionalLight, HemisphereLight, Raycaster, Scene, Vector2, WebGLRenderer } from 'three'; +import { CSS2DRenderer } from 'three/addons/renderers/CSS2DRenderer.js'; +import type { SceneAt, UnitAt } from './frames.ts'; +import type { MapLayer } from './mapLayer.ts'; +import { CameraRig, type ViewMode } from './three/cameraRig.ts'; +import { buildMapMeshes, setTerrainImage, type MapMeshes } from './three/mapMeshes.ts'; +import { Overlays, type Layers } from './three/overlays.ts'; +import { TankPool } from './three/tanks.ts'; + +export interface MapLook { + readonly view: ViewMode; + /** Drape the navigation mesh image over the terrain instead of height colours. */ + readonly navImage: boolean; + readonly objects: boolean; + readonly crushable: boolean; +} + +interface Props { + readonly mapScene: MapScene | undefined; + readonly nav: MapLayer | undefined; + readonly battle: TraceBattle | undefined; + readonly scene: SceneAt | undefined; + readonly selected: string | undefined; + readonly layers: Layers; + readonly look: MapLook; + readonly onSelect: (eid: string | undefined) => void; +} + +interface World { + readonly renderer: WebGLRenderer; + readonly labels: CSS2DRenderer; + readonly scene: Scene; + readonly rig: CameraRig; + map: MapMeshes | undefined; + tanks: TankPool; + overlays: Overlays; + selected: string | undefined; +} + +const CRUSHABLE_KIND = 3; +const CLICK_PX = 4; + +function labelOf(u: UnitAt): string { + const name = u.bot !== undefined ? (BEHAVIOR_NAMES[u.bot.behavior] ?? '?') : u.unit.human ? 'player' : ''; + return `${u.unit.eid.replace(/^0x/, '')} ${name}`; +} + +function createWorld(host: HTMLDivElement): World { + const renderer = new WebGLRenderer({ antialias: true, logarithmicDepthBuffer: true }); + renderer.setPixelRatio(window.devicePixelRatio); + host.appendChild(renderer.domElement); + const labels = new CSS2DRenderer(); + labels.domElement.className = 'labels3d'; + host.appendChild(labels.domElement); + const scene = new Scene(); + scene.background = new Color(0x0b0c0d); + scene.add(new HemisphereLight(0xdfe8ff, 0x3a3326, 1.4), new AmbientLight(0xffffff, 0.25)); + const sun = new DirectionalLight(0xffffff, 1.6); + sun.position.set(0.5, 1, 0.3); + scene.add(sun); + const tanks = new TankPool(undefined); + const overlays = new Overlays(tanks); + scene.add(tanks.group, overlays.group); + return { renderer, labels, scene, rig: new CameraRig(renderer.domElement), map: undefined, tanks, overlays, selected: undefined }; +} + +function replaceMap(w: World, mapScene: MapScene | undefined, nav: MapLayer | undefined): void { + if (w.map !== undefined) { w.scene.remove(w.map.group); w.map.dispose(); } + w.scene.remove(w.tanks.group, w.overlays.group); + w.tanks.dispose(); + w.overlays.dispose(); + w.map = mapScene === undefined ? undefined : buildMapMeshes(mapScene, nav); + w.tanks = new TankPool(mapScene?.terrain); + w.overlays = new Overlays(w.tanks); + if (w.map !== undefined) w.scene.add(w.map.group); + w.scene.add(w.tanks.group, w.overlays.group); + if (mapScene !== undefined) { + const t = mapScene.terrain; + let sum = 0; + for (const h of t.heights) sum += h; + w.rig.fit(mapScene.boundsMin[0], mapScene.boundsMin[1], mapScene.boundsMax[0], mapScene.boundsMax[1], sum / Math.max(1, t.heights.length)); + } +} + +export function Map3D({ mapScene, nav, battle, scene, selected, layers, look, onSelect }: Props): React.JSX.Element { + const hostRef = useRef(null); + const worldRef = useRef(undefined); + const onSelectRef = useRef(onSelect); + onSelectRef.current = onSelect; + + useEffect(() => { + const host = hostRef.current; + if (host === null) return; + const w = createWorld(host); + worldRef.current = w; + const resize = (): void => { + const r = host.getBoundingClientRect(); + w.renderer.setSize(r.width, r.height); + w.labels.setSize(r.width, r.height); + w.rig.resize(r.width, r.height); + }; + const obs = new ResizeObserver(resize); + obs.observe(host); + resize(); + w.renderer.setAnimationLoop(() => { + w.rig.tick(w.selected === undefined ? undefined : w.tanks.get(w.selected)); + w.renderer.render(w.scene, w.rig.camera); + w.labels.render(w.scene, w.rig.camera); + }); + const down = new Vector2(); + const el = w.renderer.domElement; + const onDown = (e: PointerEvent): void => { down.set(e.clientX, e.clientY); }; + const onUp = (e: PointerEvent): void => { + if (e.button !== 0 || Math.hypot(e.clientX - down.x, e.clientY - down.y) > CLICK_PX) return; + const r = el.getBoundingClientRect(); + const ray = new Raycaster(); + ray.setFromCamera(new Vector2(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1), w.rig.camera); + const hit = ray.intersectObjects(w.tanks.pickables(), false)[0]; + onSelectRef.current(hit?.object.userData['eid'] as string | undefined); + }; + el.addEventListener('pointerdown', onDown); + el.addEventListener('pointerup', onUp); + return () => { + obs.disconnect(); + el.removeEventListener('pointerdown', onDown); + el.removeEventListener('pointerup', onUp); + w.renderer.setAnimationLoop(null); + replaceMap(w, undefined, undefined); + w.rig.dispose(); + w.renderer.dispose(); + host.replaceChildren(); + worldRef.current = undefined; + }; + }, []); + + useEffect(() => { + const w = worldRef.current; + if (w !== undefined) replaceMap(w, mapScene, nav); + // The navigation image is applied by the effect below; only a new level rebuilds the map. + }, [mapScene]); + + useEffect(() => { + const w = worldRef.current; + if (w?.map !== undefined) setTerrainImage(w.map, look.navImage ? nav : undefined); + }, [nav, look.navImage, mapScene]); + + useEffect(() => { + const w = worldRef.current; + if (w?.map === undefined) return; + w.map.kinds.forEach((g, k) => { g.visible = look.objects && (k !== CRUSHABLE_KIND || look.crushable); }); + }, [look.objects, look.crushable, mapScene]); + + useEffect(() => { + worldRef.current?.rig.setMode(look.view); + }, [look.view]); + + useEffect(() => { + const w = worldRef.current; + if (w === undefined) return; + w.selected = selected; + w.rig.refollow(); + }, [selected]); + + useEffect(() => { + const w = worldRef.current; + if (w === undefined || battle === undefined || scene === undefined) return; + w.tanks.update(scene.units, selected, (u) => (layers.labels && u.unit.alive ? labelOf(u) : undefined)); + w.overlays.update(battle, scene, layers); + }, [battle, scene, selected, layers, mapScene]); + + return
; +} diff --git a/apps/ai-lab/src/MapView.tsx b/apps/ai-lab/src/MapView.tsx deleted file mode 100644 index 14e3b67..0000000 --- a/apps/ai-lab/src/MapView.tsx +++ /dev/null @@ -1,87 +0,0 @@ -/** The battle map: drag to pan, wheel to zoom, click a vehicle to select it. */ -import type { TraceBattle } from '@wto/ground-sim'; -import { useEffect, useRef, useState } from 'react'; -import { drawScene, type Layers } from './draw.ts'; -import type { SceneAt } from './frames.ts'; -import type { MapLayer } from './mapLayer.ts'; -import { fitView, toScreen, zoomAt, type View } from './view.ts'; - -interface Props { - readonly map: MapLayer | undefined; - readonly bounds: readonly [number, number, number, number] | undefined; - readonly battle: TraceBattle | undefined; - readonly scene: SceneAt | undefined; - readonly selected: string | undefined; - readonly layers: Layers; - readonly onSelect: (eid: string | undefined) => void; -} - -const PICK_PX = 14; - -export function MapView({ map, bounds, battle, scene, selected, layers, onSelect }: Props): React.JSX.Element { - const canvasRef = useRef(null); - const [view, setView] = useState({ cx: 0, cz: 0, scale: 1, w: 800, h: 600 }); - const drag = useRef<{ x: number; y: number; moved: boolean } | undefined>(undefined); - - useEffect(() => { - const canvas = canvasRef.current; - if (canvas === null) return; - const resize = (): void => { - const r = canvas.getBoundingClientRect(); - canvas.width = Math.max(1, Math.floor(r.width)); - canvas.height = Math.max(1, Math.floor(r.height)); - setView((v) => ({ ...v, w: canvas.width, h: canvas.height })); - }; - const obs = new ResizeObserver(resize); - obs.observe(canvas); - resize(); - return () => obs.disconnect(); - }, []); - - useEffect(() => { - if (bounds === undefined) return; - setView((v) => fitView(bounds[0], bounds[1], bounds[2], bounds[3], v.w, v.h)); - }, [bounds]); - - useEffect(() => { - const ctx = canvasRef.current?.getContext('2d'); - if (ctx === undefined || ctx === null) return; - drawScene(ctx, view, map, battle, scene, selected, layers); - }, [view, map, battle, scene, selected, layers]); - - const pick = (sx: number, sy: number): string | undefined => { - let best: string | undefined; - let bestD = PICK_PX * PICK_PX; - for (const u of scene?.units.values() ?? []) { - const [x, y] = toScreen(view, u.x, u.z); - const d = (x - sx) ** 2 + (y - sy) ** 2; - if (d < bestD) { bestD = d; best = u.unit.eid; } - } - return best; - }; - - return ( - setView((v) => zoomAt(v, e.nativeEvent.offsetX, e.nativeEvent.offsetY, e.deltaY < 0 ? 1.2 : 1 / 1.2))} - onMouseDown={(e) => { drag.current = { x: e.clientX, y: e.clientY, moved: false }; }} - onMouseMove={(e) => { - const d = drag.current; - if (d === undefined) return; - const dx = e.clientX - d.x; - const dy = e.clientY - d.y; - if (Math.abs(dx) + Math.abs(dy) > 2) d.moved = true; - d.x = e.clientX; - d.y = e.clientY; - setView((v) => ({ ...v, cx: v.cx - dx / v.scale, cz: v.cz + dy / v.scale })); - }} - onMouseUp={(e) => { - const d = drag.current; - drag.current = undefined; - if (d !== undefined && !d.moved) onSelect(pick(e.nativeEvent.offsetX, e.nativeEvent.offsetY)); - }} - onMouseLeave={() => { drag.current = undefined; }} - /> - ); -} diff --git a/apps/ai-lab/src/data.ts b/apps/ai-lab/src/data.ts index 7bd8a73..cfee8cc 100644 --- a/apps/ai-lab/src/data.ts +++ b/apps/ai-lab/src/data.ts @@ -1,5 +1,7 @@ /** Loading maps and logs through the lab's dev-server API (server/lab-api.ts). */ -import { parsePois, parseTraceLog, readNavPack, type MapPois, type NavPack, type TraceBattle } from '@wto/ground-sim'; +import { + decodeMapScene, parsePois, parseTraceLog, readNavPack, type MapPois, type MapScene, type NavPack, type TraceBattle, +} from '@wto/ground-sim'; export interface LogEntry { readonly name: string; @@ -10,11 +12,14 @@ export interface LogEntry { export interface MapEntry { readonly level: string; readonly pois: boolean; + /** The level's geometry is there, so it has a 3D map. */ + readonly scene: boolean; } export interface MapData { readonly pack: NavPack; readonly pois: MapPois | undefined; + readonly scene: MapScene | undefined; } async function get(url: string): Promise { @@ -44,5 +49,8 @@ export async function loadMap(entry: MapEntry): Promise { const pois = entry.pois ? parsePois(await (await get(`/api/maps/file?name=${encodeURIComponent(`${entry.level}.pois.json`)}`)).text()) : undefined; - return { pack: readNavPack(bytes), pois }; + const scene = entry.scene + ? decodeMapScene(new Uint8Array(await (await get(`/api/scene?name=${encodeURIComponent(entry.level)}`)).arrayBuffer())) + : undefined; + return { pack: readNavPack(bytes), pois, scene }; } diff --git a/apps/ai-lab/src/draw.ts b/apps/ai-lab/src/draw.ts deleted file mode 100644 index e1313e4..0000000 --- a/apps/ai-lab/src/draw.ts +++ /dev/null @@ -1,168 +0,0 @@ -/** Everything drawn over the static map for one moment of the replay. */ -import { BEHAVIOR_NAMES, type TraceBattle } from '@wto/ground-sim'; -import { eventsBetween, type SceneAt, type UnitAt } from './frames.ts'; -import type { MapLayer } from './mapLayer.ts'; -import { screenDir, toScreen, type View } from './view.ts'; - -export interface Layers { - readonly goals: boolean; - readonly links: boolean; - readonly cones: boolean; - readonly labels: boolean; - readonly events: boolean; -} - -export const ARMY_COLORS: Readonly> = { 1: '#4aa3ff', 2: '#ff5c5c' }; - -const GUN_FOV_HALF_DEG = 30; -const CONE_M = 120; -const EVENT_WINDOW_SEC = 2; - -function line(ctx: CanvasRenderingContext2D, ax: number, ay: number, bx: number, by: number): void { - ctx.beginPath(); - ctx.moveTo(ax, ay); - ctx.lineTo(bx, by); - ctx.stroke(); -} - -function drawHull(ctx: CanvasRenderingContext2D, v: View, u: UnitAt, selected: boolean): void { - const [sx, sy] = toScreen(v, u.x, u.z); - const [dx, dy] = screenDir(u.yaw); - const len = Math.max(5, (u.unit.light ? 3 : 3.6) * v.scale); - const wid = Math.max(3, 1.7 * v.scale); - ctx.save(); - ctx.translate(sx, sy); - ctx.rotate(Math.atan2(dy, dx)); - ctx.fillStyle = u.unit.alive ? (ARMY_COLORS[u.unit.army] ?? '#ccc') : '#555'; - ctx.fillRect(-len, -wid, len * 2, wid * 2); - ctx.fillStyle = '#fff'; - ctx.fillRect(len * 0.6, -wid * 0.5, len * 0.4, wid); - if (u.unit.human || selected) { - ctx.strokeStyle = selected ? '#ffe14a' : '#fff'; - ctx.lineWidth = selected ? 3 : 1.5; - ctx.strokeRect(-len - 2, -wid - 2, len * 2 + 4, wid * 2 + 4); - } - ctx.restore(); -} - -function drawBotIntent(ctx: CanvasRenderingContext2D, v: View, u: UnitAt, scene: SceneAt, layers: Layers): void { - const bot = u.bot; - if (bot === undefined || !u.unit.alive) return; - const [sx, sy] = toScreen(v, u.x, u.z); - if (layers.goals && bot.hasOrder) { - const [gx, gy] = toScreen(v, bot.goalX, bot.goalZ); - ctx.setLineDash([4, 6]); - ctx.strokeStyle = 'rgba(255,255,255,0.25)'; - ctx.lineWidth = 1; - line(ctx, sx, sy, gx, gy); - ctx.setLineDash([]); - } - if (bot.gunYaw !== undefined) { - const [dx, dy] = screenDir(bot.gunYaw); - if (layers.cones) { - const r = CONE_M * v.scale; - const a = Math.atan2(dy, dx); - const half = (GUN_FOV_HALF_DEG * Math.PI) / 180; - ctx.fillStyle = 'rgba(255,255,200,0.07)'; - ctx.beginPath(); - ctx.moveTo(sx, sy); - ctx.arc(sx, sy, r, a - half, a + half); - ctx.closePath(); - ctx.fill(); - } - const gl = Math.max(14, 8 * v.scale); - ctx.strokeStyle = '#fff'; - ctx.lineWidth = 2; - line(ctx, sx, sy, sx + dx * gl, sy + dy * gl); - } - const [wx, wy] = screenDir(bot.wishYaw); - const wl = Math.max(22, 14 * v.scale); - ctx.setLineDash([2, 3]); - ctx.strokeStyle = 'rgba(255,225,74,0.8)'; - ctx.lineWidth = 1; - line(ctx, sx, sy, sx + wx * wl, sy + wy * wl); - ctx.setLineDash([]); - if (!layers.links) return; - const target = scene.units.get(bot.target); - if (target !== undefined && bot.target !== '0') { - const [tx, ty] = toScreen(v, target.x, target.z); - ctx.strokeStyle = bot.targetInSight ? 'rgba(255,70,70,0.85)' : 'rgba(255,70,70,0.3)'; - ctx.lineWidth = 1.5; - line(ctx, sx, sy, tx, ty); - } - const look = scene.units.get(bot.lookAt); - if (look !== undefined && bot.lookAt !== bot.target) { - const [lx, ly] = toScreen(v, look.x, look.z); - ctx.strokeStyle = 'rgba(255,160,40,0.85)'; - ctx.lineWidth = 1.5; - line(ctx, sx, sy, lx, ly); - } -} - -function drawLabel(ctx: CanvasRenderingContext2D, v: View, u: UnitAt): void { - const [sx, sy] = toScreen(v, u.x, u.z); - const name = u.bot !== undefined ? (BEHAVIOR_NAMES[u.bot.behavior] ?? '?') : u.unit.human ? 'player' : ''; - ctx.fillStyle = 'rgba(255,255,255,0.85)'; - ctx.font = '11px sans-serif'; - ctx.fillText(`${u.unit.eid.replace(/^0x/, '')} ${name}`, sx + 8, sy - 8); -} - -function drawEvents(ctx: CanvasRenderingContext2D, v: View, battle: TraceBattle, scene: SceneAt): void { - for (const e of eventsBetween(battle, scene.t - EVENT_WINDOW_SEC, scene.t)) { - const fade = 1 - (scene.t - e.t) / EVENT_WINDOW_SEC; - if (e.kind === 'SHOT' && e.eid !== undefined) { - const from = scene.units.get(e.eid); - const to = scene.units.get(e.fields['tgt'] ?? ''); - if (from === undefined || to === undefined) continue; - const [ax, ay] = toScreen(v, from.x, from.z); - const [bx, by] = toScreen(v, to.x, to.z); - ctx.strokeStyle = `rgba(255,255,120,${fade})`; - ctx.lineWidth = 2; - line(ctx, ax, ay, bx, by); - } else if (e.kind === 'HIT') { - const [hx, hy] = toScreen(v, Number(e.fields['x']), Number(e.fields['z'])); - ctx.fillStyle = e.fields['drop'] === '1' ? `rgba(255,60,60,${fade})` : `rgba(200,200,200,${fade})`; - ctx.beginPath(); - ctx.arc(hx, hy, 4, 0, Math.PI * 2); - ctx.fill(); - } - } -} - -function drawDeaths(ctx: CanvasRenderingContext2D, v: View, battle: TraceBattle, t: number): void { - ctx.lineWidth = 2; - for (const e of eventsBetween(battle, battle.startT, t)) { - if (e.kind !== 'DEATH') continue; - const [x, y] = toScreen(v, Number(e.fields['x']), Number(e.fields['z'])); - ctx.strokeStyle = e.fields['army'] === '1' ? 'rgba(74,163,255,0.6)' : 'rgba(255,92,92,0.6)'; - line(ctx, x - 5, y - 5, x + 5, y + 5); - line(ctx, x - 5, y + 5, x + 5, y - 5); - } -} - -export function drawScene(ctx: CanvasRenderingContext2D, v: View, map: MapLayer | undefined, battle: TraceBattle | undefined, - scene: SceneAt | undefined, selected: string | undefined, layers: Layers): void { - ctx.fillStyle = '#0b0c0d'; - ctx.fillRect(0, 0, v.w, v.h); - if (map !== undefined) { - const [mx, my] = toScreen(v, map.x0, map.z1); - const k = v.scale / map.pxPerM; - ctx.imageSmoothingEnabled = k < 1; - ctx.drawImage(map.canvas, mx, my, map.canvas.width * k, map.canvas.height * k); - } - if (battle === undefined || scene === undefined) return; - for (const cap of scene.caps) { - const [cx, cy] = toScreen(v, cap.x, cap.z); - ctx.strokeStyle = ARMY_COLORS[cap.owner] ?? '#ddd'; - ctx.lineWidth = 2; - ctx.beginPath(); - ctx.arc(cx, cy, Math.max(4, cap.r * v.scale), 0, Math.PI * 2); - ctx.stroke(); - } - drawDeaths(ctx, v, battle, scene.t); - const units = [...scene.units.values()]; - for (const u of units) drawBotIntent(ctx, v, u, scene, layers); - if (layers.events) drawEvents(ctx, v, battle, scene); - for (const u of units) drawHull(ctx, v, u, u.unit.eid === selected); - if (layers.labels) for (const u of units) if (u.unit.alive) drawLabel(ctx, v, u); -} diff --git a/apps/ai-lab/src/frames.ts b/apps/ai-lab/src/frames.ts index ce5f04f..09fa89b 100644 --- a/apps/ai-lab/src/frames.ts +++ b/apps/ai-lab/src/frames.ts @@ -3,10 +3,16 @@ import type { BotSample, CapSample, TraceBattle, TraceEvent, UnitSample } from ' export interface UnitAt { readonly unit: UnitSample; - /** Interpolated position and heading. */ + /** Interpolated position, hull heading, pitch and roll. */ readonly x: number; + readonly y: number; readonly z: number; readonly yaw: number; + readonly hullPitch: number; + readonly hullRoll: number; + /** Interpolated gun world yaw and pitch; from the bot line, or the hull, when the unit line has none. */ + readonly gunYaw: number; + readonly gunPitch: number; /** Decision state of the sample at or before the time; undefined for players. */ readonly bot: BotSample | undefined; } @@ -34,6 +40,14 @@ function lerpYaw(a: number, b: number, k: number): number { return a + d * k; } +function lerp(a: number, b: number | undefined, k: number): number { + return a + ((b ?? a) - a) * k; +} + +function gunOf(u: UnitSample, bot: BotSample | undefined): [number, number] { + return [u.gunYaw ?? bot?.gunYaw ?? u.yaw, u.gunPitch ?? 0]; +} + export function sceneAt(battle: TraceBattle, t: number): SceneAt { const i = Math.max(0, frameIndexAt(battle, t)); const a = battle.frames[i]; @@ -44,12 +58,20 @@ export function sceneAt(battle: TraceBattle, t: number): SceneAt { for (const [eid, ua] of a.units) { const ub = b?.units.get(eid); const move = ub !== undefined && ua.alive && ub.alive ? k : 0; + const bot = a.bots.get(eid); + const [gyA, gpA] = gunOf(ua, bot); + const [gyB, gpB] = ub !== undefined ? gunOf(ub, b?.bots.get(eid)) : [gyA, gpA]; units.set(eid, { unit: ua, - x: ua.x + ((ub?.x ?? ua.x) - ua.x) * move, - z: ua.z + ((ub?.z ?? ua.z) - ua.z) * move, + x: lerp(ua.x, ub?.x, move), + y: lerp(ua.y, ub?.y, move), + z: lerp(ua.z, ub?.z, move), yaw: lerpYaw(ua.yaw, ub?.yaw ?? ua.yaw, move), - bot: a.bots.get(eid), + hullPitch: lerp(ua.hullPitch ?? 0, ub?.hullPitch, move), + hullRoll: lerp(ua.hullRoll ?? 0, ub?.hullRoll, move), + gunYaw: lerpYaw(gyA, gyB, move), + gunPitch: lerp(gpA, gpB, move), + bot, }); } return { t, units, caps: a.caps }; diff --git a/apps/ai-lab/src/mapLayer.ts b/apps/ai-lab/src/mapLayer.ts index de2a125..2c40b5a 100644 --- a/apps/ai-lab/src/mapLayer.ts +++ b/apps/ai-lab/src/mapLayer.ts @@ -1,5 +1,5 @@ /** - * The static map drawn once into an offscreen canvas: walkable polygons of one mesh tier coloured + * The navigation image draped over the 3D terrain, drawn once into an offscreen canvas: walkable polygons of one mesh tier coloured * by surface, optionally the tactical grid's exposure and the baked cover points. */ import { NAV_AREA_NAMES, type NavPack } from '@wto/ground-sim'; @@ -33,7 +33,8 @@ export function buildMapLayer(pack: NavPack, opts: MapLayerOptions): MapLayer { canvas.height = Math.ceil((z1 - z0) * pxPerM); const ctx = canvas.getContext('2d'); if (ctx === null) return { canvas, x0, z1, pxPerM }; - ctx.fillStyle = '#121416'; + // Off the mesh (buildings, steep or blocked ground) when draped over the 3D terrain. + ctx.fillStyle = '#55584f'; ctx.fillRect(0, 0, canvas.width, canvas.height); const tier = pack.tiers[opts.tier] ?? pack.tiers[1]; if (tier !== undefined) { diff --git a/apps/ai-lab/src/style.css b/apps/ai-lab/src/style.css index 7e1c828..f439f6d 100644 --- a/apps/ai-lab/src/style.css +++ b/apps/ai-lab/src/style.css @@ -6,7 +6,11 @@ header select { max-width: 420px; } header label { display: inline-flex; align-items: center; gap: 3px; } .status { color: #ffb74d; } main { flex: 1; display: flex; min-height: 0; } -canvas.map { flex: 1; min-width: 0; height: 100%; cursor: grab; display: block; } +.map3d { flex: 1; min-width: 0; height: 100%; position: relative; overflow: hidden; } +.map3d canvas { display: block; } +.labels3d { position: absolute; inset: 0; pointer-events: none; } +.tank-label { color: rgba(255,255,255,0.9); font-size: 11px; text-shadow: 0 0 3px #000; white-space: nowrap; } +.tank-label.human { color: #ffe14a; } .inspector { width: 360px; overflow-y: auto; padding: 8px 10px; background: #121416; border-left: 1px solid #2a2d30; } .inspector table { width: 100%; border-collapse: collapse; } .inspector th { text-align: left; color: #999; font-weight: normal; padding: 2px 8px 2px 0; white-space: nowrap; vertical-align: top; } diff --git a/apps/ai-lab/src/three/cameraRig.ts b/apps/ai-lab/src/three/cameraRig.ts new file mode 100644 index 0000000..20f4b99 --- /dev/null +++ b/apps/ai-lab/src/three/cameraRig.ts @@ -0,0 +1,119 @@ +/** + * The 3D view's cameras: a top-down orthographic map view (world +z up the screen, like the old + * flat map), a free perspective view, a view that follows the selected vehicle, and a view out of + * its muzzle along the barrel. + */ +import { OrthographicCamera, PerspectiveCamera, Quaternion, Vector3, type Camera } from 'three'; +import { MapControls } from 'three/addons/controls/MapControls.js'; +import type { Tank } from './tanks.ts'; + +export type ViewMode = 'top' | 'free' | 'follow' | 'gun'; + +const TOP_HEIGHT = 3000; +/** Top-down camera sits this far south of its target, so the controls keep north up. */ +const TOP_SOUTH = 0.01; +const FREE_MAX_POLAR = Math.PI * 0.49; + +export class CameraRig { + readonly persp = new PerspectiveCamera(50, 1, 0.5, 20000); + readonly ortho = new OrthographicCamera(-1, 1, 1, -1, 1, 10000); + readonly controls: MapControls; + private mode: ViewMode = 'top'; + private aspect = 1; + private readonly lastFollow = new Vector3(); + private following = false; + + constructor(dom: HTMLElement) { + this.controls = new MapControls(this.ortho, dom); + this.controls.enableDamping = true; + this.controls.dampingFactor = 0.15; + this.controls.screenSpacePanning = true; + this.limitTilt(); + } + + /** Top-down stays straight down; the other views may tilt down to just above the horizon. */ + private limitTilt(): void { + this.controls.maxPolarAngle = this.mode === 'top' ? 0 : FREE_MAX_POLAR; + } + + get camera(): Camera { + return this.mode === 'top' ? this.ortho : this.persp; + } + + resize(w: number, h: number): void { + this.aspect = w / Math.max(1, h); + this.persp.aspect = this.aspect; + this.persp.updateProjectionMatrix(); + const half = (this.ortho.top - this.ortho.bottom) / 2; + this.ortho.left = -half * this.aspect; + this.ortho.right = half * this.aspect; + this.ortho.updateProjectionMatrix(); + } + + /** Frames the world rectangle (x, z) in both cameras. */ + fit(minX: number, minZ: number, maxX: number, maxZ: number, groundY: number): void { + const cx = (minX + maxX) / 2; + const cz = -(minZ + maxZ) / 2; + const half = (Math.max((maxX - minX) / this.aspect, maxZ - minZ) / 2) * 1.05; + Object.assign(this.ortho, { left: -half * this.aspect, right: half * this.aspect, top: half, bottom: -half, zoom: 1 }); + this.ortho.updateProjectionMatrix(); + this.ortho.position.set(cx, groundY + TOP_HEIGHT, cz + TOP_SOUTH); + this.persp.position.set(cx, groundY + half * 0.9, cz + half * 1.1); + this.controls.target.set(cx, groundY, cz); + this.ortho.lookAt(this.controls.target); + this.persp.lookAt(this.controls.target); + this.controls.update(); + } + + setMode(mode: ViewMode): void { + if (mode === this.mode) return; + const target = this.controls.target.clone(); + if (this.mode === 'top' && mode !== 'gun') { + const span = (this.ortho.top - this.ortho.bottom) / this.ortho.zoom; + this.persp.position.set(target.x, target.y + span * 0.6, target.z + span * 0.6); + } + if (mode === 'top') this.ortho.position.set(target.x, target.y + TOP_HEIGHT, target.z + TOP_SOUTH); + this.mode = mode; + this.limitTilt(); + this.following = false; + this.controls.object = this.camera; + this.controls.enableRotate = mode !== 'top'; + this.controls.enabled = mode !== 'gun'; + this.camera.lookAt(target); + this.controls.update(); + } + + /** The next follow frame starts over around the (newly) selected vehicle. */ + refollow(): void { + this.following = false; + } + + /** Per frame: keeps the followed vehicle centred, or puts the camera at the muzzle. */ + tick(tank: Tank | undefined): void { + if (this.mode === 'follow' && tank !== undefined && tank.root.visible) { + const at = tank.root.position; + if (!this.following) { + this.controls.target.copy(at); + this.persp.position.set(at.x - 25, at.y + 15, at.z + 25); + this.following = true; + } else { + const d = at.clone().sub(this.lastFollow); + this.controls.target.add(d); + this.persp.position.add(d); + } + this.lastFollow.copy(at); + } else if (this.mode === 'gun' && tank !== undefined && tank.root.visible) { + const q = tank.barrel.getWorldQuaternion(new Quaternion()); + const dir = new Vector3(1, 0, 0).applyQuaternion(q); + const tip = tank.barrel.getWorldPosition(new Vector3()).addScaledVector(dir, tank.length * 0.8); + this.persp.position.copy(tip); + this.persp.lookAt(tip.clone().add(dir)); + return; + } + if (this.controls.enabled) this.controls.update(); + } + + dispose(): void { + this.controls.dispose(); + } +} diff --git a/apps/ai-lab/src/three/coords.ts b/apps/ai-lab/src/three/coords.ts new file mode 100644 index 0000000..ad9c3a6 --- /dev/null +++ b/apps/ai-lab/src/three/coords.ts @@ -0,0 +1,18 @@ +/** + * Game world to three.js: Dagor is left-handed with Y up, three.js right-handed, so world z is + * mirrored (three z = -world z). A world heading (degrees of atan2(z, x)) then becomes the same + * angle of rotation about three's +Y, and a model's local +X is its front, +Y up, -Z its left. + */ +import { Vector3 } from 'three'; + +export const DEG = Math.PI / 180; + +export function toThree(x: number, y: number, z: number, out: Vector3 = new Vector3()): Vector3 { + return out.set(x, y, -z); +} + +/** Three.js direction of a world heading and pitch, in degrees. */ +export function dirOf(yawDeg: number, pitchDeg: number, out: Vector3 = new Vector3()): Vector3 { + const c = Math.cos(pitchDeg * DEG); + return out.set(Math.cos(yawDeg * DEG) * c, Math.sin(pitchDeg * DEG), -Math.sin(yawDeg * DEG) * c); +} diff --git a/apps/ai-lab/src/three/mapMeshes.ts b/apps/ai-lab/src/three/mapMeshes.ts new file mode 100644 index 0000000..c163833 --- /dev/null +++ b/apps/ai-lab/src/three/mapMeshes.ts @@ -0,0 +1,134 @@ +/** + * The static 3D map: lit terrain (coloured by height, or draped with the navigation mesh image), + * the collision shapes of placed objects coloured by kind, and the water plane. + */ +import type { MapScene, SceneTerrain } from '@wto/ground-sim'; +import { + BufferAttribute, BufferGeometry, CanvasTexture, Color, DoubleSide, Group, Mesh, MeshLambertMaterial, + PlaneGeometry, SRGBColorSpace, type Material, +} from 'three'; +import type { MapLayer } from '../mapLayer.ts'; + +/** Colour and opacity per SCENE_KIND_NAMES entry. */ +const KIND_LOOK: readonly (readonly [number, number])[] = [ + [0xb9b2a3, 1], [0x7d7a74, 1], [0x9a7b55, 1], [0xe09a4a, 0.4], [0x4f8a3c, 1], [0x6f8aa0, 1], +]; + +const LOW = new Color(0x3c4a32); +const HIGH = new Color(0x9b9171); + +export interface MapMeshes { + readonly group: Group; + readonly terrain: Mesh; + /** Objects per scene kind, to switch kinds on and off. */ + readonly kinds: Group[]; + dispose(): void; +} + +function terrainGeometry(t: SceneTerrain, nav: MapLayer | undefined): BufferGeometry { + const n = t.cols * t.rows; + const pos = new Float32Array(n * 3); + const col = new Float32Array(n * 3); + const uv = new Float32Array(n * 2); + let lo = Infinity; + let hi = -Infinity; + for (const h of t.heights) { lo = Math.min(lo, h); hi = Math.max(hi, h); } + const c = new Color(); + const navW = nav === undefined ? 1 : nav.canvas.width / nav.pxPerM; + const navH = nav === undefined ? 1 : nav.canvas.height / nav.pxPerM; + for (let r = 0; r < t.rows; r++) { + for (let k = 0; k < t.cols; k++) { + const i = r * t.cols + k; + const x = t.origin[0] + k * t.cellM; + const z = t.origin[1] + r * t.cellM; + const h = t.heights[i] ?? 0; + pos.set([x, h, -z], i * 3); + c.lerpColors(LOW, HIGH, hi > lo ? (h - lo) / (hi - lo) : 0); + col.set([c.r, c.g, c.b], i * 3); + if (nav !== undefined) uv.set([(x - nav.x0) / navW, (z - (nav.z1 - navH)) / navH], i * 2); + } + } + const idx = new Uint32Array((t.cols - 1) * (t.rows - 1) * 6); + let at = 0; + for (let r = 0; r + 1 < t.rows; r++) { + for (let k = 0; k + 1 < t.cols; k++) { + const i = r * t.cols + k; + idx.set([i, i + 1, i + t.cols, i + 1, i + t.cols + 1, i + t.cols], at); + at += 6; + } + } + const g = new BufferGeometry(); + g.setAttribute('position', new BufferAttribute(pos, 3)); + g.setAttribute('color', new BufferAttribute(col, 3)); + g.setAttribute('uv', new BufferAttribute(uv, 2)); + g.setIndex(new BufferAttribute(idx, 1)); + g.computeVertexNormals(); + return g; +} + +/** Drapes the navigation image over the terrain, or goes back to height colours. */ +export function setTerrainImage(m: MapMeshes, nav: MapLayer | undefined): void { + const mat = m.terrain.material; + mat.map?.dispose(); + if (nav === undefined) { + mat.map = null; + mat.vertexColors = true; + } else { + const tex = new CanvasTexture(nav.canvas); + tex.colorSpace = SRGBColorSpace; + tex.anisotropy = 8; + mat.map = tex; + mat.vertexColors = false; + } + mat.needsUpdate = true; +} + +function objectKinds(scene: MapScene, materials: Material[]): Group[] { + const kinds = KIND_LOOK.map(() => new Group()); + const mats = KIND_LOOK.map(([color, opacity]) => new MeshLambertMaterial({ + color, flatShading: true, side: DoubleSide, transparent: opacity < 1, opacity, depthWrite: opacity >= 1, + })); + materials.push(...mats); + for (const m of scene.meshes) { + const g = new BufferGeometry(); + const pos = new Float32Array(m.positions); + for (let i = 2; i < pos.length; i += 3) pos[i] = -(pos[i] ?? 0); + g.setAttribute('position', new BufferAttribute(pos, 3)); + g.setIndex(new BufferAttribute(m.indices, 1)); + g.computeBoundingSphere(); + const mat = mats[m.kind] ?? mats[0]; + if (mat !== undefined) kinds[m.kind]?.add(new Mesh(g, mat)); + } + return kinds; +} + +export function buildMapMeshes(scene: MapScene, nav: MapLayer | undefined): MapMeshes { + const group = new Group(); + const materials: Material[] = []; + const terrainMat = new MeshLambertMaterial({ vertexColors: true }); + materials.push(terrainMat); + const terrain = new Mesh(terrainGeometry(scene.terrain, nav), terrainMat); + group.add(terrain); + const kinds = objectKinds(scene, materials); + for (const k of kinds) group.add(k); + if (scene.waterLevel !== undefined) { + const w = scene.boundsMax[0] - scene.boundsMin[0]; + const d = scene.boundsMax[1] - scene.boundsMin[1]; + const waterMat = new MeshLambertMaterial({ color: 0x2d5f8a, transparent: true, opacity: 0.55, depthWrite: false }); + materials.push(waterMat); + const water = new Mesh(new PlaneGeometry(w, d), waterMat); + water.rotation.x = -Math.PI / 2; + water.position.set(scene.boundsMin[0] + w / 2, scene.waterLevel, -(scene.boundsMin[1] + d / 2)); + group.add(water); + } + const meshes: MapMeshes = { + group, terrain, kinds, + dispose() { + group.traverse((o) => { if (o instanceof Mesh) (o.geometry as BufferGeometry).dispose(); }); + terrainMat.map?.dispose(); + for (const m of materials) m.dispose(); + }, + }; + if (nav !== undefined) setTerrainImage(meshes, nav); + return meshes; +} diff --git a/apps/ai-lab/src/three/overlays.ts b/apps/ai-lab/src/three/overlays.ts new file mode 100644 index 0000000..762f67c --- /dev/null +++ b/apps/ai-lab/src/three/overlays.ts @@ -0,0 +1,182 @@ +/** + * What is drawn over the map for one moment, rebuilt every update: goal, target and look lines, + * the gun's view cone, recent shots and hits, deaths so far, and the capture zones. + */ +import type { TraceBattle } from '@wto/ground-sim'; +import { + AdditiveBlending, BufferAttribute, BufferGeometry, Color, DoubleSide, Group, LineBasicMaterial, + LineSegments, Mesh, MeshBasicMaterial, Points, PointsMaterial, +} from 'three'; +import { eventsBetween, type SceneAt, type UnitAt } from '../frames.ts'; +import { DEG } from './coords.ts'; +import { ARMY_HEX, type TankPool } from './tanks.ts'; + +export interface Layers { + readonly goals: boolean; + readonly links: boolean; + readonly cones: boolean; + readonly labels: boolean; + readonly events: boolean; +} + +const GUN_FOV_HALF_DEG = 30; +const CONE_M = 120; +const CONE_STEPS = 12; +const EVENT_WINDOW_SEC = 2; +const CAP_STEPS = 64; +const WISH_M = 25; + +/** Line segments with per-vertex colour, refilled from scratch on every update. */ +class Lines { + readonly obj: LineSegments; + private pos: number[] = []; + private col: number[] = []; + + constructor(opacity: number, additive = false) { + const mat = new LineBasicMaterial({ vertexColors: true, transparent: true, opacity, depthTest: !additive }); + if (additive) mat.blending = AdditiveBlending; + this.obj = new LineSegments(new BufferGeometry(), mat); + this.obj.frustumCulled = false; + } + + add(ax: number, ay: number, az: number, bx: number, by: number, bz: number, c: Color): void { + this.pos.push(ax, ay, -az, bx, by, -bz); + this.col.push(c.r, c.g, c.b, c.r, c.g, c.b); + } + + flush(): void { + const g = this.obj.geometry; + g.setAttribute('position', new BufferAttribute(Float32Array.from(this.pos), 3)); + g.setAttribute('color', new BufferAttribute(Float32Array.from(this.col), 3)); + g.computeBoundingSphere(); + this.pos = []; + this.col = []; + } +} + +const C = { + goal: new Color(0x9aa4ad), target: new Color(0xff4646), targetLost: new Color(0x803030), + look: new Color(0xffa028), wish: new Color(0xffe14a), shot: new Color(0xffff78), dead1: new Color(ARMY_HEX[1]), + dead2: new Color(ARMY_HEX[2]), cap: new Color(0xdddddd), +}; + +export class Overlays { + readonly group = new Group(); + private readonly faint = new Lines(0.35); + private readonly bold = new Lines(0.9); + private readonly shots = new Lines(1, true); + private readonly cones: Mesh; + private readonly hits: Points; + + constructor(private readonly tanks: TankPool) { + this.cones = new Mesh(new BufferGeometry(), new MeshBasicMaterial({ + color: 0xffffc8, transparent: true, opacity: 0.08, side: DoubleSide, depthWrite: false, + })); + this.cones.frustumCulled = false; + this.hits = new Points(new BufferGeometry(), new PointsMaterial({ size: 6, sizeAttenuation: false, vertexColors: true })); + this.hits.frustumCulled = false; + this.group.add(this.faint.obj, this.bold.obj, this.shots.obj, this.cones, this.hits); + } + + /** Height where lines leave a vehicle: its turret top. */ + private eye(u: UnitAt): number { + return this.tanks.groundY(u.x, u.y, u.z) + (this.tanks.get(u.unit.eid)?.eyeY ?? 2); + } + + update(battle: TraceBattle, scene: SceneAt, layers: Layers): void { + const cone: number[] = []; + for (const u of scene.units.values()) this.botLines(u, scene, layers, cone); + if (layers.events) this.events(battle, scene); + this.deaths(battle, scene.t); + this.caps(scene); + const g = this.cones.geometry; + g.setAttribute('position', new BufferAttribute(Float32Array.from(cone), 3)); + this.faint.flush(); + this.bold.flush(); + this.shots.flush(); + } + + private botLines(u: UnitAt, scene: SceneAt, layers: Layers, cone: number[]): void { + const bot = u.bot; + if (bot === undefined || !u.unit.alive) return; + const y = this.eye(u); + if (layers.goals && bot.hasOrder) this.faint.add(u.x, y, u.z, bot.goalX, this.tanks.terrainY(bot.goalX, bot.goalZ) + 1, bot.goalZ, C.goal); + const wy = bot.wishYaw * DEG; + this.bold.add(u.x, y, u.z, u.x + Math.cos(wy) * WISH_M, y, u.z + Math.sin(wy) * WISH_M, C.wish); + if (layers.cones) { + for (let i = 0; i < CONE_STEPS; i++) { + const a = (u.gunYaw - GUN_FOV_HALF_DEG + (2 * GUN_FOV_HALF_DEG * i) / CONE_STEPS) * DEG; + const b = (u.gunYaw - GUN_FOV_HALF_DEG + (2 * GUN_FOV_HALF_DEG * (i + 1)) / CONE_STEPS) * DEG; + cone.push(u.x, y, -u.z, u.x + Math.cos(a) * CONE_M, y, -(u.z + Math.sin(a) * CONE_M), + u.x + Math.cos(b) * CONE_M, y, -(u.z + Math.sin(b) * CONE_M)); + } + } + if (!layers.links) return; + const target = scene.units.get(bot.target); + if (target !== undefined && bot.target !== '0') { + (bot.targetInSight ? this.bold : this.faint).add(u.x, y, u.z, target.x, this.eye(target), target.z, + bot.targetInSight ? C.target : C.targetLost); + } + const look = scene.units.get(bot.lookAt); + if (look !== undefined && bot.lookAt !== bot.target) this.bold.add(u.x, y, u.z, look.x, this.eye(look), look.z, C.look); + } + + private events(battle: TraceBattle, scene: SceneAt): void { + const pos: number[] = []; + const col: number[] = []; + const c = new Color(); + for (const e of eventsBetween(battle, scene.t - EVENT_WINDOW_SEC, scene.t)) { + const fade = 1 - (scene.t - e.t) / EVENT_WINDOW_SEC; + if (e.kind === 'SHOT' && e.eid !== undefined) { + const from = scene.units.get(e.eid); + const to = scene.units.get(e.fields['tgt'] ?? ''); + if (from === undefined || to === undefined) continue; + this.shots.add(from.x, this.eye(from), from.z, to.x, this.eye(to) - 1, to.z, c.copy(C.shot).multiplyScalar(fade)); + } else if (e.kind === 'HIT') { + const x = Number(e.fields['x']); + const z = Number(e.fields['z']); + pos.push(x, this.tanks.terrainY(x, z) + 1.5, -z); + c.set(e.fields['drop'] === '1' ? 0xff3c3c : 0xc8c8c8).multiplyScalar(fade); + col.push(c.r, c.g, c.b); + } + } + this.hits.geometry.setAttribute('position', new BufferAttribute(Float32Array.from(pos), 3)); + this.hits.geometry.setAttribute('color', new BufferAttribute(Float32Array.from(col), 3)); + } + + private deaths(battle: TraceBattle, t: number): void { + for (const e of eventsBetween(battle, battle.startT, t)) { + if (e.kind !== 'DEATH') continue; + const x = Number(e.fields['x']); + const z = Number(e.fields['z']); + const y = this.tanks.terrainY(x, z) + 0.5; + const c = e.fields['army'] === '1' ? C.dead1 : C.dead2; + this.faint.add(x - 4, y, z - 4, x + 4, y, z + 4, c); + this.faint.add(x - 4, y, z + 4, x + 4, y, z - 4, c); + } + } + + private caps(scene: SceneAt): void { + for (const cap of scene.caps) { + const c = new Color(ARMY_HEX[cap.owner] ?? C.cap.getHex()); + for (let i = 0; i < CAP_STEPS; i++) { + const a = (i / CAP_STEPS) * Math.PI * 2; + const b = ((i + 1) / CAP_STEPS) * Math.PI * 2; + const ax = cap.x + Math.cos(a) * cap.r; + const az = cap.z + Math.sin(a) * cap.r; + const bx = cap.x + Math.cos(b) * cap.r; + const bz = cap.z + Math.sin(b) * cap.r; + this.bold.add(ax, this.tanks.terrainY(ax, az) + 0.8, az, bx, this.tanks.terrainY(bx, bz) + 0.8, bz, c); + } + } + } + + dispose(): void { + this.group.traverse((o) => { + if (o instanceof Mesh || o instanceof LineSegments || o instanceof Points) { + o.geometry.dispose(); + (o.material as { dispose(): void }).dispose(); + } + }); + } +} diff --git a/apps/ai-lab/src/three/tanks.ts b/apps/ai-lab/src/three/tanks.ts new file mode 100644 index 0000000..93117dd --- /dev/null +++ b/apps/ai-lab/src/three/tanks.ts @@ -0,0 +1,141 @@ +/** + * Every vehicle as simple shapes: a hull box tilted by the hull's pitch and roll, a turret box + * turned to the gun's heading, and a barrel at the gun's pitch. Sizes come from the bot's vehicle + * class (players: light or medium). + */ +import { sceneHeightAt, type SceneTerrain } from '@wto/ground-sim'; +import { + BoxGeometry, Color, CylinderGeometry, Group, Mesh, MeshLambertMaterial, type Object3D, +} from 'three'; +import { CSS2DObject } from 'three/addons/renderers/CSS2DRenderer.js'; +import type { UnitAt } from '../frames.ts'; +import { DEG } from './coords.ts'; + +/** Length, width, hull height per vehicle class (medium, light, heavy, tank destroyer, SPAA). */ +const SIZES: readonly (readonly [number, number, number])[] = [ + [7, 3.4, 1.3], [6, 3, 1.1], [7.6, 3.6, 1.4], [7, 3.3, 1.2], [6.5, 3.1, 1.2], +]; + +export const ARMY_HEX: Readonly> = { 1: 0x4aa3ff, 2: 0xff5c5c }; +const DEAD = new Color(0x4a4a4a); +const SELECTED = new Color(0x6a5200); +const NONE = new Color(0); + +/** A trace height further than this from the terrain is kept (bridge, building, platform). */ +const OFF_GROUND_M = 1.5; + +export interface Tank { + readonly root: Group; + readonly turret: Group; + readonly barrel: Group; + readonly label: CSS2DObject; + readonly mats: MeshLambertMaterial[]; + /** Turret top above the hull origin, where lines and the gun camera start. */ + readonly eyeY: number; + readonly length: number; +} + +function sizeOf(u: UnitAt): readonly [number, number, number] { + const cls = u.bot?.vehicleClass ?? (u.unit.light ? 1 : 0); + return SIZES[cls] ?? SIZES[0] ?? [7, 3.4, 1.3]; +} + +function makeTank(u: UnitAt): Tank { + const [len, wid, hh] = sizeOf(u); + const hullMat = new MeshLambertMaterial(); + const turretMat = new MeshLambertMaterial(); + const root = new Group(); + root.rotation.order = 'YZX'; + const hull = new Mesh(new BoxGeometry(len, hh, wid), hullMat); + hull.position.y = hh / 2; + const turret = new Group(); + turret.position.set(-len * 0.05, hh, 0); + const tw = wid * 0.7; + const th = hh * 0.65; + const turretBox = new Mesh(new BoxGeometry(len * 0.48, th, tw), turretMat); + turretBox.position.y = th / 2; + const barrel = new Group(); + barrel.position.set(len * 0.2, th * 0.55, 0); + const tube = new Mesh(new CylinderGeometry(0.09, 0.11, len * 0.75, 8), turretMat); + tube.rotation.z = -Math.PI / 2; + tube.position.x = len * 0.375; + barrel.add(tube); + turret.add(turretBox, barrel); + root.add(hull, turret); + const div = document.createElement('div'); + div.className = 'tank-label'; + const label = new CSS2DObject(div); + label.position.y = hh + th + 2.5; + root.add(label); + for (const m of [hull, turretBox, tube]) m.userData['eid'] = u.unit.eid; + return { root, turret, barrel, label, mats: [hullMat, turretMat], eyeY: hh + th, length: len }; +} + +export class TankPool { + readonly group = new Group(); + private readonly tanks = new Map(); + + constructor(private readonly terrain: SceneTerrain | undefined) {} + + get(eid: string): Tank | undefined { + return this.tanks.get(eid); + } + + /** Meshes to pick with a ray. */ + pickables(): Object3D[] { + const out: Object3D[] = []; + for (const t of this.tanks.values()) if (t.root.visible) t.root.traverse((o) => { if (o instanceof Mesh) out.push(o); }); + return out; + } + + terrainY(x: number, z: number): number { + return this.terrain === undefined ? 0 : sceneHeightAt(this.terrain, x, z); + } + + /** Ground height for the vehicle: the terrain unless the trace puts it clearly above or below. */ + groundY(x: number, y: number, z: number): number { + if (this.terrain === undefined) return y; + const g = sceneHeightAt(this.terrain, x, z); + return Math.abs(y - g) <= OFF_GROUND_M ? g : y; + } + + update(units: ReadonlyMap, selected: string | undefined, labels: (u: UnitAt) => string | undefined): void { + for (const [eid, t] of this.tanks) if (!units.has(eid)) t.root.visible = false; + for (const u of units.values()) { + let t = this.tanks.get(u.unit.eid); + if (t === undefined) { + t = makeTank(u); + this.tanks.set(u.unit.eid, t); + this.group.add(t.root); + } + this.place(t, u, u.unit.eid === selected, labels(u)); + } + } + + private place(t: Tank, u: UnitAt, selected: boolean, label: string | undefined): void { + t.root.visible = true; + t.root.position.set(u.x, this.groundY(u.x, u.y, u.z), -u.z); + t.root.rotation.set(u.hullRoll * DEG, u.yaw * DEG, u.hullPitch * DEG); + const rel = ((((u.gunYaw - u.yaw) % 360) + 540) % 360) - 180; + t.turret.rotation.y = rel * DEG; + const hullSlope = u.hullPitch * Math.cos(rel * DEG) + u.hullRoll * Math.sin(rel * DEG); + t.barrel.rotation.z = (u.gunPitch - hullSlope) * DEG; + const base = u.unit.alive ? new Color(ARMY_HEX[u.unit.army] ?? 0xcccccc) : DEAD; + t.mats.forEach((m, i) => { + m.color.copy(base).multiplyScalar(i === 0 ? 1 : 0.8); + m.emissive.copy(selected ? SELECTED : NONE); + }); + t.label.visible = label !== undefined; + if (label !== undefined) t.label.element.textContent = label; + if (u.unit.human) t.label.element.classList.add('human'); + } + + dispose(): void { + for (const t of this.tanks.values()) { + t.root.traverse((o) => { if (o instanceof Mesh) o.geometry.dispose(); }); + for (const m of t.mats) m.dispose(); + t.label.element.remove(); + } + this.tanks.clear(); + } +} diff --git a/apps/ai-lab/src/view.ts b/apps/ai-lab/src/view.ts deleted file mode 100644 index 6bfe133..0000000 --- a/apps/ai-lab/src/view.ts +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Top-down view of the battle: world x to the right, world z up (Dagor is Y-up). Headings are - * degrees of atan2(z, x), as the trace writes them. - */ -export interface View { - /** World point at the centre of the canvas. */ - readonly cx: number; - readonly cz: number; - /** Screen pixels per world metre. */ - readonly scale: number; - readonly w: number; - readonly h: number; -} - -export function toScreen(v: View, x: number, z: number): [number, number] { - return [v.w / 2 + (x - v.cx) * v.scale, v.h / 2 - (z - v.cz) * v.scale]; -} - -export function toWorld(v: View, sx: number, sy: number): [number, number] { - return [v.cx + (sx - v.w / 2) / v.scale, v.cz - (sy - v.h / 2) / v.scale]; -} - -/** Screen direction (unit vector) of a world heading. */ -export function screenDir(yawDeg: number): [number, number] { - const r = (yawDeg * Math.PI) / 180; - return [Math.cos(r), -Math.sin(r)]; -} - -export function fitView(minX: number, minZ: number, maxX: number, maxZ: number, w: number, h: number): View { - const scale = Math.min(w / Math.max(1, maxX - minX), h / Math.max(1, maxZ - minZ)) * 0.95; - return { cx: (minX + maxX) / 2, cz: (minZ + maxZ) / 2, scale, w, h }; -} - -/** Zoom by `factor` keeping the world point under the screen point (sx, sy) in place. */ -export function zoomAt(v: View, sx: number, sy: number, factor: number): View { - const [wx, wz] = toWorld(v, sx, sy); - const scale = Math.min(40, Math.max(0.05, v.scale * factor)); - return { ...v, scale, cx: wx - (sx - v.w / 2) / scale, cz: wz + (sy - v.h / 2) / scale }; -} diff --git a/game-ai/ground/wto_ai_drive_common.das b/game-ai/ground/wto_ai_drive_common.das index 503229f..9c55198 100644 --- a/game-ai/ground/wto_ai_drive_common.das +++ b/game-ai/ground/wto_ai_drive_common.das @@ -19,6 +19,7 @@ require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_nav_types_common +require %appGame.wtoai.wto_ai_follow_common [never_inline] def public wto_drive_announce_script_ready() @@ -72,15 +73,6 @@ def private wto_check_echo_watchdog(unitMissionName : string; var actor : Vehicl st.deadEchoSec = 0.0 return true -def public wto_pivot_drive_mode(spec : WtoVehicleSpec const&; frontClearM, rearClearM : float; preferNeutral : bool) : int - let openFront = frontClearM >= spec.halfLen + 3.5 - let neutralTurn = spec.canPivot && frontClearM >= spec.halfLen + 1.2 && rearClearM >= spec.halfLen + 1.0 - if neutralTurn && (preferNeutral || !openFront) - return WTO_DRIVE_PIVOT - if openFront - return WTO_DRIVE_CRUISE - return rearClearM >= spec.halfLen + WTO_AI_TERRAIN_MARGIN_M ? WTO_DRIVE_REVERSE : WTO_DRIVE_HALT - [never_inline] def private wto_compute_pivot_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleSpec const&; fwd, left : float3; vFwd, omega : float; diff --git a/game-ai/ground/wto_ai_facing_common.das b/game-ai/ground/wto_ai_facing_common.das index 6df8aec..88aabc1 100644 --- a/game-ai/ground/wto_ai_facing_common.das +++ b/game-ai/ground/wto_ai_facing_common.das @@ -11,7 +11,6 @@ require %appGame.wtoai.wto_ai_combat_types_common require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_nav_types_common require %appGame.wtoai.wto_ai_follow_common -require %appGame.wtoai.wto_ai_drive_common def private wto_face_bound(spec : WtoVehicleSpec const&) : bool return spec.isTracked && (spec.role == WTO_ROLE_MEDIUM || spec.role == WTO_ROLE_HEAVY || spec.role == WTO_ROLE_TD) diff --git a/game-ai/ground/wto_ai_fire_common.das b/game-ai/ground/wto_ai_fire_common.das index b91406a..517de9d 100644 --- a/game-ai/ground/wto_ai_fire_common.das +++ b/game-ai/ground/wto_ai_fire_common.das @@ -1,6 +1,7 @@ -// Turret servo, active loaded-shell inspection, and ballistic aim solver. -// Main weapon firing goes exclusively through wto_fire_gate_try_shoot, secondary and coaxial -// weapons through wto_fire_aux_update. +// Fire control on the game's weapons: reads the primary weapon (shell, readiness, reload), samples +// the live barrel, drives the turret toward the direction wto_ai_fire_decide_common picks, and +// fires the main weapon only through wto_fire_gate_try_shoot, secondary and coaxial weapons +// through wto_fire_aux_update. options indenting = 2 options no_global_heap = true module wto_ai_fire_common shared @@ -19,12 +20,10 @@ require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_combat_types_common require %appGame.wtoai.wto_ai_types_common -require %appGame.wtoai.wto_ai_world_common -require %appGame.wtoai.wto_ai_estimate_common +require %appGame.wtoai.wto_ai_fire_decide_common require %appGame.wtoai.wto_ai_fire_gate_common require %appGame.wtoai.wto_ai_traverse_common require %appGame.wtoai.wto_ai_hull_aim_common -require %appGame.wtoai.wto_ai_turret_common require %appGame.wtoai.wto_ai_trigger_common require %appGame.wtoai.wto_ai_fire_aux_common require %appGame.wtoai.wto_ai_ammo_common @@ -214,18 +213,11 @@ def private wto_fire_sample_primary(unit : Unit const?; var state : WtoFireState state.barrelSight = barrelDir return true -def private wto_clear_aim_tracking(var fc : WtoFireState&) - fc.aimTargetEid = INVALID_ENTITY_ID - fc.aimDriftDegSec = 0.0 - fc.settleHoldSec = 0.0 - fc.lastAligned = false - fc.lastDenyReason = WTO_DENY_NO_TARGET - // SPAA vs aircraft only delegates to stock air-target fire control (never ground targets). [never_inline] def private wto_yield_air_fire(var unit : Unit?; var slot : WtoBotSlot&) wto_set_hull_aim(unit, "", false, 0.0, 0.0, unit.unitTm[0], slot) - wto_clear_aim_tracking(slot.fire) + wto_fire_clear_aim_tracking(slot.fire) wto_trig_set_target(INVALID_ENTITY_ID, slot.trigger) var gm = as_gm(unit) if gm != null @@ -233,18 +225,6 @@ def private wto_yield_air_fire(var unit : Unit?; var slot : WtoBotSlot&) *gm |> set_ignore_stop_for_fire(true) set_unit_attack_type(unit, "attack_target") -[never_inline] -def private wto_fire_has_engagement(slot : WtoBotSlot const&) : bool - assume p = slot.perceive - let yielding = slot.spec.role == WTO_ROLE_SPAA && slot.tactics.state == WTO_STATE_DISABLED - return p.hasClearLos && !!p.targetEid && !p.targetIsAir && !yielding && !wto_turret_prefers_threat(slot) - -def private wto_fire_wants_soft(world : WtoWorldSnap const&; slot : WtoBotSlot const&) : bool - if !slot.perceive.hasClearLos || slot.perceive.targetIsAir - return false - let idx = wto_world_find_unit(world, slot.perceive.targetEid) - return idx >= 0 && (world.units[idx].isLightTag || world.units[idx].halfWid < 1.35) - [never_inline] def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; className : string; now, dt : float; var slot : WtoBotSlot&; var fireBudget : int&) @@ -262,20 +242,10 @@ def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; classN let hFwd = unit.unitTm[0] var wishWorldDir = hFwd var aimPt = muzzlePos - var distToTgt = 9999.0 let engage = wto_fire_has_engagement(slot) let distXZ = sqrt(wto_xz_dist_sq(unit.pos, slot.perceive.knownPos)) - let target = engage ? slot.perceive.targetEid : INVALID_ENTITY_ID - wto_trig_set_target(target, slot.trigger) - var auxAimed = false - if engage - let aimBase = slot.perceive.visibleAimPt - distToTgt = wto_solve_ballistic_aim(muzzlePos, unit.vel, aimBase, slot.fire.activeSpeedMps, slot.fire.activeDragCx, slot.fire.activeMassKg, slot.fire.activeCaliberM, slot, aimPt, wishWorldDir) - auxAimed = wto_fire_aux_aim(unit, className, distXZ, slot) - slot.turret.lookReason = WTO_LOOK_ENGAGE - else - wishWorldDir = wto_turret_look_dir(now, muzzlePos, unit.pos, hFwd, slot) - slot.turret.wishDir = wishWorldDir + let distToTgt = wto_fire_decide_aim(now, engage, muzzlePos, unit.pos, unit.vel, hFwd, slot, aimPt, wishWorldDir) + let auxAimed = engage && wto_fire_aux_aim(unit, className, distXZ, slot) var wishYaw = 0.0 var wishPitch = 0.0 wto_world_to_hull_deg(wishWorldDir, hFwd, unit.unitTm[1], unit.unitTm[2], wishYaw, wishPitch) @@ -288,8 +258,6 @@ def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; classN if canEngage wto_fire_gate_try_shoot(world, unit, className, now, distXZ, muzzlePos, aimPt, liveBarrelDir, wishWorldDir, slot, fireBudget) else - wto_clear_aim_tracking(slot.fire) - slot.trigger.wantSpeedMps = 99.0 - slot.trigger.wantSpeedAt = -100.0 + wto_fire_hold(slot) if engage wto_fire_aux_update(world, unit, className, now, distXZ, slot, fireBudget) diff --git a/game-ai/ground/wto_ai_fire_decide_common.das b/game-ai/ground/wto_ai_fire_decide_common.das new file mode 100644 index 0000000..17ecda6 --- /dev/null +++ b/game-ai/ground/wto_ai_fire_decide_common.das @@ -0,0 +1,61 @@ +// Fire control decisions, free of weapons and turret objects so the simulator runs them as they +// are: whether the bot engages its perceived target, whether it wants a soft shell, and where +// the turret should look. wto_ai_fire_common reads the weapons and drives the turret around them. +options indenting = 2 +options no_global_heap = true +module wto_ai_fire_decide_common shared + +require ecs +require math +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_combat_types_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_world_common +require %appGame.wtoai.wto_ai_estimate_common +require %appGame.wtoai.wto_ai_turret_common +require %appGame.wtoai.wto_ai_trigger_common + +[never_inline] +def public wto_fire_has_engagement(slot : WtoBotSlot const&) : bool + assume p = slot.perceive + let yielding = slot.spec.role == WTO_ROLE_SPAA && slot.tactics.state == WTO_STATE_DISABLED + return p.hasClearLos && !!p.targetEid && !p.targetIsAir && !yielding && !wto_turret_prefers_threat(slot) + +def public wto_fire_wants_soft(world : WtoWorldSnap const&; slot : WtoBotSlot const&) : bool + if !slot.perceive.hasClearLos || slot.perceive.targetIsAir + return false + let idx = wto_world_find_unit(world, slot.perceive.targetEid) + return idx >= 0 && (world.units[idx].isLightTag || world.units[idx].halfWid < 1.35) + +def public wto_fire_clear_aim_tracking(var fc : WtoFireState&) + fc.aimTargetEid = INVALID_ENTITY_ID + fc.aimDriftDegSec = 0.0 + fc.settleHoldSec = 0.0 + fc.lastAligned = false + fc.lastDenyReason = WTO_DENY_NO_TARGET + +// No shot this frame: forget the aim tracking and lift the trigger's speed request. +def public wto_fire_hold(var slot : WtoBotSlot&) + wto_fire_clear_aim_tracking(slot.fire) + slot.trigger.wantSpeedMps = 99.0 + slot.trigger.wantSpeedAt = -100.0 + +// Hands the trigger its target and returns the world direction the turret should point: the +// ballistic solution on the engaged target, or the turret channel's look direction. Writes the +// aim point and returns the distance to the target (9999 when not engaging). +[never_inline] +def public wto_fire_decide_aim(now : float; engage : bool; muzzlePos, unitPos, unitVel, hullFwd : float3; + var slot : WtoBotSlot&; var aimPt, wishDir : float3&) : float + wto_trig_set_target(engage ? slot.perceive.targetEid : INVALID_ENTITY_ID, slot.trigger) + var distToTgt = 9999.0 + aimPt = muzzlePos + if engage + assume fc = slot.fire + distToTgt = wto_solve_ballistic_aim(muzzlePos, unitVel, slot.perceive.visibleAimPt, fc.activeSpeedMps, fc.activeDragCx, + fc.activeMassKg, fc.activeCaliberM, slot, aimPt, wishDir) + slot.turret.lookReason = WTO_LOOK_ENGAGE + else + wishDir = wto_turret_look_dir(now, muzzlePos, unitPos, hullFwd, slot) + slot.turret.wishDir = wishDir + return distToTgt diff --git a/game-ai/ground/wto_ai_follow_common.das b/game-ai/ground/wto_ai_follow_common.das index 3d75722..a3eceef 100644 --- a/game-ai/ground/wto_ai_follow_common.das +++ b/game-ai/ground/wto_ai_follow_common.das @@ -12,6 +12,17 @@ require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_nav_types_common require %appGame.wtoai.wto_ai_polyline_common +// Drive mode for turning in place or getting out: pivot when both ends have room, cruise when +// the front is open, reverse when only the rear is, halt otherwise. +def public wto_pivot_drive_mode(spec : WtoVehicleSpec const&; frontClearM, rearClearM : float; preferNeutral : bool) : int + let openFront = frontClearM >= spec.halfLen + 3.5 + let neutralTurn = spec.canPivot && frontClearM >= spec.halfLen + 1.2 && rearClearM >= spec.halfLen + 1.0 + if neutralTurn && (preferNeutral || !openFront) + return WTO_DRIVE_PIVOT + if openFront + return WTO_DRIVE_CRUISE + return rearClearM >= spec.halfLen + WTO_AI_TERRAIN_MARGIN_M ? WTO_DRIVE_REVERSE : WTO_DRIVE_HALT + [never_inline] def public wto_drive_cmd_set(var cmd : WtoDriveCmd&; mode : int; targetPos, desiredDir : float3; speedMps, frontClr, rearClr : float) diff --git a/game-ai/ground/wto_ai_nav_common.das b/game-ai/ground/wto_ai_nav_common.das index 82b4e99..569a85b 100644 --- a/game-ai/ground/wto_ai_nav_common.das +++ b/game-ai/ground/wto_ai_nav_common.das @@ -15,7 +15,6 @@ require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_nav_types_common -require %appGame.wtoai.wto_ai_drive_common require %appGame.wtoai.wto_ai_terrain_common require %appGame.wtoai.wto_ai_navquery_common require %appGame.wtoai.wto_ai_navmesh_common diff --git a/game-ai/ground/wto_ai_runtime.das b/game-ai/ground/wto_ai_runtime.das index 7fcefd5..9736d4d 100644 --- a/game-ai/ground/wto_ai_runtime.das +++ b/game-ai/ground/wto_ai_runtime.das @@ -27,6 +27,7 @@ require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_nav_types_common require %appGame.wtoai.wto_ai_specs_common require %appGame.wtoai.wto_ai_world_common +require %appGame.wtoai.wto_ai_world_refresh_common require %appGame.wtoai.wto_ai_crowd_common require %appGame.wtoai.wto_ai_lanes_common require %appGame.wtoai.wto_ai_lanes_build_common @@ -151,7 +152,7 @@ def wto_ai_world_tick_es(act : UpdateStageInfoAct) if !g_world.valid wto_drive_announce_script_ready() print("WTO_AI|RUNTIME_READY\n") - wto_world_refresh(now, g_world) + wto_world_refresh(now, wto_trace_is_due(now, g_next_trace_at), g_world) if WTO_AI_LAYER_NAVIGATION wto_navmesh_battle_tick(g_world, now, g_navmesh) g_lanes.navState = g_navmesh.state diff --git a/game-ai/ground/wto_ai_trace_common.das b/game-ai/ground/wto_ai_trace_common.das index c6bfb2c..7e5ddee 100644 --- a/game-ai/ground/wto_ai_trace_common.das +++ b/game-ai/ground/wto_ai_trace_common.das @@ -1,6 +1,7 @@ // Replay trace for the ground AI viewer (apps/ai-lab), written every diagnostics.traceIntervalSec: // WTO_AI|TRACE_CAP capture zones (position, radius, owner, progress) -// WTO_AI|TRACE_U every ground unit, bots and players alike (position, hull heading, speed) +// WTO_AI|TRACE_U every ground unit, bots and players alike (position, hull attitude, gun +// direction, speed) // WTO_AI|TRACE_B every bot's decision state (order, behavior, targets, turret, trigger) // and as they happen: WTO_AI|HIT (part damage with its offender) and WTO_AI|DEATH. // Positions are whole metres, headings whole degrees of atan2(z, x) in world space. @@ -31,12 +32,19 @@ def private wto_tr_is_bot(bots : WtoBotSlot[64] const&; eid : EntityId) : int return 1 return 0 +def private wto_tr_pitch(dir : float3) : int + return int(floor(asin(clamp(dir.y, -1.0, 1.0)) * WTO_RAD_TO_DEG + 0.5)) + +// The world refresh reads every gun on the frames this returns true. +def public wto_trace_is_due(now, nextAt : float) : bool + return WTO_AI_TRACE_ENABLED && now >= nextAt + // True when this frame writes a trace sample; then the capture zones and all ground units are // written at once, and the pipeline adds one TRACE_B line per bot. [never_inline] def public wto_trace_tick(world : WtoWorldSnap const&; now : float; bots : WtoBotSlot[64] const&; var nextAt : float&) : bool - if !WTO_AI_TRACE_ENABLED || now < nextAt + if !wto_trace_is_due(now, nextAt) return false nextAt = now + WTO_AI_TRACE_SEC for c in range(world.capCount) @@ -47,7 +55,11 @@ def public wto_trace_tick(world : WtoWorldSnap const&; now : float; bots : WtoBo if !u.isGround continue let bot = wto_tr_is_bot(bots, u.eid) - print("WTO_AI|TRACE_U|t={now}|eid={uint(u.eid)}|army={u.army}|bot={bot}|human={wto_tr_b(u.isHuman)}|alive={wto_tr_b(u.isAlive)}|x={wto_tr_m(u.pos.x)}|y={wto_tr_m(u.pos.y)}|z={wto_tr_m(u.pos.z)}|yaw={wto_tr_yaw(u.hullFwd)}|v={length(u.vel)}|shoot={wto_tr_b(u.isShooting)}|light={wto_tr_b(u.isLightTag)}\n") + // hp: hull pitch, nose up positive; hr: roll, left side up positive; gy, gp: gun world yaw + // and pitch, 9999 when the gun was not read. + let gy = u.hasGun ? wto_tr_yaw(u.gunDir) : 9999 + let gp = u.hasGun ? wto_tr_pitch(u.gunDir) : 9999 + print("WTO_AI|TRACE_U|t={now}|eid={uint(u.eid)}|army={u.army}|bot={bot}|human={wto_tr_b(u.isHuman)}|alive={wto_tr_b(u.isAlive)}|x={wto_tr_m(u.pos.x)}|y={wto_tr_m(u.pos.y)}|z={wto_tr_m(u.pos.z)}|yaw={wto_tr_yaw(u.hullFwd)}|v={length(u.vel)}|shoot={wto_tr_b(u.isShooting)}|light={wto_tr_b(u.isLightTag)}|hp={wto_tr_pitch(u.hullFwd3)}|hr={wto_tr_pitch(u.hullLeft)}|gy={gy}|gp={gp}\n") return true def private wto_tr_threat_eid(slot : WtoBotSlot const&; idx : int) : uint diff --git a/game-ai/ground/wto_ai_types_common.das b/game-ai/ground/wto_ai_types_common.das index 4122da4..893614d 100644 --- a/game-ai/ground/wto_ai_types_common.das +++ b/game-ai/ground/wto_ai_types_common.das @@ -82,6 +82,10 @@ struct public WtoUnitSnap pos : float3 = float3(0.0, 0.0, 0.0) vel : float3 = float3(0.0, 0.0, 0.0) hullFwd : float3 = float3(1.0, 0.0, 0.0) + hullFwd3 : float3 = float3(1.0, 0.0, 0.0) + hullLeft : float3 = float3(0.0, 0.0, 1.0) + gunDir : float3 = float3(0.0, 0.0, 0.0) + hasGun : bool = false halfLen : float = 3.4 halfWid : float = 1.75 engineRpm : float = 0.0 diff --git a/game-ai/ground/wto_ai_unit_pose_common.das b/game-ai/ground/wto_ai_unit_pose_common.das new file mode 100644 index 0000000..1e96a7d --- /dev/null +++ b/game-ai/ground/wto_ai_unit_pose_common.das @@ -0,0 +1,30 @@ +// Live main-gun direction of any unit, bots and players alike, for the replay trace. +options indenting = 2 +options no_global_heap = true +module wto_ai_unit_pose_common shared + +require ecs +require math +require DagorMath +require Unit +require Weapon +require %game.utils.utils_common +require %appGame.wtoai.wto_ai_math_common + +// World direction of the first real primary weapon's barrel; false when the unit has none. +[never_inline] +def public wto_pose_gun_dir(unit : Unit const?; var outDir : float3&) : bool + if unit == null || unit.weap == null + return false + var sampled = false + get_weapons_by_trigger_group(unit.weap.Weapons, WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY) <| $(weapons : array const#) + for weapon in weapons + if weapon == null || weapon.isDummyGun + continue + var gunTm : float3x4 + weapon_calcShootTm(weapon, unit.unitTm, gunTm) + if wto_is_finite3(gunTm[0]) && length_sq(gunTm[0]) > 0.25 + outDir = normalize(gunTm[0]) + sampled = true + return + return sampled diff --git a/game-ai/ground/wto_ai_world_common.das b/game-ai/ground/wto_ai_world_common.das index 05ce8b8..dd9cce7 100644 --- a/game-ai/ground/wto_ai_world_common.das +++ b/game-ai/ground/wto_ai_world_common.das @@ -1,19 +1,17 @@ -// World observation layer: builds one flat per-frame snapshot of units, wrecks, -// capture zones, respawn anchors, and ring buffers for deaths, jams, and radio spots. +// World observation layer: one flat per-frame snapshot of units, wrecks, capture zones, respawn +// anchors, and ring buffers for deaths, jams, and radio spots. Filling it from the game is +// wto_ai_world_refresh_common's job; this module only keeps and queries it, so the simulator +// loads it unchanged. options indenting = 2 options no_global_heap = true module wto_ai_world_common shared require ecs require math -require DagorMath -require Unit -require IGroundModel -require HeavyVehicleModel require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_order_common require %appGame.wtoai.wto_ai_types_common -require %appGame.wtoai.wto_ai_world_zones_common + [never_inline] def public wto_world_reset(var snap : WtoWorldSnap&) @@ -120,79 +118,3 @@ def public wto_world_find_unit(snap : WtoWorldSnap const&; eid : EntityId) : int if snap.units[i].eid == eid return i return -1 - -[never_inline] -def private wto_record_wreck_once(var snap : WtoWorldSnap&; eid : EntityId; u : Unit const?; gm : IGroundModel const?) - if gm == null || snap.wreckCount >= WTO_MAX_WRECKS - return - let box = gm.bodyBoundingBox - let wIdx = snap.wreckCount - snap.wrecks[wIdx].eid = eid - snap.wrecks[wIdx].pos = u.pos - snap.wrecks[wIdx].hullFwd = wto_xz_normalize(u.unitTm[0], float3(1.0, 0.0, 0.0)) - snap.wrecks[wIdx].halfLen = max(2.0, max(abs(box.boxMin.x), abs(box.boxMax.x))) - snap.wrecks[wIdx].halfWid = max(1.1, max(abs(box.boxMin.z), abs(box.boxMax.z))) - snap.wreckCount = wIdx + 1 - -[never_inline] -def private wto_refresh_units(var snap : WtoWorldSnap&) - snap.unitCount = 0 - snap.wreckCount = 0 - let maxDistSq = wto_sq(max(snap.battleRadius * 2.5, 2200.0)) - query() <| $ [es] (eid : EntityId; unit__ref : UnitRef) - let u = unit__ref.unit - if u == null || u.isDelayed - return - let gm = as_gm(u) - if snap.battleRadius > 1.0 && gm != null && wto_xz_dist_sq(u.pos, snap.battleCenter) > maxDistSq - return - if !u.isAlive - wto_record_wreck_once(snap, eid, u, gm) - return - if snap.unitCount >= WTO_MAX_UNITS - return - let army = int(u.army) - if army != 1 && army != 2 - return - let isGround = gm != null && as_hv(u) != null - let isAir = u.isFlightModelWrap - if !isGround && !isAir - return - var halfLen = 3.4 - var halfWid = 1.75 - if gm != null - let box = gm.bodyBoundingBox - halfLen = max(1.8, max(abs(box.boxMin.x), abs(box.boxMax.x))) - halfWid = max(0.9, max(abs(box.boxMin.z), abs(box.boxMax.z))) - let idx = snap.unitCount - snap.units[idx].eid = eid - snap.units[idx].army = army - snap.units[idx].pos = u.pos - snap.units[idx].vel = u.vel - snap.units[idx].hullFwd = wto_xz_normalize(u.unitTm[0], float3(1.0, 0.0, 0.0)) - snap.units[idx].halfLen = halfLen - snap.units[idx].halfWid = halfWid - snap.units[idx].engineRpm = gm != null ? clamp(abs(gm.engineRelativeRPM), 0.0, 1.2) : 0.0 - snap.units[idx].isAlive = true - snap.units[idx].isGround = isGround - snap.units[idx].isAir = isAir - snap.units[idx].isLightTag = false - snap.units[idx].isShooting = gm != null && (gm.isShooting || gm.hasMissilesInFlight) - snap.units[idx].isBurn = u.isBurn - snap.units[idx].isHuman = u.isHumanPlayer - snap.unitCount = idx + 1 - for i in range(snap.unitCount) - if snap.units[i].isGround - snap.units[i].isLightTag = has(snap.units[i].eid, "unit_tag__light_vehicle") - -[never_inline] -def public wto_world_refresh(now : float; var snap : WtoWorldSnap&) - snap.time = now - if snap.matchStartAt < -50.0 - snap.matchStartAt = now - wto_refresh_units(snap) - if now >= snap.nextCapRefreshAt - snap.nextCapRefreshAt = now + 0.5 - wto_world_refresh_caps(snap) - wto_world_refresh_bounds_and_spawns(snap) - snap.valid = true diff --git a/game-ai/ground/wto_ai_world_refresh_common.das b/game-ai/ground/wto_ai_world_refresh_common.das new file mode 100644 index 0000000..6a2b00b --- /dev/null +++ b/game-ai/ground/wto_ai_world_refresh_common.das @@ -0,0 +1,100 @@ +// Fills the world snapshot from the game's units every frame: live units with their pose (and +// the gun on trace frames), wrecks, capture zones, battle bounds and spawns. Only the runtime +// uses it; the simulator fills the same snapshot from its own world. +options indenting = 2 +options no_global_heap = true +module wto_ai_world_refresh_common shared + +require ecs +require math +require DagorMath +require Unit +require IGroundModel +require HeavyVehicleModel +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_world_zones_common +require %appGame.wtoai.wto_ai_unit_pose_common + +[never_inline] +def private wto_record_wreck_once(var snap : WtoWorldSnap&; eid : EntityId; u : Unit const?; gm : IGroundModel const?) + if gm == null || snap.wreckCount >= WTO_MAX_WRECKS + return + let box = gm.bodyBoundingBox + let wIdx = snap.wreckCount + snap.wrecks[wIdx].eid = eid + snap.wrecks[wIdx].pos = u.pos + snap.wrecks[wIdx].hullFwd = wto_xz_normalize(u.unitTm[0], float3(1.0, 0.0, 0.0)) + snap.wrecks[wIdx].halfLen = max(2.0, max(abs(box.boxMin.x), abs(box.boxMax.x))) + snap.wrecks[wIdx].halfWid = max(1.1, max(abs(box.boxMin.z), abs(box.boxMax.z))) + snap.wreckCount = wIdx + 1 + +// Pose of a live unit; the gun is read only on trace frames. +def private wto_unit_pose(var su : WtoUnitSnap&; u : Unit const?; sampleGun : bool) + su.pos = u.pos + su.vel = u.vel + su.hullFwd = wto_xz_normalize(u.unitTm[0], float3(1.0, 0.0, 0.0)) + su.hullFwd3 = u.unitTm[0] + su.hullLeft = u.unitTm[2] + su.hasGun = sampleGun && wto_pose_gun_dir(u, su.gunDir) + +[never_inline] +def private wto_refresh_units(var snap : WtoWorldSnap&; sampleGuns : bool) + snap.unitCount = 0 + snap.wreckCount = 0 + let maxDistSq = wto_sq(max(snap.battleRadius * 2.5, 2200.0)) + query() <| $ [es] (eid : EntityId; unit__ref : UnitRef) + let u = unit__ref.unit + if u == null || u.isDelayed + return + let gm = as_gm(u) + if snap.battleRadius > 1.0 && gm != null && wto_xz_dist_sq(u.pos, snap.battleCenter) > maxDistSq + return + if !u.isAlive + wto_record_wreck_once(snap, eid, u, gm) + return + if snap.unitCount >= WTO_MAX_UNITS + return + let army = int(u.army) + if army != 1 && army != 2 + return + let isGround = gm != null && as_hv(u) != null + let isAir = u.isFlightModelWrap + if !isGround && !isAir + return + var halfLen = 3.4 + var halfWid = 1.75 + if gm != null + let box = gm.bodyBoundingBox + halfLen = max(1.8, max(abs(box.boxMin.x), abs(box.boxMax.x))) + halfWid = max(0.9, max(abs(box.boxMin.z), abs(box.boxMax.z))) + let idx = snap.unitCount + snap.units[idx].eid = eid + snap.units[idx].army = army + wto_unit_pose(snap.units[idx], u, sampleGuns && isGround) + snap.units[idx].halfLen = halfLen + snap.units[idx].halfWid = halfWid + snap.units[idx].engineRpm = gm != null ? clamp(abs(gm.engineRelativeRPM), 0.0, 1.2) : 0.0 + snap.units[idx].isAlive = true + snap.units[idx].isGround = isGround + snap.units[idx].isAir = isAir + snap.units[idx].isLightTag = false + snap.units[idx].isShooting = gm != null && (gm.isShooting || gm.hasMissilesInFlight) + snap.units[idx].isBurn = u.isBurn + snap.units[idx].isHuman = u.isHumanPlayer + snap.unitCount = idx + 1 + for i in range(snap.unitCount) + if snap.units[i].isGround + snap.units[i].isLightTag = has(snap.units[i].eid, "unit_tag__light_vehicle") + +[never_inline] +def public wto_world_refresh(now : float; sampleGuns : bool; var snap : WtoWorldSnap&) + snap.time = now + if snap.matchStartAt < -50.0 + snap.matchStartAt = now + wto_refresh_units(snap, sampleGuns) + if now >= snap.nextCapRefreshAt + snap.nextCapRefreshAt = now + 0.5 + wto_world_refresh_caps(snap) + wto_world_refresh_bounds_and_spawns(snap) + snap.valid = true diff --git a/native/wto-ai-sim/build.ps1 b/native/wto-ai-sim/build.ps1 new file mode 100644 index 0000000..ff208fc --- /dev/null +++ b/native/wto-ai-sim/build.ps1 @@ -0,0 +1,58 @@ +<# + Build the ground AI simulator's runtime: the open-source daScript interpreter (daslang.exe) at a + pinned commit, with this project's native module `wto_sim` (native\wto-ai-sim\module). + + powershell -NoProfile -ExecutionPolicy Bypass -File native\wto-ai-sim\build.ps1 + + The daScript checkout goes to build\daslang (cloned when missing, about 420 MB), the build to + build\daslang-build. Neither is part of the repository. The module folder is linked into the + checkout as modules\wtoSim, so the daScript build compiles it with its own module rules and + daslang loads it at start. Needs Visual Studio with the x64 C++ tools; CMake and Ninja are the + ones Visual Studio bundles. +#> +param( + [string]$DasRoot = (Join-Path $PSScriptRoot '..\..\build\daslang'), + [string]$BuildDir = (Join-Path $PSScriptRoot '..\..\build\daslang-build') +) +$ErrorActionPreference = 'Stop' + +# daScript 0.6.6, the version the simulator was verified with (docs: tank-ai-revision-plan 3.3.1). +$pin = '7a51c4ef9927dbc92ecf4cab67ae41b41d239f4a' +$repo = 'https://github.com/GaijinEntertainment/daScript.git' + +if (-not (Test-Path (Join-Path $DasRoot '.git'))) { + git clone --no-checkout $repo $DasRoot + if ($LASTEXITCODE -ne 0) { throw 'git clone of daScript failed' } +} +$head = (git -C $DasRoot rev-parse HEAD 2>$null) +if ($head -ne $pin) { + git -C $DasRoot fetch origin $pin + git -C $DasRoot checkout --detach $pin + if ($LASTEXITCODE -ne 0) { throw "checkout of daScript $pin failed" } +} + +$moduleLink = Join-Path $DasRoot 'modules\wtoSim' +if (-not (Test-Path $moduleLink)) { + New-Item -ItemType Junction -Path $moduleLink -Target (Join-Path $PSScriptRoot 'module') | Out-Null +} + +$vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe' +$vs = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath +if (-not $vs) { throw 'Visual Studio with the x64 C++ tools was not found' } +$vcvars = Join-Path $vs 'VC\Auxiliary\Build\vcvars64.bat' +$cmakeDir = Join-Path $vs 'Common7\IDE\CommonExtensions\Microsoft\CMake' +$cmake = Join-Path $cmakeDir 'CMake\bin\cmake.exe' +$ninja = Join-Path $cmakeDir 'Ninja\ninja.exe' + +# Only the interpreter and the core runtime; every optional module of daScript stays off. +$off = @('ACCELERATE', 'AOT_EXAMPLES', 'AUDIO', 'CLANG_BIND', 'CLIPBOARD', 'CRYPTO', 'CUDA', 'FLEX_BISON', 'GLFW', 'HV', + 'IMGUI', 'LLVM', 'MESHOPTIMIZER', 'METAL', 'PUGIXML', 'SMT', 'SQLITE', 'STBIMAGE', 'STDDLG', 'TERMINAL', 'TESTS', + 'TREE_SITTER', 'TUTORIAL', 'VULKAN') | ForEach-Object { "-DDAS_$($_)_DISABLED=ON" } +$native = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path -replace '\\', '/' +$configure = "`"$cmake`" -S `"$DasRoot`" -B `"$BuildDir`" -G Ninja -DCMAKE_MAKE_PROGRAM=`"$ninja`" " + + "-DCMAKE_BUILD_TYPE=Release -DDAS_TOOLS_DISABLED=OFF -DWTO_SIM_NATIVE_ROOT=`"$native`" $($off -join ' ')" +cmd /c "`"$vcvars`" >nul && $configure" +if ($LASTEXITCODE -ne 0) { throw "cmake configure failed with $LASTEXITCODE" } +cmd /c "`"$vcvars`" >nul && `"$cmake`" --build `"$BuildDir`" --target daslang dasModuleWtoSim" +if ($LASTEXITCODE -ne 0) { throw "cmake build failed with $LASTEXITCODE" } +Write-Output (Join-Path $DasRoot 'bin\daslang.exe') diff --git a/native/wto-ai-sim/module/.das_module b/native/wto-ai-sim/module/.das_module new file mode 100644 index 0000000..e3cac50 --- /dev/null +++ b/native/wto-ai-sim/module/.das_module @@ -0,0 +1,9 @@ +options gen2 +require daslib/fio + +[export] +def initialize(project_path : string) { + if (das_is_dll_build()) { + register_dynamic_module("{project_path}/dasModuleWtoSim.shared_module", "Module_WtoSim") + } +} diff --git a/native/wto-ai-sim/module/.gitignore b/native/wto-ai-sim/module/.gitignore new file mode 100644 index 0000000..b642b90 --- /dev/null +++ b/native/wto-ai-sim/module/.gitignore @@ -0,0 +1,6 @@ +# The daScript build writes the shared module next to its sources. +*.shared_module +*.pdb +*.lib +*.exp +*.ilk diff --git a/native/wto-ai-sim/module/CMakeLists.txt b/native/wto-ai-sim/module/CMakeLists.txt new file mode 100644 index 0000000..37e31f2 --- /dev/null +++ b/native/wto-ai-sim/module/CMakeLists.txt @@ -0,0 +1,49 @@ +# Ground AI simulator module `wto_sim` for the open-source daScript build. native/wto-ai-sim/build.ps1 +# links this folder into the daScript checkout as modules/wtoSim, so its build includes it like its +# own modules and daslang loads the shared module at start (.das_module). +IF ((NOT DAS_WTOSIM_INCLUDED) AND ((NOT ${DAS_WTOSIM_DISABLED}) OR (NOT DEFINED DAS_WTOSIM_DISABLED))) + SET(DAS_WTOSIM_INCLUDED TRUE) + MESSAGE(STATUS "wtoSim module included.") + + # The project's native folder: given by build.ps1, else found through the link. + IF(DEFINED WTO_SIM_NATIVE_ROOT) + SET(WTO_SIM_NATIVE ${WTO_SIM_NATIVE_ROOT}) + ELSE() + FILE(REAL_PATH "${CMAKE_CURRENT_LIST_DIR}" _wto_sim_here) + GET_FILENAME_COMPONENT(WTO_SIM_NATIVE "${_wto_sim_here}/../.." ABSOLUTE) + ENDIF() + SET(WTO_SIM_DIR ${CMAKE_CURRENT_LIST_DIR}) + SET(WTO_SIM_NAV_DIR ${WTO_SIM_NATIVE}/wto-nav) + SET(WTO_SIM_DETOUR_DIR ${WTO_SIM_NATIVE}/third_party/recastnavigation/Detour) + + # The game's navigation engine and request protocol with upstream Detour, at their own warning level. + FILE(GLOB WTO_SIM_DETOUR_SRC ${WTO_SIM_DETOUR_DIR}/Source/*.cpp) + ADD_LIBRARY(wtoSimNav STATIC + ${WTO_SIM_DETOUR_SRC} + ${WTO_SIM_NAV_DIR}/wto_nav_runtime.cpp + ${WTO_SIM_NAV_DIR}/wto_nav_paths.cpp + ${WTO_SIM_NAV_DIR}/wto_nav_queries.cpp + ${WTO_SIM_NAV_DIR}/wto_nav_protocol.c + ) + TARGET_INCLUDE_DIRECTORIES(wtoSimNav PUBLIC + $ $) + # Every translation unit that sees dtQueryFilter must agree on its layout (wto_nav_runtime.cpp). + TARGET_COMPILE_DEFINITIONS(wtoSimNav PUBLIC DT_VIRTUAL_QUERYFILTER PRIVATE _CRT_SECURE_NO_WARNINGS WIN32_LEAN_AND_MEAN) + SET_TARGET_PROPERTIES(wtoSimNav PROPERTIES POSITION_INDEPENDENT_CODE ON) + # The module's static library is in daScript's export set, so what it links must be too. + INSTALL(TARGETS wtoSimNav EXPORT DASTargets ARCHIVE DESTINATION ${DAS_INSTALL_LIBDIR}) + + SET(WTO_SIM_MODULE_SRC + ${WTO_SIM_DIR}/src/wto_sim_module.cpp + ${WTO_SIM_DIR}/src/sim_geo.cpp + ${WTO_SIM_DIR}/src/sim_geo.h + ${WTO_SIM_DIR}/src/sim_nav.cpp + ${WTO_SIM_DIR}/src/sim_nav.h + ) + ADD_MODULE_CPP(WtoSim) + ADD_MODULE_LIB(libDasModuleWtoSim dasModuleWtoSim ${WTO_SIM_MODULE_SRC}) + TARGET_LINK_LIBRARIES(libDasModuleWtoSim PUBLIC wtoSimNav) + TARGET_LINK_LIBRARIES(dasModuleWtoSim PUBLIC wtoSimNav) + SETUP_CPP11(libDasModuleWtoSim) + SETUP_CPP11(dasModuleWtoSim) +ENDIF() diff --git a/native/wto-ai-sim/module/src/sim_geo.cpp b/native/wto-ai-sim/module/src/sim_geo.cpp new file mode 100644 index 0000000..d56b033 --- /dev/null +++ b/native/wto-ai-sim/module/src/sim_geo.cpp @@ -0,0 +1,443 @@ +// Terrain and object geometry of the simulated level (see sim_geo.h). Objects are indexed on an +// 8 m grid in XZ, with each cell's highest triangle and highest ground; a ray walks the cells it +// crosses, tests their triangles and marches the terrain only where it dips low enough. +#include "sim_geo.h" + +#include +#include +#include +#include +#include + +namespace wto_sim { + +namespace { + +const char GEO_MAGIC[8] = { 'W', 'T', 'O', 'G', 'E', 'O', '\0', '\x01' }; +const uint32_t GEO_MAX_VERSION = 3; +const float CELL_M = 8.0f; +const float BURIED_M = 0.3f; + +#pragma pack(push, 1) +struct GeoHeader { + char magic[8]; + uint32_t version; + uint32_t flags; + uint8_t everSha1[20]; + float waterLevel; + float boundsMin[2]; + float boundsMax[2]; + uint32_t hmWidth; + uint32_t hmHeight; + float hmCellSize; + float hmOrigin[2]; + uint32_t obsVertCount; + uint32_t obsTriCount; +}; +#pragma pack(pop) + +// One triangle ready for the ray test: a corner, two edges, and the group it belongs to. +struct Tri { + float v0[3]; + float e1[3]; + float e2[3]; + int kind; +}; + +// Obstacle class (WtoObstacleClass) to ray group. +const int KIND_OF_CLASS[8] = { RAY_HARD, RAY_BRIDGE, RAY_CRUSHABLE, RAY_TREE, RAY_TREE, RAY_HARD, RAY_PLATFORM, RAY_PLATFORM }; + +struct Geo { + bool loaded = false; + float water = -1.0e6f; + uint32_t hmW = 0; + uint32_t hmH = 0; + float hmCell = 1.0f; + float hmOrigin[2] = { 0.0f, 0.0f }; + std::vector heights; + std::vector tris; + // Grid over the objects: cell (c, r) holds items[offsets[i] .. offsets[i + 1]). + float gridOrigin[2] = { 0.0f, 0.0f }; + int gridCols = 0; + int gridRows = 0; + std::vector offsets; + std::vector items; + std::vector cellTop; + // Highest terrain sample in each cell (with its border), so a ray above it skips the march. + std::vector cellGround; + // Ray id stamped on each triangle already tested by the current ray. + std::vector stamp; + uint32_t rayId = 0; +}; + +Geo g_geo; + +float height_at(const Geo & g, float x, float z) +{ + if (g.hmW < 2 || g.hmH < 2) + return 0.0f; + const float fx = std::min(float(g.hmW) - 1.001f, std::max(0.0f, (x - g.hmOrigin[0]) / g.hmCell)); + const float fz = std::min(float(g.hmH) - 1.001f, std::max(0.0f, (z - g.hmOrigin[1]) / g.hmCell)); + const uint32_t x0 = uint32_t(fx); + const uint32_t z0 = uint32_t(fz); + const float tx = fx - float(x0); + const float tz = fz - float(z0); + const float * row0 = &g.heights[size_t(z0) * g.hmW + x0]; + const float * row1 = row0 + g.hmW; + const float a = row0[0] + (row0[1] - row0[0]) * tx; + const float b = row1[0] + (row1[1] - row1[0]) * tx; + return a + (b - a) * tz; +} + +void sub(const float a[3], const float b[3], float out[3]) +{ + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; +} + +void cross(const float a[3], const float b[3], float out[3]) +{ + out[0] = a[1] * b[2] - a[2] * b[1]; + out[1] = a[2] * b[0] - a[0] * b[2]; + out[2] = a[0] * b[1] - a[1] * b[0]; +} + +float dot(const float a[3], const float b[3]) +{ + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +} + +bool read_bytes(std::ifstream & in, void * out, size_t size) +{ + in.read(static_cast(out), std::streamsize(size)); + return bool(in); +} + +bool buried(const Geo & g, const float * v) +{ + return v[1] < height_at(g, v[0], v[2]) - BURIED_M; +} + +// Keeps the triangles that are not wholly under the terrain, as ready-to-test records. +void keep_triangles(Geo & g, const std::vector & verts, const std::vector & raw, uint32_t count) +{ + g.tris.clear(); + g.tris.reserve(count); + const uint32_t vertCount = uint32_t(verts.size() / 3); + for (uint32_t i = 0; i < count; i++) { + const uint8_t * rec = &raw[size_t(i) * 13]; + uint32_t idx[3]; + std::memcpy(idx, rec, sizeof(idx)); + if (idx[0] >= vertCount || idx[1] >= vertCount || idx[2] >= vertCount) + continue; + const float * a = &verts[size_t(idx[0]) * 3]; + const float * b = &verts[size_t(idx[1]) * 3]; + const float * c = &verts[size_t(idx[2]) * 3]; + if (buried(g, a) && buried(g, b) && buried(g, c)) + continue; + Tri t; + std::memcpy(t.v0, a, sizeof(t.v0)); + sub(b, a, t.e1); + sub(c, a, t.e2); + t.kind = KIND_OF_CLASS[rec[12] & 7]; + g.tris.push_back(t); + } +} + +void tri_bounds(const Tri & t, float lo[3], float hi[3]) +{ + for (int k = 0; k < 3; k++) { + const float b = t.v0[k] + t.e1[k]; + const float c = t.v0[k] + t.e2[k]; + lo[k] = std::min(t.v0[k], std::min(b, c)); + hi[k] = std::max(t.v0[k], std::max(b, c)); + } +} + +void cell_span(const Geo & g, const float lo[3], const float hi[3], int & c0, int & c1, int & r0, int & r1) +{ + c0 = std::clamp(int(std::floor((lo[0] - g.gridOrigin[0]) / CELL_M)), 0, g.gridCols - 1); + c1 = std::clamp(int(std::floor((hi[0] - g.gridOrigin[0]) / CELL_M)), 0, g.gridCols - 1); + r0 = std::clamp(int(std::floor((lo[2] - g.gridOrigin[1]) / CELL_M)), 0, g.gridRows - 1); + r1 = std::clamp(int(std::floor((hi[2] - g.gridOrigin[1]) / CELL_M)), 0, g.gridRows - 1); +} + +// Two passes over the triangles: count per cell, then fill the cells' item lists. +void build_grid(Geo & g, const float boundsMin[2], const float boundsMax[2]) +{ + g.gridOrigin[0] = boundsMin[0]; + g.gridOrigin[1] = boundsMin[1]; + g.gridCols = std::max(1, int(std::ceil((boundsMax[0] - boundsMin[0]) / CELL_M))); + g.gridRows = std::max(1, int(std::ceil((boundsMax[1] - boundsMin[1]) / CELL_M))); + const size_t cells = size_t(g.gridCols) * size_t(g.gridRows); + std::vector counts(cells, 0); + g.cellTop.assign(cells, -1.0e9f); + float lo[3], hi[3]; + int c0, c1, r0, r1; + for (const Tri & t : g.tris) { + tri_bounds(t, lo, hi); + cell_span(g, lo, hi, c0, c1, r0, r1); + for (int r = r0; r <= r1; r++) { + for (int c = c0; c <= c1; c++) { + const size_t i = size_t(r) * g.gridCols + c; + counts[i]++; + g.cellTop[i] = std::max(g.cellTop[i], hi[1]); + } + } + } + g.offsets.assign(cells + 1, 0); + for (size_t i = 0; i < cells; i++) + g.offsets[i + 1] = g.offsets[i] + counts[i]; + g.items.assign(g.offsets[cells], 0); + std::fill(counts.begin(), counts.end(), 0); + for (uint32_t ti = 0; ti < uint32_t(g.tris.size()); ti++) { + tri_bounds(g.tris[ti], lo, hi); + cell_span(g, lo, hi, c0, c1, r0, r1); + for (int r = r0; r <= r1; r++) { + for (int c = c0; c <= c1; c++) { + const size_t i = size_t(r) * g.gridCols + c; + g.items[g.offsets[i] + counts[i]++] = ti; + } + } + } + g.stamp.assign(g.tris.size(), 0); + g.rayId = 0; +} + +void build_ground_tops(Geo & g) +{ + g.cellGround.assign(size_t(g.gridCols) * g.gridRows, -1.0e9f); + for (int r = 0; r < g.gridRows; r++) { + for (int c = 0; c < g.gridCols; c++) { + const float x0 = g.gridOrigin[0] + float(c) * CELL_M; + const float z0 = g.gridOrigin[1] + float(r) * CELL_M; + float top = -1.0e9f; + for (float z = z0 - g.hmCell; z <= z0 + CELL_M + g.hmCell; z += g.hmCell) + for (float x = x0 - g.hmCell; x <= x0 + CELL_M + g.hmCell; x += g.hmCell) + top = std::max(top, height_at(g, x, z)); + g.cellGround[size_t(r) * g.gridCols + c] = top; + } + } +} + +// Möller–Trumbore, both faces. Returns the distance along the ray, or -1. +float ray_tri(const Tri & t, const float p[3], const float dir[3]) +{ + float pv[3], tv[3], qv[3]; + cross(dir, t.e2, pv); + const float det = dot(t.e1, pv); + if (std::fabs(det) < 1.0e-9f) + return -1.0f; + const float inv = 1.0f / det; + sub(p, t.v0, tv); + const float u = dot(tv, pv) * inv; + if (u < 0.0f || u > 1.0f) + return -1.0f; + cross(tv, t.e1, qv); + const float v = dot(dir, qv) * inv; + if (v < 0.0f || u + v > 1.0f) + return -1.0f; + return dot(t.e2, qv) * inv; +} + +void tri_normal(const Tri & t, const float dir[3], float out[3]) +{ + cross(t.e1, t.e2, out); + const float len = std::sqrt(dot(out, out)); + const float s = (len > 0.0f ? 1.0f / len : 0.0f) * (dot(out, dir) > 0.0f ? -1.0f : 1.0f); + out[0] *= s; + out[1] *= s; + out[2] *= s; +} + +// Tests the cell's triangles of the selected groups; keeps the nearest hit within maxT. +void test_cell(Geo & g, size_t cell, const float p[3], const float dir[3], float maxT, int mask, RayHit & best) +{ + for (uint32_t k = g.offsets[cell]; k < g.offsets[cell + 1]; k++) { + const uint32_t ti = g.items[k]; + if (g.stamp[ti] == g.rayId) + continue; + g.stamp[ti] = g.rayId; + const Tri & t = g.tris[ti]; + if ((t.kind & mask) == 0) + continue; + const float d = ray_tri(t, p, dir); + if (d >= 0.0f && d <= maxT && (best.dist < 0.0f || d < best.dist)) { + best.dist = d; + best.kind = t.kind; + tri_normal(t, dir, best.normal); + } + } +} + +void terrain_normal(const Geo & g, float x, float z, float out[3]) +{ + const float e = g.hmCell; + const float dx = height_at(g, x + e, z) - height_at(g, x - e, z); + const float dz = height_at(g, x, z + e) - height_at(g, x, z - e); + out[0] = -dx; + out[1] = 2.0f * e; + out[2] = -dz; + const float len = std::sqrt(dot(out, out)); + out[0] /= len; + out[1] /= len; + out[2] /= len; +} + +// Height of the ray above the terrain at distance t. +float above_ground(const Geo & g, const float p[3], const float dir[3], float t) +{ + return p[1] + dir[1] * t - height_at(g, p[0] + dir[0] * t, p[2] + dir[2] * t); +} + +// Terrain crossing of the ray within [t0, t1], marched at half the heightmap spacing and bisected. +bool terrain_in(const Geo & g, const float p[3], const float dir[3], float t0, float t1, RayHit & best) +{ + const float step = g.hmCell * 0.5f; + float prevT = t0; + if (above_ground(g, p, dir, t0) <= 0.0f) { + best.dist = t0; + } else { + bool crossed = false; + for (float t = std::min(t0 + step, t1); prevT < t1; t = std::min(t + step, t1)) { + if (above_ground(g, p, dir, t) <= 0.0f) { + float lo = prevT; + float hi = t; + for (int i = 0; i < 8; i++) { + const float mid = 0.5f * (lo + hi); + if (above_ground(g, p, dir, mid) > 0.0f) + lo = mid; + else + hi = mid; + } + best.dist = hi; + crossed = true; + break; + } + prevT = t; + } + if (!crossed) + return false; + } + best.kind = 0; + terrain_normal(g, p[0] + dir[0] * best.dist, p[2] + dir[2] * best.dist, best.normal); + return true; +} + +// Walks the grid cells under the ray (2D DDA in XZ). In each cell the terrain is marched only when +// the ray dips below the cell's highest ground, the objects tested only when it dips below the +// cell's highest triangle. Stops at the first cell that holds a hit. +void ray_walk(Geo & g, const float p[3], const float dir[3], float len, int mask, RayHit & best) +{ + if (++g.rayId == 0) { + std::fill(g.stamp.begin(), g.stamp.end(), 0); + g.rayId = 1; + } + const bool terrain = (mask & RAY_TERRAIN) != 0; + const int objects = mask & ~RAY_TERRAIN; + const float gx = (p[0] - g.gridOrigin[0]) / CELL_M; + const float gz = (p[2] - g.gridOrigin[1]) / CELL_M; + int c = int(std::floor(gx)); + int r = int(std::floor(gz)); + const int stepC = dir[0] > 0.0f ? 1 : -1; + const int stepR = dir[2] > 0.0f ? 1 : -1; + const float big = 1.0e30f; + const float dtC = std::fabs(dir[0]) > 1.0e-7f ? CELL_M / std::fabs(dir[0]) : big; + const float dtR = std::fabs(dir[2]) > 1.0e-7f ? CELL_M / std::fabs(dir[2]) : big; + float nextC = std::fabs(dir[0]) > 1.0e-7f ? ((stepC > 0 ? float(c + 1) - gx : gx - float(c)) * dtC) : big; + float nextR = std::fabs(dir[2]) > 1.0e-7f ? ((stepR > 0 ? float(r + 1) - gz : gz - float(r)) * dtR) : big; + float t0 = 0.0f; + while (t0 <= len) { + const float t1 = std::min(len, std::min(nextC, nextR)); + const bool inside = c >= 0 && r >= 0 && c < g.gridCols && r < g.gridRows; + const size_t cell = inside ? size_t(r) * g.gridCols + c : 0; + const float lowY = std::min(p[1] + dir[1] * t0, p[1] + dir[1] * t1); + if (objects != 0 && inside && lowY <= g.cellTop[cell]) + test_cell(g, cell, p, dir, len, objects, best); + const float groundEnd = best.dist >= 0.0f ? std::min(t1, best.dist) : t1; + if (terrain && (!inside || lowY <= g.cellGround[cell]) && terrain_in(g, p, dir, t0, groundEnd, best)) + return; + if (best.dist >= 0.0f && best.dist <= t1) + return; + if (t1 >= len) + return; + if (nextC < nextR) { + c += stepC; + t0 = nextC; + nextC += dtC; + } else { + r += stepR; + t0 = nextR; + nextR += dtR; + } + } +} + +} + +bool geo_load(const std::string & path, std::string & error) +{ + Geo g; + std::ifstream in(path, std::ios::binary); + GeoHeader h; + if (!in || !read_bytes(in, &h, sizeof(h))) { + error = "cannot read " + path; + return false; + } + if (std::memcmp(h.magic, GEO_MAGIC, sizeof(GEO_MAGIC)) != 0 || h.version < 1 || h.version > GEO_MAX_VERSION) { + error = "not a .wtogeo file of a known version"; + return false; + } + g.water = h.waterLevel; + g.hmW = h.hmWidth; + g.hmH = h.hmHeight; + g.hmCell = h.hmCellSize > 0.0f ? h.hmCellSize : 1.0f; + g.hmOrigin[0] = h.hmOrigin[0]; + g.hmOrigin[1] = h.hmOrigin[1]; + g.heights.resize(size_t(h.hmWidth) * h.hmHeight); + std::vector verts(size_t(h.obsVertCount) * 3); + std::vector raw(size_t(h.obsTriCount) * 13); + if (!read_bytes(in, g.heights.data(), g.heights.size() * sizeof(float)) || + !read_bytes(in, verts.data(), verts.size() * sizeof(float)) || !read_bytes(in, raw.data(), raw.size())) { + error = "file is truncated"; + return false; + } + keep_triangles(g, verts, raw, h.obsTriCount); + build_grid(g, h.boundsMin, h.boundsMax); + build_ground_tops(g); + g.loaded = true; + g_geo = std::move(g); + return true; +} + +bool geo_loaded() +{ + return g_geo.loaded; +} + +float geo_height(float x, float z) +{ + return height_at(g_geo, x, z); +} + +float geo_water_level() +{ + return g_geo.water; +} + +RayHit geo_ray(const float p[3], const float dir[3], float len, int mask) +{ + RayHit best; + if (!g_geo.loaded || !(len > 0.0f)) + return best; + ray_walk(g_geo, p, dir, len, mask, best); + return best; +} + +uint32_t geo_triangle_count() +{ + return uint32_t(g_geo.tris.size()); +} + +} diff --git a/native/wto-ai-sim/module/src/sim_geo.h b/native/wto-ai-sim/module/src/sim_geo.h new file mode 100644 index 0000000..2f731b8 --- /dev/null +++ b/native/wto-ai-sim/module/src/sim_geo.h @@ -0,0 +1,42 @@ +// The simulator's world geometry: the level's terrain heightmap and the collision triangles of its +// placed objects, read from the navigation extractor's `.wtogeo` (native/wto-nav/wto_nav_format.h), +// which is also what the AI lab's 3D view draws. Rays answer the AI script's line of sight, ground +// and obstacle probes in place of the engine's traces. +#pragma once + +#include +#include + +namespace wto_sim { + +// Ray masks: terrain plus groups of WtoObstacleClass. +enum RayMask : int { + RAY_TERRAIN = 1, + RAY_HARD = 2, // buildings, rocks, walls (hard solid and hard without cover) + RAY_BRIDGE = 4, // bridge decks + RAY_CRUSHABLE = 8, // fences, bushes, light objects a tank drives through + RAY_TREE = 16, // tree trunks + RAY_PLATFORM = 32, // walkable tops of placed objects + RAY_ALL = 63, +}; + +// What a ray hit: -1 nothing, 0 terrain, otherwise the RayMask bit of the object group. +struct RayHit { + float dist = -1.0f; + int kind = -1; + float normal[3] = { 0.0f, 1.0f, 0.0f }; +}; + +// Loads the geometry; on failure returns false and `error` says why. Replaces what was loaded. +bool geo_load(const std::string & path, std::string & error); +bool geo_loaded(); +// Bilinear terrain height (clamped to the heightmap); 0 when nothing is loaded. +float geo_height(float x, float z); +// The level's water level, or -1e6 when it has none. +float geo_water_level(); +// First hit of the ray p + dir * t for t in [0, len], against what `mask` selects. `dir` is unit. +RayHit geo_ray(const float p[3], const float dir[3], float len, int mask); +// Triangles kept after dropping buried faces, and grid cells, for the load log. +uint32_t geo_triangle_count(); + +} diff --git a/native/wto-ai-sim/module/src/sim_nav.cpp b/native/wto-ai-sim/module/src/sim_nav.cpp new file mode 100644 index 0000000..92c2864 --- /dev/null +++ b/native/wto-ai-sim/module/src/sim_nav.cpp @@ -0,0 +1,137 @@ +// "wtoNav" requests in the simulator (see sim_nav.h). The script's DataBlock arrives as text +// lines; queries go through the shared protocol, the pack ops are answered here: the simulated +// battle's pack is set by the host, so there is no prefetch and no fingerprint check. +#include "sim_nav.h" + +#include "wto_nav_protocol.h" +#include "wto_nav_runtime.h" + +#include +#include +#include + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include + +namespace wto_sim { + +namespace { + +struct Block { + std::map values; + std::vector> reply; +}; + +std::string g_pack; +std::string g_level; + +const char * block_get(const void * blk, const char * name) +{ + const Block * b = static_cast(blk); + const auto it = b->values.find(name); + return it == b->values.end() ? "" : it->second.c_str(); +} + +void block_set(Block * b, const char * name, const std::string & value) +{ + b->values[name] = value; + b->reply.emplace_back(name, value); +} + +void block_set_str(void * blk, const char * name, const char * value) +{ + block_set(static_cast(blk), name, value ? value : ""); +} + +void block_set_int(void * blk, const char * name, int32_t value) +{ + block_set(static_cast(blk), name, std::to_string(value)); +} + +void parse(const std::string & text, Block & b) +{ + size_t at = 0; + while (at < text.size()) { + size_t end = text.find('\n', at); + if (end == std::string::npos) + end = text.size(); + const size_t eq = text.find('=', at); + if (eq != std::string::npos && eq < end) + b.values[text.substr(at, eq - at)] = text.substr(eq + 1, end - eq - 1); + at = end + 1; + } +} + +std::wstring widen(const std::string & s) +{ + if (s.empty()) + return std::wstring(); + const int n = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), int(s.size()), nullptr, 0); + std::wstring out(size_t(n), L'\0'); + MultiByteToWideChar(CP_UTF8, 0, s.c_str(), int(s.size()), out.data(), n); + return out; +} + +void load_map(const WtoNavBlock & nb, Block & b) +{ + WtoNavLoadInfo info = {}; + std::string reason; + if (g_pack.empty()) { + reason = "no pack set for the simulated level"; + } else { + wto_nav_protocol_setup(&nb); + wto_nav_load(widen(g_pack).c_str(), nullptr, &info); + if (info.result != WTO_NAV_LOAD_OK) + reason = info.detail; + } + const bool ok = reason.empty(); + const bool fallback = std::string(block_get(&b, "allowFallback")) != "0"; + block_set(&b, "state", ok ? "loaded" : fallback ? "fallback" : "failed"); + block_set(&b, "fingerprint", "unknown"); + block_set(&b, "level", g_level); + block_set(&b, "reason", reason); + block_set_int(&b, "tiers", ok ? int32_t(info.tiers) : 0); + block_set_int(&b, "covers", ok ? int32_t(info.covers) : 0); +} + +} + +void nav_set_pack(const std::string & packPath, const std::string & level) +{ + g_pack = packPath; + g_level = level; +} + +std::string nav_request(const std::string & request) +{ + Block b; + parse(request, b); + WtoNavBlock nb; + nb.blk = &b; + nb.get_str = block_get; + nb.set_str = block_set_str; + nb.set_int = block_set_int; + const std::string op = block_get(&b, "op"); + if (!wto_nav_protocol_query(&nb, op.c_str())) { + if (op == "load_map") { + load_map(nb, b); + } else if (op == "prefetch") { + block_set(&b, "state", "skipped"); + block_set(&b, "level", g_level); + block_set(&b, "reason", "the simulator loads on load_map"); + } else if (op == "unload_map") { + wto_nav_unload(); + block_set_int(&b, "ok", 1); + } else { + std::fprintf(stderr, "WTO_NAV|BAD_REQUEST|op=%s\n", op.c_str()); + } + } + std::string out; + for (const auto & kv : b.reply) + out += kv.first + "=" + kv.second + "\n"; + return out; +} + +} diff --git a/native/wto-ai-sim/module/src/sim_nav.h b/native/wto-ai-sim/module/src/sim_nav.h new file mode 100644 index 0000000..04b84dd --- /dev/null +++ b/native/wto-ai-sim/module/src/sim_nav.h @@ -0,0 +1,15 @@ +// The simulator's side of the AI script's "wtoNav" requests: the same navigation engine and +// request protocol as the game (native/wto-nav), fed from the simulated level's pack. +#pragma once + +#include + +namespace wto_sim { + +// The pack load_map will read; the level name is reported back to the script. +void nav_set_pack(const std::string & packPath, const std::string & level); + +// Answers one request. Both are "key=value" lines; the reply holds only the values written back. +std::string nav_request(const std::string & request); + +} diff --git a/native/wto-ai-sim/module/src/wto_sim_module.cpp b/native/wto-ai-sim/module/src/wto_sim_module.cpp new file mode 100644 index 0000000..cd1e34f --- /dev/null +++ b/native/wto-ai-sim/module/src/wto_sim_module.cpp @@ -0,0 +1,93 @@ +// daScript module `wto_sim`: what the ground AI simulator's scripts need from native code, the +// level geometry (rays, ground height, water) and the navigation engine behind "wtoNav" requests. +// The engine stand-ins of the simulator (Dacoll, RendInst, Mission...) are scripts built on it. +#include "daScript/misc/platform.h" + +#include "daScript/ast/ast.h" +#include "daScript/ast/ast_interop.h" +#include "daScript/ast/ast_handle.h" + +#include "sim_geo.h" +#include "sim_nav.h" + +#include + +namespace das { + +// Loads the level geometry; prints why when it fails. +static bool wto_sim_geo_load(const char * path) +{ + std::string error; + if (wto_sim::geo_load(path ? path : "", error)) { + std::printf("WTO_SIM|GEO_LOADED|path=%s|tris=%u\n", path, wto_sim::geo_triangle_count()); + return true; + } + std::printf("WTO_SIM|GEO_FAILED|path=%s|reason=%s\n", path ? path : "", error.c_str()); + return false; +} + +static float wto_sim_geo_height(float x, float z) +{ + return wto_sim::geo_height(x, z); +} + +static float wto_sim_geo_water() +{ + return wto_sim::geo_water_level(); +} + +// Distance to the first hit of the ray, or -1; `kind` is 0 for terrain, else the object group. +static float wto_sim_geo_ray(float3 p, float3 dir, float len, int32_t mask, int32_t & kind, float3 & normal) +{ + const float pa[3] = { p.x, p.y, p.z }; + const float da[3] = { dir.x, dir.y, dir.z }; + const wto_sim::RayHit hit = wto_sim::geo_ray(pa, da, len, mask); + kind = hit.kind; + normal = float3(hit.normal[0], hit.normal[1], hit.normal[2]); + return hit.dist; +} + +static void wto_sim_nav_set_pack(const char * packPath, const char * level) +{ + wto_sim::nav_set_pack(packPath ? packPath : "", level ? level : ""); +} + +static char * wto_sim_nav_request(const char * request, Context * context, LineInfoArg * at) +{ + const std::string reply = wto_sim::nav_request(request ? request : ""); + return context->allocateString(reply, at); +} + +class Module_WtoSim : public Module { +public: + Module_WtoSim() : Module("wto_sim") { + ModuleLibrary lib; + lib.addModule(this); + lib.addBuiltInModule(); + addConstant(*this, "WTO_SIM_RAY_TERRAIN", int32_t(wto_sim::RAY_TERRAIN)); + addConstant(*this, "WTO_SIM_RAY_HARD", int32_t(wto_sim::RAY_HARD)); + addConstant(*this, "WTO_SIM_RAY_BRIDGE", int32_t(wto_sim::RAY_BRIDGE)); + addConstant(*this, "WTO_SIM_RAY_CRUSHABLE", int32_t(wto_sim::RAY_CRUSHABLE)); + addConstant(*this, "WTO_SIM_RAY_TREE", int32_t(wto_sim::RAY_TREE)); + addConstant(*this, "WTO_SIM_RAY_PLATFORM", int32_t(wto_sim::RAY_PLATFORM)); + addConstant(*this, "WTO_SIM_RAY_ALL", int32_t(wto_sim::RAY_ALL)); + addExtern(*this, lib, "wto_sim_geo_load", + SideEffects::modifyExternal, "wto_sim_geo_load")->args({"path"}); + addExtern(*this, lib, "wto_sim_geo_height", + SideEffects::accessExternal, "wto_sim_geo_height")->args({"x", "z"}); + addExtern(*this, lib, "wto_sim_geo_water", + SideEffects::accessExternal, "wto_sim_geo_water"); + addExtern(*this, lib, "wto_sim_geo_ray", + SideEffects::modifyArgumentAndExternal, "wto_sim_geo_ray") + ->args({"p", "dir", "len", "mask", "kind", "normal"}); + addExtern(*this, lib, "wto_sim_nav_set_pack", + SideEffects::modifyExternal, "wto_sim_nav_set_pack")->args({"pack", "level"}); + addExtern(*this, lib, "wto_sim_nav_request", + SideEffects::modifyExternal, "wto_sim_nav_request")->args({"request", "context", "at"}); + } +}; + +REGISTER_DYN_MODULE(Module_WtoSim, Module_WtoSim); +} + +REGISTER_MODULE_IN_NAMESPACE(Module_WtoSim, das); diff --git a/native/wto-nav/wto_nav_protocol.c b/native/wto-nav/wto_nav_protocol.c new file mode 100644 index 0000000..ed98fad --- /dev/null +++ b/native/wto-nav/wto_nav_protocol.c @@ -0,0 +1,247 @@ +/* The "wtoNav" request protocol on top of the navigation engine (see wto_nav_protocol.h). */ +#include "wto_nav_protocol.h" +#include "wto_nav_runtime.h" + +#include +#include +#include + +/* Costs in the order of WtoPolyArea; empty names are areas the mesh never carries. */ +static const char *const AREA_KEYS[WTO_NAV_RT_AREA_COUNT] = { + "", "road", "bridge", "ground", "rough", "forest", "crushable", "shallowWater", "", "exposed", "", "", +}; + +static float get_real(const WtoNavBlock *b, const char *name, float def) +{ + const char *text = b->get_str(b->blk, name); + char *end; + float value; + if (text == NULL || text[0] == '\0') + return def; + value = strtof(text, &end); + return (*end == '\0' && value == value) ? value : def; +} + +static long get_long(const WtoNavBlock *b, const char *name, long def) +{ + const char *text = b->get_str(b->blk, name); + char *end; + long value; + if (text == NULL || text[0] == '\0') + return def; + value = strtol(text, &end, 10); + return *end == '\0' ? value : def; +} + +/* x, y, z */ +static void get_vec(const WtoNavBlock *b, char prefix, float out[3]) +{ + char key[3]; + key[0] = prefix; + key[1] = 'x'; + key[2] = '\0'; + out[0] = get_real(b, key, 0.0f); + key[1] = 'y'; + out[1] = get_real(b, key, 0.0f); + key[1] = 'z'; + out[2] = get_real(b, key, 0.0f); +} + +static void set_int(const WtoNavBlock *b, const char *name, int32_t value) +{ + b->set_int(b->blk, name, value); +} + +static int32_t to_cm(float metres) +{ + const float cm = metres * 100.0f; + if (cm > 2.0e9f) + return INT32_MAX; + if (cm < -2.0e9f) + return INT32_MIN; + return (int32_t)(cm >= 0.0f ? cm + 0.5f : cm - 0.5f); +} + +static void set_vec_cm(const WtoNavBlock *b, const char *x, const char *y, const char *z, const float v[3]) +{ + set_int(b, x, to_cm(v[0])); + set_int(b, y, to_cm(v[1])); + set_int(b, z, to_cm(v[2])); +} + +static void read_costs(const WtoNavBlock *b, const char *prefix, WtoNavCosts *costs) +{ + char key[48]; + int area; + for (area = 0; area < WTO_NAV_RT_AREA_COUNT; area++) { + costs->area[area] = 1.0f; + if (AREA_KEYS[area][0] == '\0') + continue; + snprintf(key, sizeof(key), "%s_%s", prefix, AREA_KEYS[area]); + costs->area[area] = get_real(b, key, 1.0f); + if (!(costs->area[area] > 0.0f)) + costs->area[area] = 1.0f; + } + snprintf(key, sizeof(key), "%s_chokepoint", prefix); + costs->chokepointMul = get_real(b, key, 1.0f); + if (!(costs->chokepointMul > 0.0f)) + costs->chokepointMul = 1.0f; +} + +void wto_nav_protocol_setup(const WtoNavBlock *b) +{ + WtoNavCosts costs; + WtoNavTuning tuning; + read_costs(b, "t", &costs); + wto_nav_set_costs(0, &costs); + read_costs(b, "w", &costs); + wto_nav_set_costs(1, &costs); + tuning.trafficCostPerPath = get_real(b, "trafficPerPath", 0.0f); + tuning.trafficCostMaxMul = get_real(b, "trafficMaxMul", 1.0f); + tuning.trafficHoldSec = get_real(b, "trafficHoldSec", 0.0f); + tuning.cornerOffsetM = get_real(b, "cornerOffset", 0.0f); + wto_nav_set_tuning(&tuning); +} + +static void path_request(const WtoNavBlock *b) +{ + WtoNavPathRequest req; + const long slot = get_long(b, "slot", -1), tier = get_long(b, "tier", -1), filter = get_long(b, "filter", 0); + const long group = get_long(b, "group", 0); + uint32_t ticket = 0; + + memset(&req, 0, sizeof(req)); + req.tier = (uint32_t)tier; + req.filter = (uint32_t)filter; + req.group = group > 0 ? (uint32_t)group : 0u; + req.snapM = get_real(b, "snap", 0.0f); + req.goalSnapM = get_real(b, "goalSnap", 0.0f); + get_vec(b, 's', req.start); + get_vec(b, 'g', req.goal); + if (slot >= 0 && tier >= 0 && filter >= 0) + ticket = wto_nav_path_request((uint32_t)slot, &req); + set_int(b, "ticket", (int32_t)ticket); +} + +static void path_result(const WtoNavBlock *b) +{ + static const char *const STATUS[] = { "full", "partial", "no_start", "no_goal", "failed", "pending", "stale" }; + float points[WTO_NAV_RT_MAX_CORNERS * 3]; + const long slot = get_long(b, "slot", -1), ticket = get_long(b, "ticket", 0); + WtoNavPathResult result; + int i; + + wto_nav_path_result(slot < 0 ? UINT32_MAX : (uint32_t)slot, ticket <= 0 ? 0u : (uint32_t)ticket, + points, WTO_NAV_RT_MAX_CORNERS, &result); + b->set_str(b->blk, "status", STATUS[result.status]); + set_int(b, "count", result.count); + set_int(b, "lenCm", to_cm(result.lengthM)); + set_int(b, "truncated", result.truncated); + set_int(b, "goalMoved", result.goalMoved); + for (i = 0; i < result.count; i++) { + char kx[16], ky[16], kz[16]; + snprintf(kx, sizeof(kx), "p%dx", i); + snprintf(ky, sizeof(ky), "p%dy", i); + snprintf(kz, sizeof(kz), "p%dz", i); + set_vec_cm(b, kx, ky, kz, points + i * 3); + } +} + +static void probe(const WtoNavBlock *b) +{ + WtoNavProbe info; + float pos[3]; + get_vec(b, 'p', pos); + if (!wto_nav_probe((uint32_t)get_long(b, "tier", 0), (uint32_t)get_long(b, "filter", 0), pos, + get_real(b, "snap", 0.0f), get_real(b, "wallR", 0.0f), &info)) + info.onMesh = -1; + set_int(b, "onMesh", info.onMesh); + if (info.onMesh != 1) + return; + set_int(b, "offCm", to_cm(info.offsetM)); + set_int(b, "wallCm", to_cm(info.wallDistM)); + set_int(b, "area", (int32_t)info.area); + set_int(b, "flags", (int32_t)info.flags); + set_vec_cm(b, "nx", "ny", "nz", info.nearest); +} + +static void raycast(const WtoNavBlock *b) +{ + float start[3], goal[3], hit[3], frac = 0.0f; + int clear; + get_vec(b, 's', start); + get_vec(b, 'g', goal); + clear = wto_nav_raycast((uint32_t)get_long(b, "tier", 0), (uint32_t)get_long(b, "filter", 0), + get_real(b, "snap", 0.0f), start, goal, &frac, hit); + set_int(b, "clear", clear); + set_int(b, "hitPm", (int32_t)(frac * 1000.0f + 0.5f)); + set_vec_cm(b, "hx", "hy", "hz", hit); +} + +static void nearest(const WtoNavBlock *b) +{ + float pos[3], out[3] = { 0.0f, 0.0f, 0.0f }; + int found; + get_vec(b, 'p', pos); + found = wto_nav_nearest((uint32_t)get_long(b, "tier", 0), (uint32_t)get_long(b, "filter", 0), + get_real(b, "radius", 0.0f), pos, out); + set_int(b, "found", found); + set_vec_cm(b, "x", "y", "z", out); +} + +static void add_dynamic(const WtoNavBlock *b) +{ + float pos[3]; + get_vec(b, 'p', pos); + set_int(b, "count", (int32_t)wto_nav_add_dynamic(pos, get_real(b, "radius", 0.0f), get_real(b, "mul", 1.0f), + get_real(b, "until", 0.0f))); +} + +static void get_stats(const WtoNavBlock *b) +{ + WtoNavStats stats; + wto_nav_get_stats(&stats); + set_int(b, "loaded", stats.loaded); + set_int(b, "queries", (int32_t)stats.queries); + set_int(b, "failures", (int32_t)stats.failures); + set_int(b, "avgUs", stats.queries ? (int32_t)(stats.totalMicros / stats.queries) : 0); + set_int(b, "maxUs", (int32_t)stats.maxMicros); + set_int(b, "maxFrames", (int32_t)stats.maxFrames); + set_int(b, "pumpMaxUs", (int32_t)stats.pumpMaxMicros); + set_int(b, "pending", (int32_t)stats.pending); + set_int(b, "dynamic", (int32_t)stats.dynamic); + set_int(b, "meshQueries", (int32_t)stats.meshQueries); + set_int(b, "traffic", (int32_t)stats.trafficPaths); + set_int(b, "cornersMoved", (int32_t)stats.cornersMoved); +} + +static void pump(const WtoNavBlock *b) +{ + WtoNavStats stats; + wto_nav_pump((double)get_real(b, "budgetUs", 500.0f), get_real(b, "now", 0.0f)); + wto_nav_get_stats(&stats); + set_int(b, "pending", (int32_t)stats.pending); +} + +int wto_nav_protocol_query(const WtoNavBlock *b, const char *op) +{ + if (strcmp(op, "probe") == 0) + probe(b); + else if (strcmp(op, "path_result") == 0) + path_result(b); + else if (strcmp(op, "path_request") == 0) + path_request(b); + else if (strcmp(op, "raycast") == 0) + raycast(b); + else if (strcmp(op, "pump") == 0) + pump(b); + else if (strcmp(op, "nearest") == 0) + nearest(b); + else if (strcmp(op, "dynamic") == 0) + add_dynamic(b); + else if (strcmp(op, "get_stats") == 0) + get_stats(b); + else + return 0; + return 1; +} diff --git a/native/wto-nav/wto_nav_protocol.h b/native/wto-nav/wto_nav_protocol.h new file mode 100644 index 0000000..8835d67 --- /dev/null +++ b/native/wto-nav/wto_nav_protocol.h @@ -0,0 +1,49 @@ +/* + * The "wtoNav" request protocol of the ground AI script, shared by the game (wto-net + * local_mp_nav.c) and the AI simulator (native/wto-ai-sim): the script fills a block of string + * values with `op` and its arguments, the host answers by writing ints and strings back into it. + * Coordinates in replies are centimetres. The host keeps the ops that depend on where the battle's + * pack comes from (prefetch, load_map, unload_map); everything that only needs the loaded pack is + * answered here. + * + * op=pump now (script seconds), budgetUs -> pending + * op=path_request slot, tier, filter (0 tracked, 1 wheeled), group (team, 0 none), snap, + * goalSnap, sx..sz, gx..gz -> ticket + * op=path_result slot, ticket -> status=pending|full|partial|no_start|no_goal|failed|stale, + * count, lenCm, truncated, goalMoved, px/py/pz + * op=probe tier, filter, snap, wallR, px..pz -> onMesh, offCm, wallCm, area, flags, + * nx/ny/nz + * op=raycast tier, filter, snap, sx..sz, gx..gz -> clear=1|0|-1, hitPm, hx/hy/hz + * op=nearest tier, filter, radius, px..pz -> found, x/y/z + * op=dynamic px..pz, radius, mul, until (script seconds) -> count + * op=get_stats -> loaded, queries, failures, avgUs, maxUs, maxFrames, pumpMaxUs, pending, + * dynamic, meshQueries, traffic, cornersMoved + * + * load_map carries the per-class costs t_, w_ and the search tuning trafficPerPath, + * trafficMaxMul, trafficHoldSec, cornerOffset; wto_nav_protocol_setup applies them. + */ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Access to one request block. get_str returns "" for a value the block does not have. */ +typedef struct WtoNavBlock { + void *blk; + const char *(*get_str)(const void *blk, const char *name); + void (*set_str)(void *blk, const char *name, const char *value); + void (*set_int)(void *blk, const char *name, int32_t value); +} WtoNavBlock; + +/* Hands the costs and search tuning of a load_map request to the engine, before it loads. */ +void wto_nav_protocol_setup(const WtoNavBlock *b); + +/* Answers `op` when it is one of the queries above; returns 0 for any other op. */ +int wto_nav_protocol_query(const WtoNavBlock *b, const char *op); + +#ifdef __cplusplus +} +#endif diff --git a/native/wto-net/build.ps1 b/native/wto-net/build.ps1 index 2138e2d..7dbe352 100644 --- a/native/wto-net/build.ps1 +++ b/native/wto-net/build.ps1 @@ -32,7 +32,7 @@ $sources = Quote @( "$src\dll_main.c", "$src\hook_config.c", "$src\redirect_rules.c", "$src\resolver_hooks.c", "$src\connection_hooks.c", "$src\local_mp_core.c", "$src\local_mp_values.c", "$src\local_mp_players.c", "$src\local_mp_loadout.c", "$src\local_mp_actions.c", "$src\local_mp_awards.c", "$src\local_mp_kills.c", "$src\local_mp_events.c", "$src\local_mp_scores.c", "$src\local_mp_nuke.c", "$src\local_mp_support.c", "$src\local_mp_damage_notifications.c", "$src\local_mp_hit_feedback.c", "$src\local_mp_air_events.c", "$src\local_mp_ground_ai.c", "$src\local_mp_nav.c", "$src\local_mp_zones.c", "$src\local_mp_captures.c", "$src\local_mp_air_ai_sync.c", - "$nav\wto_nav_runtime.cpp", "$nav\wto_nav_paths.cpp", "$nav\wto_nav_queries.cpp", + "$nav\wto_nav_runtime.cpp", "$nav\wto_nav_paths.cpp", "$nav\wto_nav_queries.cpp", "$nav\wto_nav_protocol.c", "$mh\src\hook.c", "$mh\src\buffer.c", "$mh\src\trampoline.c", "$mh\src\hde\hde64.c" ) $detourSources = Quote (Get-ChildItem "$dt\Source\*.cpp").FullName diff --git a/native/wto-net/src/local_mp_nav.c b/native/wto-net/src/local_mp_nav.c index 0fb4c43..dfea6f0 100644 --- a/native/wto-net/src/local_mp_nav.c +++ b/native/wto-net/src/local_mp_nav.c @@ -1,30 +1,17 @@ /* * "wtoNav" requests of the ground AI script (call_mission_action, local_mp_ground_ai.c) and the - * battle's navigation pack (native/wto-nav). The script fills a DataBlock with the request, this - * module answers synchronously by writing into the same block: + * battle's navigation pack (native/wto-nav). The script fills a DataBlock with the request and this + * module answers synchronously into the same block. The queries are the shared protocol of + * native/wto-nav/wto_nav_protocol.h; this module adds the ops that depend on the battle: * * op=prefetch -> state=started|skipped, level, reason (battle still loading) - * op=load_map allowFallback="0|1", tracked/wheeled costs t_, w_, - * trafficPerPath, trafficMaxMul, trafficHoldSec, cornerOffset + * op=load_map allowFallback="0|1", plus the costs and tuning of the protocol * -> state=loaded|fallback|failed, fingerprint=match|mismatch|unknown, level, * reason, tiers, covers * op=unload_map -> ok - * op=pump now (script seconds), budgetUs -> pending - * op=path_request slot, tier, filter (0 tracked, 1 wheeled), group (team, 0 none), snap, - * goalSnap, sx..sz, gx..gz -> ticket - * op=path_result slot, ticket -> status=pending|full|partial|no_start|no_goal|failed|stale, - * count, lenCm, truncated, goalMoved, px/py/pz - * op=probe tier, filter, snap, wallR, px..pz -> onMesh, offCm, wallCm, area, flags, - * nx/ny/nz - * op=raycast tier, filter, snap, sx..sz, gx..gz -> clear=1|0|-1, hitPm, hx/hy/hz - * op=nearest tier, filter, radius, px..pz -> found, x/y/z - * op=dynamic px..pz, radius, mul, until (script seconds) -> count - * op=get_stats -> loaded, queries, failures, avgUs, maxUs, maxFrames, pumpMaxUs, pending, - * dynamic, meshQueries, traffic, cornersMoved * - * Coordinates in replies are centimetres (ints). Request values are strings: the script only uses - * the DataBlock string add it already relies on. Replies are ints and strings written with the - * setters local_mp_awards resolves. + * Request values are strings: the script only uses the DataBlock string add it already relies on. + * Replies are ints and strings written with the setters local_mp_awards resolves. * * The level comes from the mission settings (customBots wtoLevel, written by the local server), * the pack folder from wto_ws.cfg (nav.dir). The script asks for a prefetch while the battle @@ -36,6 +23,7 @@ #include "local_mp_internal.h" #include "local_mp_offsets.h" #include "local_mp_values.h" +#include "wto_nav_protocol.h" #include "wto_nav_runtime.h" #include @@ -64,11 +52,6 @@ typedef struct NavBattle { uint32_t covers; } NavBattle; -/* Costs in the order of WtoPolyArea; empty names are areas the mesh never carries. */ -static const char *const AREA_KEYS[WTO_NAV_RT_AREA_COUNT] = { - "", "road", "bridge", "ground", "rough", "forest", "crushable", "shallowWater", "", "exposed", "", "", -}; - static NavBattle g_battle; static SRWLOCK g_battle_lock = SRWLOCK_INIT; static LONG g_missing_values_logged; @@ -96,17 +79,6 @@ static void set_int(void *blk, const char *name, int32_t value) ((BlkSetIntFn)g_lmp.blk_set_int)(blk, name, &value); } -static float get_real(const void *blk, const char *name, float def) -{ - const char *text = g_lmp_datablock_get_str(blk, name, ""); - char *end; - float value; - if (text == NULL || text[0] == '\0') - return def; - value = strtof(text, &end); - return (*end == '\0' && value == value) ? value : def; -} - static long get_long(const void *blk, const char *name, long def) { const char *text = g_lmp_datablock_get_str(blk, name, ""); @@ -118,32 +90,20 @@ static long get_long(const void *blk, const char *name, long def) return *end == '\0' ? value : def; } -/* x, y, z */ -static void get_vec(const void *blk, char prefix, float out[3]) +static const char *block_get_str(const void *blk, const char *name) { - char key[3] = { prefix, 'x', '\0' }; - out[0] = get_real(blk, key, 0.0f); - key[1] = 'y'; - out[1] = get_real(blk, key, 0.0f); - key[1] = 'z'; - out[2] = get_real(blk, key, 0.0f); + const char *text = g_lmp_datablock_get_str(blk, name, ""); + return text ? text : ""; } -static int32_t to_cm(float metres) +static WtoNavBlock game_block(void *blk) { - const float cm = metres * 100.0f; - if (cm > 2.0e9f) - return INT32_MAX; - if (cm < -2.0e9f) - return INT32_MIN; - return (int32_t)(cm >= 0.0f ? cm + 0.5f : cm - 0.5f); -} - -static void set_vec_cm(void *blk, const char *x, const char *y, const char *z, const float v[3]) -{ - set_int(blk, x, to_cm(v[0])); - set_int(blk, y, to_cm(v[1])); - set_int(blk, z, to_cm(v[2])); + WtoNavBlock b; + b.blk = blk; + b.get_str = block_get_str; + b.set_str = set_str; + b.set_int = set_int; + return b; } static void hex20(const uint8_t *sha1, char out[41]) @@ -227,35 +187,6 @@ static int battle_paths(char level[NAV_LEVEL_MAX], wchar_t pack[MAX_PATH], wchar return 1; } -static void read_costs(const void *blk, const char *prefix, WtoNavCosts *costs) -{ - char key[48]; - int area; - for (area = 0; area < WTO_NAV_RT_AREA_COUNT; area++) { - costs->area[area] = 1.0f; - if (AREA_KEYS[area][0] == '\0') - continue; - snprintf(key, sizeof(key), "%s_%s", prefix, AREA_KEYS[area]); - costs->area[area] = get_real(blk, key, 1.0f); - if (!(costs->area[area] > 0.0f)) - costs->area[area] = 1.0f; - } - snprintf(key, sizeof(key), "%s_chokepoint", prefix); - costs->chokepointMul = get_real(blk, key, 1.0f); - if (!(costs->chokepointMul > 0.0f)) - costs->chokepointMul = 1.0f; -} - -static void read_tuning(const void *blk) -{ - WtoNavTuning tuning; - tuning.trafficCostPerPath = get_real(blk, "trafficPerPath", 0.0f); - tuning.trafficCostMaxMul = get_real(blk, "trafficMaxMul", 1.0f); - tuning.trafficHoldSec = get_real(blk, "trafficHoldSec", 0.0f); - tuning.cornerOffsetM = get_real(blk, "cornerOffset", 0.0f); - wto_nav_set_tuning(&tuning); -} - static void log_loaded(const WtoNavLoadInfo *info) { char expected[41], actual[41]; @@ -272,16 +203,12 @@ static void decide_locked(const void *blk, int allow_fallback) { wchar_t pack[MAX_PATH], level_path[MAX_PATH]; WtoNavLoadInfo info; - WtoNavCosts costs; + WtoNavBlock request = game_block((void *)blk); memset(&info, 0, sizeof(info)); info.result = WTO_NAV_LOAD_MISSING; if (battle_paths(g_battle.level, pack, level_path, g_battle.reason, sizeof(g_battle.reason))) { - read_costs(blk, "t", &costs); - wto_nav_set_costs(0, &costs); - read_costs(blk, "w", &costs); - wto_nav_set_costs(1, &costs); - read_tuning(blk); + wto_nav_protocol_setup(&request); wto_nav_load(pack, level_path[0] ? level_path : NULL, &info); if (info.result != WTO_NAV_LOAD_OK) snprintf(g_battle.reason, sizeof(g_battle.reason), "%s", info.detail); @@ -358,129 +285,9 @@ static void unload_locked(const char *why) memset(&g_battle, 0, sizeof(g_battle)); } -static void path_request(void *blk) -{ - WtoNavPathRequest req; - const long slot = get_long(blk, "slot", -1), tier = get_long(blk, "tier", -1), filter = get_long(blk, "filter", 0); - const long group = get_long(blk, "group", 0); - uint32_t ticket = 0; - - memset(&req, 0, sizeof(req)); - req.tier = (uint32_t)tier; - req.filter = (uint32_t)filter; - req.group = group > 0 ? (uint32_t)group : 0u; - req.snapM = get_real(blk, "snap", 0.0f); - req.goalSnapM = get_real(blk, "goalSnap", 0.0f); - get_vec(blk, 's', req.start); - get_vec(blk, 'g', req.goal); - if (slot >= 0 && tier >= 0 && filter >= 0) - ticket = wto_nav_path_request((uint32_t)slot, &req); - set_int(blk, "ticket", (int32_t)ticket); -} - -static void path_result(void *blk) -{ - static const char *const STATUS[] = { "full", "partial", "no_start", "no_goal", "failed", "pending", "stale" }; - float points[WTO_NAV_RT_MAX_CORNERS * 3]; - const long slot = get_long(blk, "slot", -1), ticket = get_long(blk, "ticket", 0); - WtoNavPathResult result; - char key[16]; - int i; - - wto_nav_path_result(slot < 0 ? UINT32_MAX : (uint32_t)slot, ticket <= 0 ? 0u : (uint32_t)ticket, - points, WTO_NAV_RT_MAX_CORNERS, &result); - set_str(blk, "status", STATUS[result.status]); - set_int(blk, "count", result.count); - set_int(blk, "lenCm", to_cm(result.lengthM)); - set_int(blk, "truncated", result.truncated); - set_int(blk, "goalMoved", result.goalMoved); - for (i = 0; i < result.count; i++) { - char ky[16], kz[16]; - snprintf(key, sizeof(key), "p%dx", i); - snprintf(ky, sizeof(ky), "p%dy", i); - snprintf(kz, sizeof(kz), "p%dz", i); - set_vec_cm(blk, key, ky, kz, points + i * 3); - } -} - -static void probe(void *blk) -{ - WtoNavProbe info; - float pos[3]; - get_vec(blk, 'p', pos); - if (!wto_nav_probe((uint32_t)get_long(blk, "tier", 0), (uint32_t)get_long(blk, "filter", 0), pos, - get_real(blk, "snap", 0.0f), get_real(blk, "wallR", 0.0f), &info)) - info.onMesh = -1; - set_int(blk, "onMesh", info.onMesh); - if (info.onMesh != 1) - return; - set_int(blk, "offCm", to_cm(info.offsetM)); - set_int(blk, "wallCm", to_cm(info.wallDistM)); - set_int(blk, "area", (int32_t)info.area); - set_int(blk, "flags", (int32_t)info.flags); - set_vec_cm(blk, "nx", "ny", "nz", info.nearest); -} - -static void raycast(void *blk) -{ - float start[3], goal[3], hit[3], frac = 0.0f; - int clear; - get_vec(blk, 's', start); - get_vec(blk, 'g', goal); - clear = wto_nav_raycast((uint32_t)get_long(blk, "tier", 0), (uint32_t)get_long(blk, "filter", 0), - get_real(blk, "snap", 0.0f), start, goal, &frac, hit); - set_int(blk, "clear", clear); - set_int(blk, "hitPm", (int32_t)(frac * 1000.0f + 0.5f)); - set_vec_cm(blk, "hx", "hy", "hz", hit); -} - -static void nearest(void *blk) -{ - float pos[3], out[3] = { 0.0f, 0.0f, 0.0f }; - int found; - get_vec(blk, 'p', pos); - found = wto_nav_nearest((uint32_t)get_long(blk, "tier", 0), (uint32_t)get_long(blk, "filter", 0), - get_real(blk, "radius", 0.0f), pos, out); - set_int(blk, "found", found); - set_vec_cm(blk, "x", "y", "z", out); -} - -static void add_dynamic(void *blk) -{ - float pos[3]; - get_vec(blk, 'p', pos); - set_int(blk, "count", (int32_t)wto_nav_add_dynamic(pos, get_real(blk, "radius", 0.0f), get_real(blk, "mul", 1.0f), - get_real(blk, "until", 0.0f))); -} - -static void get_stats(void *blk) -{ - WtoNavStats stats; - wto_nav_get_stats(&stats); - set_int(blk, "loaded", stats.loaded); - set_int(blk, "queries", (int32_t)stats.queries); - set_int(blk, "failures", (int32_t)stats.failures); - set_int(blk, "avgUs", stats.queries ? (int32_t)(stats.totalMicros / stats.queries) : 0); - set_int(blk, "maxUs", (int32_t)stats.maxMicros); - set_int(blk, "maxFrames", (int32_t)stats.maxFrames); - set_int(blk, "pumpMaxUs", (int32_t)stats.pumpMaxMicros); - set_int(blk, "pending", (int32_t)stats.pending); - set_int(blk, "dynamic", (int32_t)stats.dynamic); - set_int(blk, "meshQueries", (int32_t)stats.meshQueries); - set_int(blk, "traffic", (int32_t)stats.trafficPaths); - set_int(blk, "cornersMoved", (int32_t)stats.cornersMoved); -} - -static void pump(void *blk) -{ - WtoNavStats stats; - wto_nav_pump((double)get_real(blk, "budgetUs", 500.0f), get_real(blk, "now", 0.0f)); - wto_nav_get_stats(&stats); - set_int(blk, "pending", (int32_t)stats.pending); -} - void local_mp_nav_request(void *blk) { + WtoNavBlock request; const char *op; if (blk == NULL || !values_ready()) @@ -488,21 +295,10 @@ void local_mp_nav_request(void *blk) op = g_lmp_datablock_get_str(blk, "op", ""); if (op == NULL) return; - if (strcmp(op, "probe") == 0) { - probe(blk); - } else if (strcmp(op, "path_result") == 0) { - path_result(blk); - } else if (strcmp(op, "path_request") == 0) { - path_request(blk); - } else if (strcmp(op, "raycast") == 0) { - raycast(blk); - } else if (strcmp(op, "pump") == 0) { - pump(blk); - } else if (strcmp(op, "nearest") == 0) { - nearest(blk); - } else if (strcmp(op, "dynamic") == 0) { - add_dynamic(blk); - } else if (strcmp(op, "prefetch") == 0) { + request = game_block(blk); + if (wto_nav_protocol_query(&request, op)) + return; + if (strcmp(op, "prefetch") == 0) { prefetch(blk); } else if (strcmp(op, "load_map") == 0) { load_map(blk); @@ -511,8 +307,6 @@ void local_mp_nav_request(void *blk) unload_locked("battle ended"); ReleaseSRWLockExclusive(&g_battle_lock); set_int(blk, "ok", 1); - } else if (strcmp(op, "get_stats") == 0) { - get_stats(blk); } else { log_line("WTO_NAV|BAD_REQUEST|op=%s", op); } diff --git a/packages/ground-sim/src/index.ts b/packages/ground-sim/src/index.ts index c769fef..55c35c7 100644 --- a/packages/ground-sim/src/index.ts +++ b/packages/ground-sim/src/index.ts @@ -6,6 +6,11 @@ export { NAV_AREA_NAMES, NAV_FLAG, NAV_TIER_NAMES, NavPackError, readNavPack, type NavCover, type NavHeader, type NavPack, type NavTactical, type NavTier, } from './map/wtonav.ts'; +export { GEO_CLASS_NAMES, GeoError, geoHeightAt, readGeo, type GeoData } from './map/wtogeo.ts'; +export { + SCENE_BUILD_DEFAULTS, SCENE_KIND_NAMES, buildMapScene, decodeMapScene, encodeMapScene, sceneHeightAt, + type MapScene, type SceneBuildOptions, type SceneMesh, type SceneTerrain, +} from './map/scene.ts'; export { parsePois, type MapPoint, type MapPois } from './map/pois.ts'; export { BEHAVIOR_NAMES, BLOCK_NAMES, COMMAND_NAMES, DENY_NAMES, LANE_NAMES, LOOK_NAMES, STATE_NAMES, diff --git a/packages/ground-sim/src/map/scene.ts b/packages/ground-sim/src/map/scene.ts new file mode 100644 index 0000000..d3ae6bb --- /dev/null +++ b/packages/ground-sim/src/map/scene.ts @@ -0,0 +1,214 @@ +/** + * The 3D map of the AI lab: the level's terrain and the collision shapes of its placed objects, + * made from the `.wtogeo` geometry that the simulator's line of sight also uses. Building it + * thins the heightmap to a display size, drops object faces buried under the terrain, cuts the + * objects into square tiles by kind and welds shared vertices, so the browser can draw them in a + * few large meshes. `.wtoscene` is that result as one binary file. + */ +import { geoHeightAt, type GeoData } from './wtogeo.ts'; + +/** How the viewer colours the objects; several obstacle classes share a kind. */ +export const SCENE_KIND_NAMES = ['solid', 'noCover', 'bridge', 'crushable', 'tree', 'platform'] as const; + +/** Obstacle class (GEO_CLASS_NAMES) to scene kind. */ +const KIND_OF_CLASS = [0, 2, 3, 4, 4, 1, 5, 5] as const; + +export interface SceneTerrain { + readonly cols: number; + readonly rows: number; + readonly cellM: number; + readonly origin: readonly [number, number]; + /** `heights[row * cols + col]` at origin + (col, row) * cellM. */ + readonly heights: Float32Array; +} + +export interface SceneMesh { + /** SCENE_KIND_NAMES index. */ + readonly kind: number; + /** x, y, z triples in world metres. */ + readonly positions: Float32Array; + readonly indices: Uint32Array; +} + +export interface MapScene { + readonly boundsMin: readonly [number, number]; + readonly boundsMax: readonly [number, number]; + readonly waterLevel: number | undefined; + readonly terrain: SceneTerrain; + readonly meshes: SceneMesh[]; +} + +export interface SceneBuildOptions { + /** Most terrain samples kept; the heightmap is thinned by a whole stride to fit. */ + readonly maxTerrainSamples: number; + readonly tileM: number; + /** Vertices closer than this are welded into one. */ + readonly weldM: number; + /** A face whose corners all lie this far under the terrain is dropped. */ + readonly buriedM: number; +} + +export const SCENE_BUILD_DEFAULTS: SceneBuildOptions = { maxTerrainSamples: 1_200_000, tileM: 256, weldM: 0.05, buriedM: 0.3 }; + +function thinTerrain(geo: GeoData, maxSamples: number): SceneTerrain { + const stride = Math.max(1, Math.ceil(Math.sqrt((geo.hmCols * geo.hmRows) / maxSamples))); + const cols = Math.floor((geo.hmCols - 1) / stride) + 1; + const rows = Math.floor((geo.hmRows - 1) / stride) + 1; + const heights = new Float32Array(cols * rows); + for (let r = 0; r < rows; r++) { + for (let c = 0; c < cols; c++) heights[r * cols + c] = geo.heights[r * stride * geo.hmCols + c * stride] ?? 0; + } + return { cols, rows, cellM: geo.hmCellM * stride, origin: geo.hmOrigin, heights }; +} + +function buried(geo: GeoData, v: Float32Array, i: number, depth: number): boolean { + const x = v[i * 3] ?? 0; + const z = v[i * 3 + 2] ?? 0; + return (v[i * 3 + 1] ?? 0) < geoHeightAt(geo, x, z) - depth; +} + +/** Triangle ids per tile and kind, after dropping buried faces. */ +function bucketTriangles(geo: GeoData, opts: SceneBuildOptions): Map { + const { verts, tris, triClass } = geo; + const tilesX = Math.ceil((geo.boundsMax[0] - geo.boundsMin[0]) / opts.tileM) + 1; + const buckets = new Map(); + for (let t = 0; t < triClass.length; t++) { + const a = tris[t * 3] ?? 0; + const b = tris[t * 3 + 1] ?? 0; + const c = tris[t * 3 + 2] ?? 0; + if (buried(geo, verts, a, opts.buriedM) && buried(geo, verts, b, opts.buriedM) && buried(geo, verts, c, opts.buriedM)) continue; + const cx = ((verts[a * 3] ?? 0) + (verts[b * 3] ?? 0) + (verts[c * 3] ?? 0)) / 3; + const cz = ((verts[a * 3 + 2] ?? 0) + (verts[b * 3 + 2] ?? 0) + (verts[c * 3 + 2] ?? 0)) / 3; + const tx = Math.max(0, Math.floor((cx - geo.boundsMin[0]) / opts.tileM)); + const tz = Math.max(0, Math.floor((cz - geo.boundsMin[1]) / opts.tileM)); + const kind = KIND_OF_CLASS[triClass[t] ?? 0] ?? 0; + const key = (tz * tilesX + tx) * SCENE_KIND_NAMES.length + kind; + let list = buckets.get(key); + if (list === undefined) { list = []; buckets.set(key, list); } + list.push(t); + } + return buckets; +} + +/** One tile's triangles as an indexed mesh with welded, snapped vertices; degenerate faces dropped. */ +function weldTile(geo: GeoData, kind: number, triIds: readonly number[], weldM: number): SceneMesh | undefined { + const [bx, bz] = geo.boundsMin; + const slot = new Map(); + const pos: number[] = []; + const idx: number[] = []; + const corner = [0, 0, 0]; + for (const t of triIds) { + for (let k = 0; k < 3; k++) { + const v = geo.tris[t * 3 + k] ?? 0; + const qx = Math.round(((geo.verts[v * 3] ?? 0) - bx) / weldM); + const qy = Math.round(((geo.verts[v * 3 + 1] ?? 0) + 1000) / weldM); + const qz = Math.round(((geo.verts[v * 3 + 2] ?? 0) - bz) / weldM); + const key = (qx * 65536 + qy) * 131072 + qz; + let at = slot.get(key); + if (at === undefined) { + at = pos.length / 3; + slot.set(key, at); + pos.push(bx + qx * weldM, qy * weldM - 1000, bz + qz * weldM); + } + corner[k] = at; + } + const [a, b, c] = corner as [number, number, number]; + if (a !== b && b !== c && a !== c) idx.push(a, b, c); + } + if (idx.length === 0) return undefined; + return { kind, positions: Float32Array.from(pos), indices: Uint32Array.from(idx) }; +} + +export function buildMapScene(geo: GeoData, opts: SceneBuildOptions = SCENE_BUILD_DEFAULTS): MapScene { + const meshes: SceneMesh[] = []; + for (const [key, triIds] of bucketTriangles(geo, opts)) { + const mesh = weldTile(geo, key % SCENE_KIND_NAMES.length, triIds, opts.weldM); + if (mesh !== undefined) meshes.push(mesh); + } + return { + boundsMin: geo.boundsMin, + boundsMax: geo.boundsMax, + waterLevel: geo.waterLevel, + terrain: thinTerrain(geo, opts.maxTerrainSamples), + meshes, + }; +} + +/** Bilinear height of the scene's terrain at world (x, z), clamped to its grid. */ +export function sceneHeightAt(t: SceneTerrain, x: number, z: number): number { + const fx = Math.min(t.cols - 1.001, Math.max(0, (x - t.origin[0]) / t.cellM)); + const fz = Math.min(t.rows - 1.001, Math.max(0, (z - t.origin[1]) / t.cellM)); + const x0 = Math.floor(fx); + const z0 = Math.floor(fz); + const i = z0 * t.cols + x0; + const h = t.heights; + const a = (h[i] ?? 0) + ((h[i + 1] ?? 0) - (h[i] ?? 0)) * (fx - x0); + const b = (h[i + t.cols] ?? 0) + ((h[i + t.cols + 1] ?? 0) - (h[i + t.cols] ?? 0)) * (fx - x0); + return a + (b - a) * (fz - z0); +} + +const SCENE_MAGIC = 'WTOSCN\0\x01'; +const SCENE_VERSION = 1; +const SCENE_HEADER_BYTES = 56; + +/** + * `.wtoscene`: magic, version, bounds, water level (-1e6 when none), terrain grid, mesh count; + * the terrain heights; then per mesh its kind, vertex and index counts, positions and indices. + * Little-endian, every block 4-byte aligned. + */ +export function encodeMapScene(s: MapScene): Uint8Array { + let size = SCENE_HEADER_BYTES + s.terrain.heights.byteLength; + for (const m of s.meshes) size += 12 + m.positions.byteLength + m.indices.byteLength; + const out = new Uint8Array(size); + const dv = new DataView(out.buffer); + for (let i = 0; i < 8; i++) out[i] = SCENE_MAGIC.charCodeAt(i); + const head = [SCENE_VERSION, s.meshes.length, s.terrain.cols, s.terrain.rows]; + head.forEach((v, i) => dv.setUint32(8 + i * 4, v, true)); + const floats = [s.boundsMin[0], s.boundsMin[1], s.boundsMax[0], s.boundsMax[1], s.waterLevel ?? -1e6, + s.terrain.cellM, s.terrain.origin[0], s.terrain.origin[1]]; + floats.forEach((v, i) => dv.setFloat32(24 + i * 4, v, true)); + let at = SCENE_HEADER_BYTES; + const put = (a: Float32Array | Uint32Array): void => { out.set(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), at); at += a.byteLength; }; + put(s.terrain.heights); + for (const m of s.meshes) { + dv.setUint32(at, m.kind, true); + dv.setUint32(at + 4, m.positions.length / 3, true); + dv.setUint32(at + 8, m.indices.length, true); + at += 12; + put(m.positions); + put(m.indices); + } + return out; +} + +export function decodeMapScene(bytes: Uint8Array): MapScene { + if (String.fromCharCode(...bytes.subarray(0, 8)) !== SCENE_MAGIC) throw new Error('not a .wtoscene file'); + const own = bytes.byteOffset % 4 === 0 ? bytes : bytes.slice(); + const dv = new DataView(own.buffer, own.byteOffset, own.byteLength); + if (dv.getUint32(8, true) !== SCENE_VERSION) throw new Error('unsupported .wtoscene version'); + const meshCount = dv.getUint32(12, true); + const cols = dv.getUint32(16, true); + const rows = dv.getUint32(20, true); + const f = (i: number): number => dv.getFloat32(24 + i * 4, true); + let at = own.byteOffset + SCENE_HEADER_BYTES; + const floats = (n: number): Float32Array => { const a = new Float32Array(own.buffer, at, n); at += n * 4; return a; }; + const uints = (n: number): Uint32Array => { const a = new Uint32Array(own.buffer, at, n); at += n * 4; return a; }; + const heights = floats(cols * rows); + const meshes: SceneMesh[] = []; + for (let i = 0; i < meshCount; i++) { + const base = at - own.byteOffset; + const kind = dv.getUint32(base, true); + const verts = dv.getUint32(base + 4, true); + const count = dv.getUint32(base + 8, true); + at += 12; + meshes.push({ kind, positions: floats(verts * 3), indices: uints(count) }); + } + const water = f(4); + return { + boundsMin: [f(0), f(1)], + boundsMax: [f(2), f(3)], + waterLevel: water > -1e5 ? water : undefined, + terrain: { cols, rows, cellM: f(5), origin: [f(6), f(7)], heights }, + meshes, + }; +} diff --git a/packages/ground-sim/src/map/wtogeo.ts b/packages/ground-sim/src/map/wtogeo.ts new file mode 100644 index 0000000..4318473 --- /dev/null +++ b/packages/ground-sim/src/map/wtogeo.ts @@ -0,0 +1,99 @@ +/** + * Reader for the `.wtogeo` intermediate geometry (native/wto-nav/wto_nav_format.h) that the + * navigation extractor writes from the game's level: the cropped terrain heightmap and every + * collision triangle of placed objects, each with its obstacle class. Trailers (road mask, + * downhill links) are not read. Only plain views over the bytes, so it runs in Node and in the + * browser. + */ + +const MAGIC = 'WTOGEO\0\x01'; +const HEADER_BYTES = 84; +const TRI_BYTES = 13; + +/** WtoObstacleClass. */ +export const GEO_CLASS_NAMES = [ + 'hardSolid', 'bridgeDeck', 'crushable', 'treeThick', 'treeThin', 'hardNoCover', 'platform', 'platformNoCover', +] as const; + +export interface GeoData { + readonly version: number; + readonly waterLevel: number | undefined; + /** World x, z of the crop (battle area union plus margin). */ + readonly boundsMin: readonly [number, number]; + readonly boundsMax: readonly [number, number]; + /** Heightmap: `heights[row * cols + col]` is the height at origin + (col, row) * cellM. */ + readonly hmCols: number; + readonly hmRows: number; + readonly hmCellM: number; + readonly hmOrigin: readonly [number, number]; + readonly heights: Float32Array; + /** Obstacle vertices as x, y, z triples in world metres. */ + readonly verts: Float32Array; + /** Three vertex indices per triangle, and its class (GEO_CLASS_NAMES). */ + readonly tris: Uint32Array; + readonly triClass: Uint8Array; +} + +export class GeoError extends Error {} + +function floatsAt(bytes: Uint8Array, offset: number, count: number): Float32Array { + const at = bytes.byteOffset + offset; + if (at % 4 === 0) return new Float32Array(bytes.buffer, at, count); + return new Float32Array(bytes.slice(offset, offset + count * 4).buffer); +} + +export function readGeo(bytes: Uint8Array): GeoData { + if (bytes.byteLength < HEADER_BYTES) throw new GeoError('file shorter than its header'); + const magic = String.fromCharCode(...bytes.subarray(0, 8)); + if (magic !== MAGIC) throw new GeoError('not a .wtogeo file'); + const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const u32 = (o: number): number => dv.getUint32(o, true); + const f32 = (o: number): number => dv.getFloat32(o, true); + const hmCols = u32(56); + const hmRows = u32(60); + const vertCount = u32(76); + const triCount = u32(80); + const hOff = HEADER_BYTES; + const vOff = hOff + hmCols * hmRows * 4; + const tOff = vOff + vertCount * 12; + if (tOff + triCount * TRI_BYTES > bytes.byteLength) throw new GeoError('file is truncated'); + const tris = new Uint32Array(triCount * 3); + const triClass = new Uint8Array(triCount); + for (let i = 0; i < triCount; i++) { + const o = tOff + i * TRI_BYTES; + tris[i * 3] = u32(o); + tris[i * 3 + 1] = u32(o + 4); + tris[i * 3 + 2] = u32(o + 8); + triClass[i] = bytes[o + 12] ?? 0; + } + const water = f32(36); + return { + version: u32(8), + waterLevel: water > -1e5 ? water : undefined, + boundsMin: [f32(40), f32(44)], + boundsMax: [f32(48), f32(52)], + hmCols, + hmRows, + hmCellM: f32(64), + hmOrigin: [f32(68), f32(72)], + heights: floatsAt(bytes, hOff, hmCols * hmRows), + verts: floatsAt(bytes, vOff, vertCount * 3), + tris, + triClass, + }; +} + +/** Bilinear terrain height at world (x, z), clamped to the heightmap. */ +export function geoHeightAt(geo: GeoData, x: number, z: number): number { + const fx = Math.min(geo.hmCols - 1.001, Math.max(0, (x - geo.hmOrigin[0]) / geo.hmCellM)); + const fz = Math.min(geo.hmRows - 1.001, Math.max(0, (z - geo.hmOrigin[1]) / geo.hmCellM)); + const x0 = Math.floor(fx); + const z0 = Math.floor(fz); + const tx = fx - x0; + const tz = fz - z0; + const h = geo.heights; + const i = z0 * geo.hmCols + x0; + const a = (h[i] ?? 0) + ((h[i + 1] ?? 0) - (h[i] ?? 0)) * tx; + const b = (h[i + geo.hmCols] ?? 0) + ((h[i + geo.hmCols + 1] ?? 0) - (h[i + geo.hmCols] ?? 0)) * tx; + return a + (b - a) * tz; +} diff --git a/packages/ground-sim/src/trace/parse.ts b/packages/ground-sim/src/trace/parse.ts index 899c89e..42ef36a 100644 --- a/packages/ground-sim/src/trace/parse.ts +++ b/packages/ground-sim/src/trace/parse.ts @@ -37,6 +37,14 @@ function num(f: Fields, key: string): number { return Number.isFinite(v) ? v : 0; } +/** A number that older traces lack, or that the game marks unknown with 9999. */ +function optNum(f: Fields, key: string): number | undefined { + const raw = f[key]; + if (raw === undefined) return undefined; + const v = Number(raw); + return Number.isFinite(v) && v !== 9999 ? v : undefined; +} + function flag(f: Fields, key: string): boolean { return f[key] === '1'; } @@ -53,6 +61,7 @@ function readUnit(f: Fields): UnitSample { return { eid: id(f, 'eid'), army: num(f, 'army'), bot: flag(f, 'bot'), human: flag(f, 'human'), alive: flag(f, 'alive'), x: num(f, 'x'), y: num(f, 'y'), z: num(f, 'z'), yaw: num(f, 'yaw'), speed: num(f, 'v'), + hullPitch: optNum(f, 'hp'), hullRoll: optNum(f, 'hr'), gunYaw: optNum(f, 'gy'), gunPitch: optNum(f, 'gp'), shooting: flag(f, 'shoot'), light: flag(f, 'light'), }; } diff --git a/packages/ground-sim/src/trace/types.ts b/packages/ground-sim/src/trace/types.ts index f859b04..809f077 100644 --- a/packages/ground-sim/src/trace/types.ts +++ b/packages/ground-sim/src/trace/types.ts @@ -23,6 +23,12 @@ export interface UnitSample { readonly y: number; readonly z: number; readonly yaw: number; + /** Hull pitch, nose up positive, and roll, left side up positive; undefined in older traces. */ + readonly hullPitch: number | undefined; + readonly hullRoll: number | undefined; + /** Main gun world yaw and pitch; undefined when the gun was not read. */ + readonly gunYaw: number | undefined; + readonly gunPitch: number | undefined; readonly speed: number; readonly shooting: boolean; readonly light: boolean;