diff --git a/src/game/server/nav.h b/src/game/server/nav.h index 35899935e4..bb09068c59 100644 --- a/src/game/server/nav.h +++ b/src/game/server/nav.h @@ -24,7 +24,7 @@ */ #ifdef NEO -const float GenerationStepSize = 20.0f; // NEO: some hallways/openings were missing connections with larger value +constexpr float GenerationStepSize = 20.0f; // NEO: some hallways/openings were missing connections with larger value #else const float GenerationStepSize = 25.0f; // (30) was 20, but bots can't fit always fit #endif diff --git a/src/game/server/nav_area.cpp b/src/game/server/nav_area.cpp index 035662fa18..f85e6825fe 100644 --- a/src/game/server/nav_area.cpp +++ b/src/game/server/nav_area.cpp @@ -984,6 +984,10 @@ void CNavArea::FinishMerge( CNavArea *adjArea ) { m_invDxCorners = m_invDyCorners = 0; } +#ifdef NEO + + TheNavMesh->AddNavAreaToGrid( this ); +#endif // NEO // reassign the adjacent area's internal nodes to the final area adjArea->AssignNodes( this ); @@ -1830,6 +1834,10 @@ bool CNavArea::MergeEdit( CNavArea *adj ) MergeAdjacentConnections( adj ); InheritAttributes( adj ); +#ifdef NEO + + TheNavMesh->AddNavAreaToGrid( this ); +#endif // NEO // remove subsumed adjacent area TheNavAreas.FindAndRemove( adj ); diff --git a/src/game/server/nav_edit.cpp b/src/game/server/nav_edit.cpp index c9997552b0..1bc77c2af2 100644 --- a/src/game/server/nav_edit.cpp +++ b/src/game/server/nav_edit.cpp @@ -555,7 +555,11 @@ void StepAlongClimbableSurface( Vector &pos, const Vector &increment, const Vect //-------------------------------------------------------------------------------------------------------------- +#ifdef NEO +void CNavMesh::CommandNavBuildLadder( NavLadderSourceType source ) +#else void CNavMesh::CommandNavBuildLadder( void ) +#endif { if ( !IsEditMode( NORMAL ) || !m_climbableSurface ) { @@ -590,7 +594,11 @@ void CNavMesh::CommandNavBuildLadder( void ) Vector bottom = top; bottom.z = bottomEdge.z; +#ifdef NEO + CreateLadder( topEdge, bottomEdge, leftEdge.DistTo( rightEdge ), m_ladderNormal.AsVector2D(), 0.0f, source ); +#else CreateLadder( topEdge, bottomEdge, leftEdge.DistTo( rightEdge ), m_ladderNormal.AsVector2D(), 0.0f ); +#endif } diff --git a/src/game/server/nav_generate.cpp b/src/game/server/nav_generate.cpp index 0282559ddf..d881772b8b 100644 --- a/src/game/server/nav_generate.cpp +++ b/src/game/server/nav_generate.cpp @@ -278,11 +278,95 @@ void CNavMesh::CreateLadder( const Vector& absMin, const Vector& absMax, float m } +#ifdef NEO +//-------------------------------------------------------------------------------------------------------------- +static constexpr float LadderEndScanStep = 10.0f; + +/** + * Move a ladder end along the ladder until the space in front of it is clear. + * Returns true if the end moved. + */ +static bool ClearLadderEnd( Vector *end, const Vector &along, float length, const Vector &normal ) +{ + const float minLadderClearance = 32.0f; + + // A brush ladder's ends lie on the face of its own climbable brush, which the trace mask + // can count as solid, so start the clearance traces just off the face. + const float faceOffset = 0.1f; + const Vector offFace = normal * faceOffset; + + trace_t result; + for ( float t = 0.0f; t <= length; t += LadderEndScanStep ) + { + const Vector on = *end + t * along; + const Vector out = on + normal * minLadderClearance; + + UTIL_TraceLine( on + offFace, out, TheNavMesh->GetGenerationTraceMask(), NULL, COLLISION_GROUP_NONE, &result ); + + if (result.fraction == 1.0f && !result.startsolid) + { + *end = on; + return t > 0.0f; + } + } + + return false; +} + + +//-------------------------------------------------------------------------------------------------------------- +/** + * Move both ends of a new ladder to where they are reachable. + * Returns false if a brush ladder has too little climb left to keep. + */ +static bool TrimLadderEnds( CNavLadder *ladder, NavLadderSourceType source ) +{ + Vector along = ladder->m_top - ladder->m_bottom; + const float length = along.NormalizeInPlace(); + + const bool bottomTrimmed = ClearLadderEnd( &ladder->m_bottom, along, length, ladder->GetNormal() ); + const bool topTrimmed = ClearLadderEnd( &ladder->m_top, -along, length, ladder->GetNormal() ); + + ladder->m_length = (ladder->m_top - ladder->m_bottom).Length(); + + if (source != NAV_LADDER_SOURCE_BRUSH) + { + return true; + } + + const float finalSignedSpan = DotProduct( ladder->m_top - ladder->m_bottom, along ); + const char *rejectReason = nullptr; + if (finalSignedSpan <= 0.0f) + { + rejectReason = "coincident or crossed endpoints"; + } + // The clearance scans cannot resolve a remnant shorter than their step. + else if ((bottomTrimmed || topTrimmed) && finalSignedSpan < LadderEndScanStep) + { + rejectReason = "clearance-trimmed span below scan interval"; + } + + if (!rejectReason) + { + return true; + } + + DevMsg( "Brush ladder rejected (%s): raw span %.1f, final signed span %.1f\n", + rejectReason, length, finalSignedSpan ); + return false; +} +#endif // NEO + + //-------------------------------------------------------------------------------------------------------------- /** * Create a navigation representation of a ladder. */ +#ifdef NEO +void CNavMesh::CreateLadder( const Vector &top, const Vector &bottom, float width, const Vector2D &ladderDir, float maxHeightAboveTopArea, NavLadderSourceType source ) +#else void CNavMesh::CreateLadder( const Vector &top, const Vector &bottom, float width, const Vector2D &ladderDir, float maxHeightAboveTopArea ) +#endif // NEO { CNavLadder *ladder = new CNavLadder; @@ -314,6 +398,13 @@ void CNavMesh::CreateLadder( const Vector &top, const Vector &bottom, float widt // adjust top and bottom of ladder to make sure they are reachable // (cs_office has a crate right in front of the base of a ladder) +#ifdef NEO + if (!TrimLadderEnds( ladder, source )) + { + delete ladder; + return; + } +#else Vector along = ladder->m_top - ladder->m_bottom; float length = along.NormalizeInPlace(); Vector on, out; @@ -357,6 +448,7 @@ void CNavMesh::CreateLadder( const Vector &top, const Vector &bottom, float widt } ladder->m_length = (ladder->m_top - ladder->m_bottom).Length(); +#endif // NEO ladder->SetDir( ladder->GetDir() ); // now that we've adjusted the top and bottom, re-check the normal @@ -365,15 +457,104 @@ void CNavMesh::CreateLadder( const Vector &top, const Vector &bottom, float widt ladder->m_topLeftArea = NULL; ladder->m_topRightArea = NULL; ladder->m_topBehindArea = NULL; +#ifdef NEO + // Brush ladders are built before sampling; area creation connects them once areas exist. + if (source != NAV_LADDER_SOURCE_BRUSH) + { + ladder->ConnectGeneratedLadder( maxHeightAboveTopArea ); + } +#else ladder->ConnectGeneratedLadder( maxHeightAboveTopArea ); +#endif // NEO // add ladder to global list m_ladders.AddToTail( ladder ); } +#ifdef NEO +//-------------------------------------------------------------------------------------------------------------- +/** + * Find the area at the bottom of a generated ladder. + */ +static CNavArea *FindLadderBottomArea( const Vector ¢er, NavLadderSourceType source ) +{ + if (source == NAV_LADDER_SOURCE_BRUSH) + { + // The foot is the ladder's bottom end, and it can sit above the floor. + // GetNearestNavArea picks by distance with no beneath test, so from a raised foot + // the top landing can be nearer than the floor. Look straight down first, + // as far as the dangling check lets a foot hang. + const float floorReach = GenerationStepSize + HumanHeight; + CNavArea *floor = TheNavMesh->GetNavArea( center, floorReach ); + if (floor) + { + return floor; + } + } + + return TheNavMesh->GetNearestNavArea( center, true ); +} + + //-------------------------------------------------------------------------------------------------------------- +/** + * Retry the top scans of a brush ladder that found no exit, and drop a forward area far below the top. + */ +static void RetryBrushLadderTopScans( CNavLadder *ladder, const Vector ¢er, float beneathLimit, float nearLadderRange ) +{ + const float behindLadderRange = 2.0f * nearLadderRange; + const NavDirType dir = ladder->GetDir(); + + auto findTopArea = [&]( const Vector &start, NavDirType searchDir, float range ) -> CNavArea * + { + CNavArea *area = findFirstAreaInDirection( &start, searchDir, range, beneathLimit, NULL ); + return (area == ladder->m_bottomArea) ? NULL : area; + }; + + // A climbable brush can end below the landing, where the scan hits the landing's lip. + // Or the space above its top can be solid (a ceiling or prop), so the scan starts inside it. + const float topRetryOffsets[] = { StepHeight, -GenerationStepSize }; + for ( const float offset : topRetryOffsets ) + { + if (ladder->m_topForwardArea || ladder->m_topLeftArea || ladder->m_topRightArea) + { + break; + } + + const Vector retryStart = center + Vector( 0, 0, offset ); + ladder->m_topForwardArea = findTopArea( retryStart, OppositeDirection( dir ), nearLadderRange ); + ladder->m_topLeftArea = findTopArea( retryStart, DirectionLeft( dir ), nearLadderRange ); + ladder->m_topRightArea = findTopArea( retryStart, DirectionRight( dir ), nearLadderRange ); + if (!ladder->m_topBehindArea) + { + ladder->m_topBehindArea = findTopArea( retryStart, dir, behindLadderRange ); + } + } + + if (!ladder->m_topForwardArea) + { + return; + } + + // Over the top of a climbable brush, a floor well below the top lies past the far side of + // the climb, not on a landing; snapping the top down to it would end the climb under the brush top. + Vector close; + ladder->m_topForwardArea->GetClosestPointOnArea( ladder->m_top, &close ); + if (close.z < ladder->m_top.z - StepHeight) + { + ladder->m_topForwardArea = NULL; + } +} +#endif // NEO + + +//-------------------------------------------------------------------------------------------------------------- +#ifdef NEO +void CNavLadder::ConnectGeneratedLadder( float maxHeightAboveTopArea, NavLadderSourceType source ) +#else void CNavLadder::ConnectGeneratedLadder( float maxHeightAboveTopArea ) +#endif // NEO { const float nearLadderRange = 75.0f; // 50 @@ -385,7 +566,11 @@ void CNavLadder::ConnectGeneratedLadder( float maxHeightAboveTopArea ) Vector center = m_bottom + Vector( 0, 0, GenerationStepSize ); AddDirectionVector( ¢er, m_dir, HalfHumanWidth ); +#ifdef NEO + m_bottomArea = FindLadderBottomArea( center, source ); +#else m_bottomArea = TheNavMesh->GetNearestNavArea( center, true ); +#endif // NEO if (!m_bottomArea) { DevMsg( "ERROR: Unconnected ladder bottom at ( %g, %g, %g )\n", m_bottom.x, m_bottom.y, m_bottom.z ); @@ -425,6 +610,13 @@ void CNavLadder::ConnectGeneratedLadder( float maxHeightAboveTopArea ) m_topBehindArea = findFirstAreaInDirection( ¢er, m_dir, 2.0f*nearLadderRange, beneathLimit, NULL ); if (m_topBehindArea == m_bottomArea) m_topBehindArea = NULL; +#ifdef NEO + + if (source == NAV_LADDER_SOURCE_BRUSH) + { + RetryBrushLadderTopScans( this, center, beneathLimit, nearLadderRange ); + } +#endif // NEO // can't include behind area, since it is not used when going up a ladder if (!m_topForwardArea && !m_topLeftArea && !m_topRightArea) @@ -443,7 +635,20 @@ void CNavLadder::ConnectGeneratedLadder( float maxHeightAboveTopArea ) if (m_topBehindArea) { m_topBehindArea->AddLadderDown( this ); +#ifdef NEO + if (source == NAV_LADDER_SOURCE_BRUSH) + { + // Disconnect() clears the first slot holding the area, which is a forward or side slot + // when one of those scans found this area too. + m_topBehindArea = NULL; + } + else + { + Disconnect( m_topBehindArea ); + } +#else Disconnect( m_topBehindArea ); +#endif // NEO } // adjust top of ladder to highest connected area @@ -3403,7 +3608,12 @@ void CNavMesh::CreateNavAreasFromNodes( void ) for ( int i=0; iConnectGeneratedLadder( 0.0f, NAV_LADDER_SOURCE_BRUSH ); +#else ladder->ConnectGeneratedLadder( 0.0f ); +#endif } } } @@ -3437,12 +3647,30 @@ void CNavMesh::AddWalkableSeeds( void ) */ void CNavMesh::BeginGeneration( bool incremental ) { +#ifdef NEO + if (nav_generate_debug_brushladders.GetBool()) + { + if (!BuildBrushLaddersFromBsp()) + { + Warning("Generating brush ladders...FAIL\n"); + } + else + { + Msg( "Generating brush ladders...DONE\n" ); + } + return; + } +#endif + IGameEvent *event = gameeventmanager->CreateEvent( "nav_generate" ); if ( event ) { gameeventmanager->FireEvent( event ); } +#ifdef NEO + engine->ServerCommand( "neo_bot_kick all\n" ); +#else #ifdef TERROR engine->ServerCommand( "director_stop\nnb_delete_all\n" ); if ( !incremental && !engine->IsDedicatedServer() ) @@ -3456,6 +3684,7 @@ void CNavMesh::BeginGeneration( bool incremental ) #else engine->ServerCommand( "bot_kick\n" ); #endif +#endif // NEO // Right now, incrementally-generated areas won't connect to existing areas automatically. // Since this means hand-editing will be necessary, don't do a full analyze. @@ -3478,6 +3707,18 @@ void CNavMesh::BeginGeneration( bool incremental ) if ( !incremental ) ///< @incremental update doesn't build ladders to avoid overlapping existing ones { BuildLadders(); +#ifdef NEO + // Before sampling, so the sampler also explores from the ladder ends and reaches + // landings that only a climb leads to. + if (!BuildBrushLaddersFromBsp()) + { + Warning("Generating brush ladders...FAIL\n"); + } + else + { + Msg( "Generating brush ladders...DONE\n" ); + } +#endif } // start sampling from a spawn point @@ -4221,6 +4462,15 @@ inline CNavNode *LadderEndSearch( const Vector *pos, NavDirType mountDir ) Vector tryNormal; if (TheNavMesh->GetGroundHeight( tryPos, &tryPos.z, &tryNormal ) == false) continue; +#ifdef NEO + + // Ground this far below the ladder end is a fall, not a dismount; a climbable brush + // over a void would otherwise seed the void's floor. + if (pos->z - tryPos.z > HumanHeight) + { + continue; + } +#endif // make sure this point is not on the other side of a wall const float fudge = 4.0f; diff --git a/src/game/server/nav_ladder.h b/src/game/server/nav_ladder.h index 295dc90b9d..e24ef224ae 100644 --- a/src/game/server/nav_ladder.h +++ b/src/game/server/nav_ladder.h @@ -15,6 +15,14 @@ class CNavArea; +#ifdef NEO +enum NavLadderSourceType +{ + NAV_LADDER_SOURCE_DEFAULT, + NAV_LADDER_SOURCE_BRUSH, ///< built from a climbable brush of the BSP +}; +#endif // NEO + //-------------------------------------------------------------------------------------------------------------- /** * The NavLadder represents ladders in the Navigation Mesh, and their connections to adjacent NavAreas @@ -71,7 +79,11 @@ class CNavLadder bool IsConnected( const CNavArea *area, LadderDirectionType dir ) const; ///< returns true if given area is connected in given direction +#ifdef NEO + void ConnectGeneratedLadder( float maxHeightAboveTopArea, NavLadderSourceType source = NAV_LADDER_SOURCE_DEFAULT ); ///< Connect a generated ladder to nav areas at the end of nav generation +#else void ConnectGeneratedLadder( float maxHeightAboveTopArea ); ///< Connect a generated ladder to nav areas at the end of nav generation +#endif void ConnectTo( CNavArea *area ); ///< connect this ladder to given area void Disconnect( CNavArea *area ); ///< disconnect this ladder from given area diff --git a/src/game/server/nav_mesh.cpp b/src/game/server/nav_mesh.cpp index de1255ae73..fce5c5cad2 100644 --- a/src/game/server/nav_mesh.cpp +++ b/src/game/server/nav_mesh.cpp @@ -26,6 +26,11 @@ #include "tf/nav_mesh/tf_nav_area.h" #endif +#ifdef NEO +#include "mathlib/polyhedron.h" +#include "nav.h" +#include "polylib.h" +#endif #ifdef NEXT_BOT #include "NextBot/NavMeshEntities/func_nav_prerequisite.h" #endif @@ -38,6 +43,14 @@ #define DrawLine( from, to, duration, red, green, blue ) NDebugOverlay::Line( from, to, red, green, blue, true, NDEBUG_PERSIST_TILL_NEXT_SERVER ) +#ifdef NEO +static auto DrawBrushLadderLine(const Vector& from, const Vector& to, float duration = NDEBUG_PERSIST_TILL_NEXT_SERVER, + int r = 255, int g=255, int b=255) +{ + return NDebugOverlay::Line(from, to, r, g, b, true, duration); +} +#endif + /** * The singleton for accessing the navigation mesh @@ -56,6 +69,12 @@ ConVar nav_max_vis_delta_list_length( "nav_max_vis_delta_list_length", "64", FCV extern ConVar nav_show_potentially_visible; +#ifdef NEO +ConVar nav_generate_debug_brushladders("nav_generate_debug_brushladders", "0", FCVAR_CHEAT, + "If non-zero, will only visualize ladder brush generation during nav_generate and do nothing else. " + "The visualization will remain visible for the amount of seconds specified by cvar value.", + true, false, false, 0); +#endif bool FindGroundForNode( Vector *pos, Vector *normal ); @@ -531,6 +550,33 @@ void CNavMesh::AddNavArea( CNavArea *area ) ++m_areaCount; } +#ifdef NEO +//-------------------------------------------------------------------------------------------------------------- +/** + * Add an area to every grid cell of its extent that does not hold it yet. + * Merging grows an area in place, so its new part would otherwise be missing from the grid. + */ +void CNavMesh::AddNavAreaToGrid( CNavArea *area ) +{ + const int loX = WorldToGridX( area->GetCorner( NORTH_WEST ).x ); + const int loY = WorldToGridY( area->GetCorner( NORTH_WEST ).y ); + const int hiX = WorldToGridX( area->GetCorner( SOUTH_EAST ).x ); + const int hiY = WorldToGridY( area->GetCorner( SOUTH_EAST ).y ); + + for ( int y = loY; y <= hiY; ++y ) + { + for ( int x = loX; x <= hiX; ++x ) + { + NavAreaVector &cell = m_grid[ x + y*m_gridSizeX ]; + if ( !cell.HasElement( area ) ) + { + cell.AddToTail( area ); + } + } + } +} +#endif // NEO + //-------------------------------------------------------------------------------------------------------------- /** * Remove an area from the mesh @@ -3229,6 +3275,592 @@ void CNavMesh::DestroyLadders( void ) m_markedLadder = NULL; m_selectedLadder = NULL; } +#ifdef NEO + +namespace Neo +{ + struct MockBspHdr { + decltype(dheader_t::ident) ident; + decltype(dheader_t::version) version; + }; + + // Sanity check BSP header, version, and endianness compatibility. + // Has the side-effect of reading sizeof(Neo::MockBspHdr) into the file handle. + static bool ValidateBspHeader(FileHandle_t f) + { + static_assert(VALVE_LITTLE_ENDIAN); + + MockBspHdr hdr; + filesystem->Read(&hdr, sizeof(hdr), f); + if (hdr.ident != IDBSPHEADER) + { + CByteswap().SwapBuffer(&hdr.ident, &hdr.ident); + if (hdr.ident != IDBSPHEADER) + { + Warning("%s: invalid BSP file ident 0x%x (expected 0x%x)\n", + __FUNCTION__, hdr.ident, IDBSPHEADER); + return false; + } + else + { + Warning("%s: BSP had unsupported endianness (expected %s, was %s)\n", + __FUNCTION__, + VALVE_LITTLE_ENDIAN ? "little" : "big", + VALVE_LITTLE_ENDIAN ? "big" : "little"); + return false; + } + } + else if (hdr.version < MINBSPVERSION || hdr.version > BSPVERSION) + { + Warning("%s: unsupported BSP file version %d (expected in range %d-%d)\n", + __FUNCTION__, hdr.version, MINBSPVERSION, BSPVERSION); + return false; + } + + return true; + } + + constexpr static auto LumpHdrOffs(GameLumpId_t id) + { + auto lumpBegin = _hacky_datamap_offsetof(dheader_t, lumps); + return narrow_cast(lumpBegin + id * sizeof(lump_t)); + } + + [[nodiscard]] static bool ReadLumpHdr(GameLumpId_t id, FileHandle_t f, lump_t* out) + { + constexpr auto lumpSize = sizeof(std::remove_pointer_t); + static_assert(lumpSize > 0); + + Assert(filesystem); + Assert(f); + + const auto seekOffs = LumpHdrOffs(id); + if (seekOffs < 0) + { + Assert(false); + return false; + } + else if (seekOffs > filesystem->Size(f) + lumpSize) + { + Assert(false); + return false; + } + + filesystem->Seek(f, LumpHdrOffs(id), FILESYSTEM_SEEK_HEAD); + + const auto totalRead = filesystem->Read(out, lumpSize, f); + const bool ok = (totalRead == lumpSize); + Assert(ok); + return ok; + } + + template + [[nodiscard]] static bool ReadLump(GameLumpId_t id, FileHandle_t f, T* out, + int startLump = 0, int numLumpsToRead = 1, const lump_t* lump = {}) + { + if (numLumpsToRead == 0) + { + return true; // if they want to read nothing, that's fine I suppose + } + else + { + Assert(filesystem); + } + + if (numLumpsToRead < 0) + { + Warning("%s: Cannot read negative amount of lumps (%d)\n", __FUNCTION__, numLumpsToRead); + return false; + } + if (startLump < 0) + { + Warning("%s: Lump start position cannot be negative\n", __FUNCTION__); + return false; + } + if (!f) + { + Warning("%s: Invalid file handle\n", __FUNCTION__); + return false; + } + + lump_t hdr; + if (!ReadLumpHdr(id, f, &hdr)) + { + Warning("%s: Failed to read BSP header for lump %d\n", __FUNCTION__, id); + return false; + } + if (hdr.fileofs < 0) + { + Warning("%s: Lump hdr reported negative target lump offset %d\n", __FUNCTION__, hdr.fileofs); + return false; + } + if (hdr.filelen < 0) + { + Warning("%s: File hdr reported negative target lump length %d\n", __FUNCTION__, hdr.filelen); + return false; + } + + const auto fileTargetLumpOffset = hdr.fileofs + startLump * sizeof(T); + if (fileTargetLumpOffset <= 0) + { + Warning("%s: Expected a positive target lump offset for lump %d but got %zu\n", __FUNCTION__, id, fileTargetLumpOffset); + return false; + } + else if (fileTargetLumpOffset > std::numeric_limits::max()) + { + Warning("%s: Starting to read lumpid(s) of type %d from index %d would require lump offset of %zu which is >max: %d\n", + __FUNCTION__, id, startLump, fileTargetLumpOffset, std::numeric_limits::max()); + return false; + } + + const auto numLumpsAvailable = hdr.filelen / sizeof(T); + Assert(numLumpsAvailable >= 0); + + if (numLumpsToRead > numLumpsAvailable) + { + Warning("%s: Requested %d lump(s) of type %d but only %zu such lump(s) available\n", + __FUNCTION__, numLumpsToRead, id, numLumpsAvailable); + return false; + } + + const auto fileSize = filesystem->Size(f); + const auto sizeToRead = sizeof(T) * numLumpsToRead; + if (sizeToRead > std::numeric_limits::max()) + { + Warning("%s: Reading %d lumps of lumpid %d would require %zu bytes which >max: %d\n", + __FUNCTION__, numLumpsToRead, id, sizeToRead, std::numeric_limits::max()); + return false; + } + + const auto requiredSize = fileTargetLumpOffset + sizeToRead; + Assert(fileSize > 0); + Assert(requiredSize > 0); + if (fileSize < requiredSize) + { + Warning("%s: File size (%d bytes) not large enough to process %d lump(s) offset for lumpid %d (%zu bytes)\n", + __FUNCTION__, fileSize, numLumpsToRead, id, requiredSize); + return false; + } + + filesystem->Seek(f, narrow_cast(fileTargetLumpOffset), FILESYSTEM_SEEK_HEAD); + + const auto bytesReadTotal = filesystem->Read(out, narrow_cast(sizeToRead), f); + if (bytesReadTotal != sizeToRead) + { + Warning("%s: Expected to read %zu bytes from %d lump(s) of type %d, but read %d bytes\n", + __FUNCTION__, sizeToRead, numLumpsToRead, id, bytesReadTotal); + return false; + } + + return true; + } + + template + [[nodiscard]] static bool ReadLump(GameLumpId_t id, FileHandle_t f, T& out, + int startLump = 0, const lump_t* lump = {}) + { + return ReadLump(id, f, &out, startLump, 1, lump); + } + + [[nodiscard]] static bool ReadBrushes(FileHandle_t f, CUtlVector& out) + { + lump_t brushHdr; + if (!ReadLumpHdr(LUMP_BRUSHES, f, &brushHdr)) + { + Warning("%s: failed to read brush lump hdr\n", __FUNCTION__); + return false; + } + const auto mapBrushCount = narrow_cast(brushHdr.filelen / sizeof(dbrush_t)); + if (mapBrushCount <= 0) + { + Warning("%s: could not find any brushes for bsp\n", __FUNCTION__); + return false; + } + else if (mapBrushCount > MAX_MAP_BRUSHES) + { + Warning("%s: map reported to contain %d brushes but max is %d\n", + __FUNCTION__, mapBrushCount, MAX_MAP_BRUSHES); + return false; + } + + out.EnsureCapacity(mapBrushCount); + dbrush_t brush; + for (int i = 0; i < mapBrushCount; ++i) + { + if (!ReadLump(LUMP_BRUSHES, f, brush, i, &brushHdr)) + { + Warning("%s: failed to read brush %d lump contents\n", __FUNCTION__, i); + return false; + } + + if (!(brush.contents & CONTENTS_LADDER)) + { + continue; + } + + if (brush.numsides < 4) + { + Warning("%s ladder brush %d reported %d numsides which is insufficient to construct a polyhedron\n", + __FUNCTION__, i, brush.numsides); + continue; + } + + if (brush.numsides > MAX_MAP_BRUSHSIDES) + { + Warning("%s ladder brush %d reported %d numsides which is more than max supported: %d\n", + __FUNCTION__, i, brush.numsides, MAX_MAP_BRUSHSIDES); + continue; + } + + out.AddToTail(brush); + } + + return true; + } + + [[nodiscard]] static bool ReadCSG(FileHandle_t f, + CUtlVector>& out) + { + CUtlVector brushes; + if (!ReadBrushes(f, brushes)) + { + return false; + } + + CUtlVector ladderSides; + CUtlVector ladderPlanes; + + out.EnsureCapacity(brushes.Count()); + Assert(out.Count() == 0); + for (const auto& brush : brushes) + { + ladderSides.SetCount(brush.numsides); + if (!Neo::ReadLump(LUMP_BRUSHSIDES, f, ladderSides.Base(), brush.firstside, brush.numsides)) + { + Warning("%s: failed to read brush sides lump contents %d - %d\n", __FUNCTION__, brush.firstside, brush.firstside + brush.numsides); + return false; + } + + ladderPlanes.Purge(); + for (int j = 0; j < ladderSides.Count(); ++j) + { + auto* storeAddr = ladderPlanes.AddToTailGetPtr(); + Assert(storeAddr); + if (!Neo::ReadLump(LUMP_PLANES, f, storeAddr, ladderSides[j].planenum)) + { + Warning("%s: failed to read plane lump contents for ladder side %d of plane num %d\n", __FUNCTION__, + j, ladderSides[j].planenum); + return false; + } + Assert(storeAddr->normal.IsValid()); + Assert(IsFinite(storeAddr->dist)); + } + Assert(ladderPlanes.Count() > 0); + + auto* nextPlanes = out.AddToTailGetPtr(); + nextPlanes->EnsureCapacity(ladderPlanes.Count()); + Assert(nextPlanes->Count() == 0); + for (const auto& p : ladderPlanes) + { + Vector4D alignedPlane{ p.normal.x, p.normal.y, p.normal.z, p.dist }; + Assert(alignedPlane.IsValid()); + nextPlanes->AddToTail(alignedPlane); + } + Assert(nextPlanes->Count() == ladderPlanes.Count()); + } + Assert(out.Count() == brushes.Count()); + + return true; + } +} + +void CNavMesh::LadderFromPolyhedron(const CPolyhedron* polyhedron) +{ + Assert(polyhedron); + + if (nav_generate_debug_brushladders.GetBool()) + { + Assert(debugoverlay); + } + + // To be used for the center position of each polygon of the polyhedron. + // By reference, because the final CommandNavBuildLadder call which actually builds the ladder + // depends on this state, and we can spare the extra Vector by just assigning to it directly. + Vector& polyCenter = m_editCursorPos; + Vector& polyNormal = m_surfaceNormal; + + const int firstLadder = m_ladders.Count(); + + Vector polyMins, polyMaxs; + trace_t tr; + for (int i = 0; i < polyhedron->iPolygonCount; ++i) + { + const auto& polygon = polyhedron->pPolygons[i]; + polyNormal = { polygon.polyNormal.x, polygon.polyNormal.y, polygon.polyNormal.z }; +#ifdef DBGFLAG_ASSERT + { + Assert(polyNormal.IsValid()); + Assert(!polyNormal.IsZero()); + AssertFloatEquals(polyNormal.Length(), 1.f, 0.01f); // unit vector + } +#endif + // Can't build up/down facing ladder mounting points, skip + if (!polyNormal.x && !polyNormal.y) + { + continue; + } + // Also reject sides that the nav system considers too flat for ladders + if (polyNormal.z) + { + extern ConVar nav_slope_limit; + Assert(nav_slope_limit.GetFloat() >= 0); + Assert(nav_slope_limit.GetFloat() <= 1); + if (abs(polyNormal.z) > nav_slope_limit.GetFloat()) + { + continue; + } + } + + if (nav_generate_debug_brushladders.GetBool()) + { + DevMsg("---\n\t%d POLYGON: %d\n", i, polygon.iIndexCount); + } + + ClearBounds(polyMins, polyMaxs); + + for (int j = 0; j < polygon.iIndexCount; ++j) + { + auto index = polygon.iFirstIndex + j; + const auto& idxLineRef = polyhedron->pIndices[index]; + const auto& pointIndices = polyhedron->pLines[idxLineRef.iLineIndex].iPointIndices; + + const Vector& linePos1 = polyhedron->pVertices[pointIndices[0]]; + const Vector& linePos2 = polyhedron->pVertices[pointIndices[1]]; + Assert(linePos1.IsValid()); + Assert(linePos2.IsValid()); + Assert(linePos1 != linePos2); + + AddPointToBounds(linePos1, polyMins, polyMaxs); + AddPointToBounds(linePos2, polyMins, polyMaxs); + + if (nav_generate_debug_brushladders.GetBool()) + { + DevMsg("\t\tLINE: %f %f %f -> %f %f %f\n", + linePos1.x, linePos1.y, linePos1.z, + linePos2.x, linePos2.y, linePos2.z); + + static int r = 0; + r = (r + 25) % 255; + DrawBrushLadderLine(linePos1, linePos2, + nav_generate_debug_brushladders.GetFloat(), r, 255, 255); + } + } + polyCenter = VectorLerp(polyMins, polyMaxs, 0.5); + + enum LadderPolyFilterReason { + ThisIsFine = 0, // No problems detected, do not filter this poly. + TooSlim, // At least one of the dimensions of this 2D poly is unacceptably slim for bot navigation. + TooCramped, // Insufficient nav clearance for bots to meaningfully mount here. + } filter = ThisIsFine; + + // Ignore ladder polygons that are super slim, because it's likely either a side + // or a bevel of the actual intended mounting point. + // While such surfaces *could* sometimes be used by humans, they require a lot of + // finesse to meaningfully traverse, so it's better for the bots to prefer the obvious + // large mapper-intended primary climb surfaces. Of course, the mapper could opt + // to manually markup their custom slim ladders as usual outside the auto-gen. + constexpr float smallestLadderDimToConsider = 4; + int nSmaller = 0; + nSmaller += (polyMaxs.x - polyMins.x < smallestLadderDimToConsider); + nSmaller += (polyMaxs.y - polyMins.y < smallestLadderDimToConsider); + nSmaller += (polyMaxs.z - polyMins.z < smallestLadderDimToConsider); + // Because the poly mins/maxs are modeling a 2D surface, it is expected for + // one of the dimensions to be 0 or near 0. But if 2 or more are below + // smallestLadderDimToConsider, then we do want to filter. + if (nSmaller > 1) + { + filter = TooSlim; + } + + else if (filter == ThisIsFine) + { + // Cull ladder sides facing the wall etc. + // Need clearance of at least GenerationStepSize in front of the ladder to mount. + UTIL_TraceLine( + polyCenter + (polyNormal * ON_EPSILON), + polyCenter + (polyNormal * GenerationStepSize), + GetGenerationTraceMask(), nullptr, COLLISION_GROUP_NONE, &tr); + if (tr.DidHit()) + { + filter = TooCramped; + } + } + + if (nav_generate_debug_brushladders.GetBool()) + { + Color c; + switch (filter) + { + case ThisIsFine: + c = COLOR_LIME; + break; + case TooSlim: + c = COLOR_DARK_ORANGE; + break; + case TooCramped: + c = COLOR_NEON_PINK; + break; + default: + c = COLOR_BLACK; + Assert(false); + break; + } + DevMsg("\t\tPOLY NORMAL: %f %f %f\n", + polyNormal.x, polyNormal.y, polyNormal.z); + DrawBrushLadderLine(polyCenter, polyCenter + (polyNormal * GenerationStepSize), + nav_generate_debug_brushladders.GetFloat(), c.r(), c.g(), c.b()); + } + + if (filter != ThisIsFine) + { + if (nav_generate_debug_brushladders.GetBool()) + { + DevMsg("\t\tREJECTED! enum: %d\n", filter); + } + continue; + } + + // Create for real only if we're not debugging this logic + if (nav_generate_debug_brushladders.GetBool()) + { + continue; + } + + // Set up state as required by the CommandNavBuildLadder call below + m_editMode = EditModeType::NORMAL; + m_climbableSurface = true; + + CommandNavBuildLadder(NAV_LADDER_SOURCE_BRUSH); + } + + RemoveNarrowSideLadders(firstLadder); +} + +// A climb brush often has climbable end faces narrower than its main face. The player hull +// overhangs such a face, so a small sideways drift while climbing loses the surface, and bots +// mounting one fall off. Drop a ladder of the brush when a wider one facing another way covers +// the same height. +void CNavMesh::RemoveNarrowSideLadders(int firstLadder) +{ + constexpr float widthTolerance = 1.0f; + + for (int i = m_ladders.Count() - 1; i >= firstLadder; --i) + { + const CNavLadder* ladder = m_ladders[i]; + bool covered = false; + for (int j = firstLadder; j < m_ladders.Count() && !covered; ++j) + { + const CNavLadder* other = m_ladders[j]; + covered = other->GetDir() != ladder->GetDir() + && other->m_width > ladder->m_width + widthTolerance + && other->m_top.z >= ladder->m_top.z - StepHeight + && other->m_bottom.z <= ladder->m_bottom.z + StepHeight; + } + + if (!covered) + { + continue; + } + + CNavLadder* sideLadder = m_ladders[i]; + m_ladders.Remove(i); + OnEditDestroyNotify(sideLadder); + delete sideLadder; + } +} + +bool CNavMesh::BuildBrushLaddersFromBsp() +{ + bool ok = true; + + FileHandle_t f = {}; + CUtlVector> planesOfLadderBrushes; + + Assert(gpGlobals); + if (gpGlobals->bMapLoadFailed) + { + Warning("%s: map load failed\n", __FUNCTION__); + goto fail; + } + + char mapPath[MAX_PATH]; + Assert(!!gpGlobals->mapname && *gpGlobals->mapname.ToCStr()); + Assert(V_strlen(gpGlobals->mapname.ToCStr()) < MAX_MAP_NAME); + V_sprintf_safe(mapPath, "maps/%s.bsp", gpGlobals->mapname.ToCStr()); + if (!*mapPath) + { + Warning("%s: failed to get map name\n", __FUNCTION__); + goto fail; + } + + Assert(filesystem); + if (!filesystem->FileExists(mapPath)) + { + Warning("%s: failed to locate map from filesystem: \"%s\"\n", + __FUNCTION__, mapPath); + goto fail; + } + + f = filesystem->Open(mapPath, "rb"); + if (!f) + { + Warning("%s: failed to open map file handle\n", __FUNCTION__); + goto fail; + } + + if (!Neo::ValidateBspHeader(f)) + { + goto fail; + } + + if (!Neo::ReadCSG(f, planesOfLadderBrushes)) + { + goto fail; + } + + if (planesOfLadderBrushes.Count() == 0) // no ladders? + { + goto cleanup; + } + + for (const auto& planesOfLadderBrush : planesOfLadderBrushes) + { + auto* polyhedron = GeneratePolyhedronFromPlanes( + planesOfLadderBrush.Base()->Base(), + planesOfLadderBrush.Count(), + ON_EPSILON, true); + + if (!polyhedron) + { + Assert(false); + goto fail; + } + + LadderFromPolyhedron(polyhedron); + polyhedron->Release(); + } + +cleanup: + if (f) + { + filesystem->Close(f); + } + return ok; +fail: + ok = false; + goto cleanup; +} +#endif //-------------------------------------------------------------------------------------------------------------- /** diff --git a/src/game/server/nav_mesh.h b/src/game/server/nav_mesh.h index b4a665b024..ccfa2bfab2 100644 --- a/src/game/server/nav_mesh.h +++ b/src/game/server/nav_mesh.h @@ -36,6 +36,9 @@ extern ConVar nav_edit; extern ConVar nav_quicksave; extern ConVar nav_show_approach_points; extern ConVar nav_show_danger; +#ifdef NEO +extern ConVar nav_generate_debug_brushladders; +#endif //-------------------------------------------------------------------------------------------------------- class NavAreaCollector @@ -456,7 +459,11 @@ class CNavMesh : public CGameEventListener void CommandNavLadderFlip( void ); // Flips the direction a ladder faces void CommandNavToggleAttribute( NavAttributeType attribute ); // toggle an attribute on current area void CommandNavMakeSniperSpots( void ); // cuts up the marked area into individual areas suitable for sniper spots +#ifdef NEO + void CommandNavBuildLadder( NavLadderSourceType source = NAV_LADDER_SOURCE_DEFAULT ); // builds a nav ladder on the climbable surface under the cursor +#else void CommandNavBuildLadder( void ); // builds a nav ladder on the climbable surface under the cursor +#endif void CommandNavRemoveJumpAreas( void ); // removes jump areas, replacing them with connections void CommandNavSubdivide( const CCommand &args ); // subdivide each nav area in X and Y to create 4 new areas - limit min size void CommandNavSaveSelected( const CCommand &args ); // Save selected set to disk @@ -486,7 +493,11 @@ class CNavMesh : public CGameEventListener } void CreateLadder( const Vector &mins, const Vector &maxs, float maxHeightAboveTopArea ); +#ifdef NEO + void CreateLadder( const Vector &top, const Vector &bottom, float width, const Vector2D &ladderDir, float maxHeightAboveTopArea, NavLadderSourceType source = NAV_LADDER_SOURCE_DEFAULT ); +#else void CreateLadder( const Vector &top, const Vector &bottom, float width, const Vector2D &ladderDir, float maxHeightAboveTopArea ); +#endif float SnapToGrid( float x, bool forceGrid = false ) const; // snap given coordinate to generation grid boundary Vector SnapToGrid( const Vector& in, bool snapX = true, bool snapY = true, bool forceGrid = false ) const; // snap given vector's X & Y coordinates to generation grid boundary @@ -1128,6 +1139,9 @@ class CNavMesh : public CGameEventListener void GridToWorld( int gridX, int gridY, Vector *pos ) const; void AddNavArea( CNavArea *area ); // add an area to the grid +#ifdef NEO + void AddNavAreaToGrid( CNavArea *area ); // add an area to grid cells its grown extent now covers +#endif // NEO void DestroyNavigationMesh( bool incremental = false ); // free all resources of the mesh and reset it to empty state void DestroyHidingSpots( void ); @@ -1213,6 +1227,13 @@ class CNavMesh : public CGameEventListener NavLadderVector m_ladders; // list of ladder navigation representations void BuildLadders( void ); void DestroyLadders( void ); +#ifdef NEO + // Build ladders from the BSP brush lump ladders (rather than func_ladder) + [[nodiscard]] bool BuildBrushLaddersFromBsp(); +private: + void LadderFromPolyhedron(const CPolyhedron* polyhedron); + void RemoveNarrowSideLadders(int firstLadder); +#endif bool SampleStep( void ); // sample the walkable areas of the map void CreateNavAreasFromNodes( void ); // cover all of the sampled nodes with nav areas diff --git a/src/game/server/ndebugoverlay.cpp b/src/game/server/ndebugoverlay.cpp index fa152ba3fc..934adb0ff1 100644 --- a/src/game/server/ndebugoverlay.cpp +++ b/src/game/server/ndebugoverlay.cpp @@ -66,7 +66,11 @@ OverlayLine_t* GetDebugOverlayLine(void) // Input : If testLOS is true, color is based on line of sight test // Output : //----------------------------------------------------------------------------- +#ifdef NEO +void UTIL_AddDebugLine(const Vector &startPos, const Vector &endPos, bool noDepthTest, bool testLOS, const Color& color) +#else void UTIL_AddDebugLine(const Vector &startPos, const Vector &endPos, bool noDepthTest, bool testLOS) +#endif { OverlayLine_t* debugLine = GetDebugOverlayLine(); @@ -88,9 +92,15 @@ void UTIL_AddDebugLine(const Vector &startPos, const Vector &endPos, bool noDept } } +#ifdef NEO + debugLine->r = color.r(); + debugLine->g = color.g(); + debugLine->b = color.b(); +#else debugLine->r = 255; debugLine->g = 255; debugLine->b = 255; +#endif } //----------------------------------------------------------------------------- diff --git a/src/game/server/ndebugoverlay.h b/src/game/server/ndebugoverlay.h index 7b0a64a9d3..2a68d7e15c 100644 --- a/src/game/server/ndebugoverlay.h +++ b/src/game/server/ndebugoverlay.h @@ -25,7 +25,11 @@ struct OverlayLine_t bool draw; }; +#ifdef NEO +extern void UTIL_AddDebugLine( const Vector &startPos, const Vector &endPos, bool noDepthTest, bool testLOS, const Color& color={255,255,255,255}); +#else extern void UTIL_AddDebugLine( const Vector &startPos, const Vector &endPos, bool noDepthTest, bool testLOS ); +#endif extern void UTIL_DrawPositioningOverlay( float flCrossDistance ); extern void UTIL_DrawOverlayLines( void ); diff --git a/src/game/shared/shareddefs.h b/src/game/shared/shareddefs.h index b290d6486e..e0ad452dd3 100644 --- a/src/game/shared/shareddefs.h +++ b/src/game/shared/shareddefs.h @@ -628,6 +628,9 @@ typedef enum #define COLOR_TRANSPARENT Color(0, 0, 0, 0) #define COLOR_DARK Color(55, 55, 55, 255) #define COLOR_FADED_DARK Color(55, 55, 55, 176) +#define COLOR_NEON_PINK Color(255, 16, 240) +#define COLOR_DARK_ORANGE Color(255, 140, 0) +#define COLOR_LIME Color(0, 255, 0) #endif // All NPCs need this data diff --git a/src/public/mathlib/polyhedron.h b/src/public/mathlib/polyhedron.h index 22859167fb..1ce75a4434 100644 --- a/src/public/mathlib/polyhedron.h +++ b/src/public/mathlib/polyhedron.h @@ -26,8 +26,8 @@ struct BasicVector { BasicVector res; res.x = x + v.x; - res.x = y + v.y; - res.x = z + v.z; + res.y = y + v.y; + res.z = z + v.z; return res; } @@ -35,8 +35,8 @@ struct BasicVector { BasicVector res; res.x = x - v.x; - res.x = y - v.y; - res.x = z - v.z; + res.y = y - v.y; + res.z = z - v.z; return res; } @@ -44,8 +44,8 @@ struct BasicVector { BasicVector res; res.x = x * v; - res.x = y * v; - res.x = z * v; + res.y = y * v; + res.z = z * v; return res; }