Skip to content

Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.

feat(ai): price the ground units keep getting stuck on

Olcay Seygan60dc9bef16f6
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
index 2da685c82..ab9c7ff31 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h
@@ -777,6 +777,9 @@ public:
static void bumpNoPath( void ); ///< a path request came back empty
static void bumpBlockedFrame( Bool stuck ); ///< one unit-frame spent blocked by another unit
static void bumpQueueDetour( void ); ///< a unit gave up on its queue and repathed round it
+
+ void noteJam( const ICoord2D& cell ); ///< one blocked unit-frame, stamped where it happened
+ void decayJamMap( void ); ///< age the whole map; call once per logic frame
void processPathfindQueue(void); ///< Process some or all of the queued pathfinds.
void forceMapRecalculation( ); ///< Force pathfind map recomputation. If region is given, only that area is recomputed
@@ -1002,6 +1005,11 @@ private:
UnsignedByte *m_pathUsage; ///< Congestion map, (hi.x+1)*(hi.y+1), indexed [x*(hi.y+1)+y]
Int getPathUsage( Int x, Int y ) const;
+ UnsignedByte *m_jamMap; ///< Jam map, same shape and indexing: where units are actually stuck
+ Int m_jamCells; ///< non-zero cells in it, so an unjammed match never sweeps the map
+ UnsignedInt m_jamDecayFrame; ///< logic frame the last decay ran on
+ Int getJam( Int x, Int y ) const;
+
//
// Reservation map. A dense per-cell array would be a second whole-map allocation to hold a few
// thousand live claims, so the claims live in a pool and are found through a fixed hash of the
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
index 8b4d8ee7d..143b0a54d 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
@@ -487,6 +487,7 @@ public:
// That is what says "I am in a line, not in traffic".
//
Bool isQueuedBehindUnits(void) const;
+ Int getNumFramesQueued(void) const {return m_queueFrames;}
void spendQueueCredit(void); ///< a path was computed; the detour has had its chance
Bool canComputeQuickPath(void); ///< Returns true if we can quickly comput a path. Usually missiles & the like that just move straight to the destination.
Bool computeQuickPath(const Coord3D *destination); ///< Computes a quick path to the destination.
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
index b7ad31a78..3cd1084e7 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp
@@ -375,6 +375,9 @@ void AI::update( void )
Int64 start, afterPathfind, end;
QueryPerformanceCounter( (LARGE_INTEGER *)&start );
+ // age the record of where units have been getting stuck, before any search reads it
+ m_pathfinder->decayJamMap();
+
// Do pathfinding.
m_pathfinder->processPathfindQueue();
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
index 00b655650..828b5781c 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
@@ -2017,6 +2017,42 @@ const Int PATH_CONGESTION_MAX_PATHS = 4; ///< the penalty stops growing past thi
const Int PATH_QUEUE_COST = 5*COST_ORTHOGONAL;
const Int PATH_QUEUE_RANGE = 10; ///< cells from the start within which standing units cost extra
+/* Both costs above describe a moment. The congestion map says somebody's path runs through a cell,
+ the queue cost says somebody is standing in it right now, and neither remembers anything: a
+ doorway that has been solid for two seconds is priced exactly like one a tank has just rolled
+ into. A unit repathing out of a queue therefore keeps choosing the doorway its own column is
+ wedged in, because at the instant the search runs the cells past the jam are empty.
+
+ The jam map is the memory. Every blocked unit stamps the cell it is standing in, once a frame,
+ and the whole map loses one everywhere every JAM_DECAY_FRAMES - so a cell holds roughly the
+ blocked unit-frames spent in it over the last JAM_MAX*JAM_DECAY_FRAMES frames, which is 80
+ frames, a bit under three seconds. Integer and quantised on the frame number, because a
+ real-valued decay read by the search is a desync waiting for a machine with a different FPU.
+
+ JAM_FLOOR is the "three or more" gate: one unit pausing for a frame is traffic and stamps 1 or
+ 2, and only ground that several units have been stuck on, or one has been stuck on for a while,
+ gets past 3 and costs anything. Like every other cost here it is capped, for the reason the
+ congestion comment gives at length - the A* heuristic cannot see it, so an uncapped version
+ floods the search. */
+const Int PATH_JAM_COST = 3*COST_ORTHOGONAL; ///< per blocked unit-frame above the floor
+const Int PATH_JAM_FLOOR = 3; ///< stamps below this are traffic, not a jam
+const Int PATH_JAM_MAX = 10; ///< the stamp saturates here
+const Int PATH_JAM_DECAY_FRAMES = 8; ///< every cell loses one stamp this often
+const Int PATH_JAM_MAX_CHARGED = 4; ///< the penalty stops growing past this much over the floor
+
+/* Split out for the same reason as the congestion penalty: the floor and the cap are the whole of
+ the design, and a version without either is a search that floods or a cost that fires on
+ ordinary traffic. */
+Int Pathfinder_jamPenalty( Int jam )
+{
+ Int over = jam - PATH_JAM_FLOOR;
+ if (over <= 0)
+ return 0;
+ if (over > PATH_JAM_MAX_CHARGED)
+ over = PATH_JAM_MAX_CHARGED;
+ return over * PATH_JAM_COST;
+}
+
/* Split out of examineNeighboringCells so the cap is testable: the cap is the only thing keeping
this cost from flooding the search, since the heuristic cannot see it. */
Int Pathfinder_congestionPenalty( Int usage, Int costPerPath )
@@ -4272,7 +4308,7 @@ void PathfindLayer::classifyWallMapCell( Int i, Int j , PathfindCell *cell, Obje
//----------------------- Pathfinder ---------------------------------------
-Pathfinder::Pathfinder( void ) :m_map(NULL), m_pathUsage(NULL)
+Pathfinder::Pathfinder( void ) :m_map(NULL), m_pathUsage(NULL), m_jamMap(NULL)
{
debugPath = NULL;
PathfindCellInfo::allocateCellInfos();
@@ -4401,6 +4437,12 @@ void Pathfinder::reset( void )
delete [] m_pathUsage;
m_pathUsage = NULL;
}
+ if (m_jamMap) {
+ delete [] m_jamMap;
+ m_jamMap = NULL;
+ }
+ m_jamCells = 0;
+ m_jamDecayFrame = 0;
resetReservations();
Int i;
@@ -5133,6 +5175,10 @@ void Pathfinder::newMap( void )
}
m_pathUsage = MSGNEW("PathfindMapCells") UnsignedByte[(bounds.hi.x+1)*(bounds.hi.y+1)];
memset(m_pathUsage, 0, (bounds.hi.x+1)*(bounds.hi.y+1));
+ m_jamMap = MSGNEW("PathfindMapCells") UnsignedByte[(bounds.hi.x+1)*(bounds.hi.y+1)];
+ memset(m_jamMap, 0, (bounds.hi.x+1)*(bounds.hi.y+1));
+ m_jamCells = 0;
+ m_jamDecayFrame = 0;
for (i=0; i<LAYER_LAST; i++) {
if (!m_layers[i].isUnused()) {
m_layers[i].allocateCells(&m_extent);
@@ -5834,6 +5880,53 @@ void Pathfinder::releasePathUsageBefore( const Path *path, const PathNode *node
path->setUsageHead(node);
}
+//-------------------------------------------------------------------------------------------------
+// Jam map. Same cells again, holding what actually happened rather than what somebody planned.
+Int Pathfinder::getJam( Int x, Int y ) const
+{
+ if (!m_jamMap || x < m_extent.lo.x || x > m_extent.hi.x || y < m_extent.lo.y || y > m_extent.hi.y)
+ return 0;
+ return m_jamMap[x*(m_extent.hi.y+1)+y];
+}
+
+/* One blocked unit, one frame, one cell. Called from doLocomotor, which is the only place a unit
+ is counted once per frame instead of once per collision pair - a cell where two units keep
+ bumping each other must not stamp twice as fast as a cell where one is wedged against a wall. */
+void Pathfinder::noteJam( const ICoord2D& cell )
+{
+ if (!m_jamMap) return;
+ if (cell.x < m_extent.lo.x || cell.x > m_extent.hi.x ||
+ cell.y < m_extent.lo.y || cell.y > m_extent.hi.y) return;
+ UnsignedByte &jam = m_jamMap[cell.x*(m_extent.hi.y+1)+cell.y];
+ if (jam == 0)
+ m_jamCells++;
+ if (jam < PATH_JAM_MAX)
+ jam++;
+}
+
+/* The decay, once every PATH_JAM_DECAY_FRAMES, off the logic frame number so that every machine
+ does it on the same frame. A whole-map sweep is a quarter of a megabyte on a big map, which is
+ why m_jamCells is kept: a match with nothing jammed anywhere - which is most of a match - does
+ not touch the map at all. */
+void Pathfinder::decayJamMap( void )
+{
+ if (!m_jamMap || m_jamCells == 0) return;
+ UnsignedInt now = TheGameLogic->getFrame();
+ if (now - m_jamDecayFrame < (UnsignedInt)PATH_JAM_DECAY_FRAMES) return;
+ m_jamDecayFrame = now;
+
+ const Int cells = (m_extent.hi.x+1)*(m_extent.hi.y+1);
+ Int nonZero = 0;
+ for (Int i = 0; i < cells; i++)
+ {
+ if (m_jamMap[i] == 0)
+ continue;
+ if (--m_jamMap[i] > 0)
+ nonZero++;
+ }
+ m_jamCells = nonZero;
+}
+
//-------------------------------------------------------------------------------------------------
// Reservation map. Same cells as the congestion map, one entry each, plus the frame and heading.
Int Pathfinder::reservationBucketOf( Int x, Int y )
@@ -7105,7 +7198,13 @@ Int Pathfinder::examineNeighboringCells(PathfindCell *parentCell, PathfindCell *
info.layer = parentCell->getLayer();
info.centerInCell = centerInCell;
info.radius = radius;
- info.considerTransient = false;
+ /* The two guards below were written to switch this off outside a small box around the
+ start, which only means something if it is on inside that box. EA initialised it to
+ false, so both branches assigned the same value, the guards were dead and the main A*
+ has never been able to see a moving unit at all: a queued tank repathed with the queue
+ invisible and got the line it was already standing in handed back. Only the cells
+ next to the start, and only for a unit that does not drive through people. */
+ info.considerTransient = !canPathThroughUnits;
info.acceptableSurfaces = locomotorSet.getValidSurfaces();
Int dx = newCellCoord.x-startCellNdx.x;
Int dy = newCellCoord.y-startCellNdx.y;
@@ -7143,6 +7242,14 @@ Int Pathfinder::examineNeighboringCells(PathfindCell *parentCell, PathfindCell *
&& (info.allyMoving || info.allyFixedCount>0)) {
newCostSoFar += queueCost;
}
+ // ...and the ground they have been stuck on for the last couple of seconds, which is not
+ // the same ground: a doorway empties for a frame every time the jam shuffles, and the
+ // search that runs in that frame is the one that routes another unit into it. Only the
+ // unit leaving a queue pays this, for the same reason it is the only one paying the cost
+ // above - every other search keeps retail's routes.
+ if (queueCost && m_jamMap && dx<PATH_QUEUE_RANGE && dy<PATH_QUEUE_RANGE) {
+ newCostSoFar += Pathfinder_jamPenalty( getJam(newCellCoord.x, newCellCoord.y) );
+ }
if (m_pathUsage && dx < PATH_CONGESTION_RANGE && dy < PATH_CONGESTION_RANGE) {
// Other units' live paths through our footprint: pay per path so we pick a parallel
// lane. Capped, because the heuristic does not know about this cost and an uncapped
@@ -11328,11 +11435,12 @@ Path *Pathfinder::getMoveAwayFromPath(Object* obj, Object *otherObj,
ICoord2D startCellNdx;
Coord3D startPos = *obj->getPosition();
if (!centerInCell) {
+ // same EA typo as in patchPath: the second increment is the y half-cell
startPos.x += PATHFIND_CELL_SIZE_F*0.5f;
- startPos.x += PATHFIND_CELL_SIZE_F*0.5f;
+ startPos.y += PATHFIND_CELL_SIZE_F*0.5f;
}
worldToCell(&startPos, &startCellNdx);
- PathfindCell *parentCell = getClippedCell( obj->getLayer(), obj->getPosition() );
+ PathfindCell *parentCell = getClippedCell( obj->getLayer(), obj->getPosition() );
if (parentCell == NULL)
return false;
if (!obj->getAIUpdateInterface()) {
@@ -11504,8 +11612,10 @@ Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSet
ICoord2D startCellNdx;
Coord3D startPos = *obj->getPosition();
if (!centerInCell) {
+ // EA incremented x twice; the second one is the y half-cell, and without it the start cell
+ // of every even-footprint unit is one cell off along one axis only
startPos.x += PATHFIND_CELL_SIZE_F*0.5f;
- startPos.x += PATHFIND_CELL_SIZE_F*0.5f;
+ startPos.y += PATHFIND_CELL_SIZE_F*0.5f;
}
worldToCell(&startPos, &startCellNdx);
//worldToCell(obj->getPosition(), &startCellNdx);
@@ -11545,6 +11655,24 @@ Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSet
}
#endif
+ /* How far from the start a moving unit still counts as being in the way. EA's fixed two cells
+ is the distance a tank covers in well under the second that passes between deciding to leave
+ a queue and getting the new path, so by the time the path came back the unit it was supposed
+ to route around had left the window and the patch went straight back into the line. Scale it
+ with the footprint and with how far this unit travels while it waits, and cap it: past six
+ cells the search is being told to avoid ground that will be empty by the time it gets there. */
+ Int transientWindow = 2 + radius;
+ {
+ const Locomotor *loco = obj->getAIUpdateInterface()->getCurLocomotor();
+ if (loco) {
+ Real speed = loco->getMaxSpeedForCondition(obj->getBodyModule()->getDamageState());
+ transientWindow += REAL_TO_INT(speed * LOGICFRAMES_PER_SECOND / PATHFIND_CELL_SIZE_F);
+ }
+ const Int TRANSIENT_WINDOW_MAX = 6;
+ if (transientWindow > TRANSIENT_WINDOW_MAX)
+ transientWindow = TRANSIENT_WINDOW_MAX;
+ }
+
PathNode *startNode;
Coord3D goalPos = *originalPath->getLastNode()->getPosition();
Real goalDeltaSqr = sqr(goalPos.x-currentPosition.x) + sqr(goalPos.y - currentPosition.y);
@@ -11568,8 +11696,8 @@ Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSet
#endif
Int dx = cellCoord.x-startCellNdx.x;
Int dy = cellCoord.y-startCellNdx.y;
- if (dx<-2 || dx>2) info.considerTransient = false;
- if (dy<-2 || dy>2) info.considerTransient = false;
+ if (dx<-transientWindow || dx>transientWindow) info.considerTransient = false;
+ if (dy<-transientWindow || dy>transientWindow) info.considerTransient = false;
if (!checkForMovement(obj, info)) {
break;
}
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
index 90cb85eec..4d030b69f 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp
@@ -1761,6 +1761,25 @@ void AIInternalMoveToState::onExit( StateExitType status )
}
}
+/* Does this unit look like it is moving, to a player watching it? EA answered with a frame count -
+ a quarter of a second of blocked frames cleared MODELCONDITION_MOVING - and a frame count is not
+ a speed. A tank easing round a jam at a third of its top speed is moving; it was drawn parked
+ and sliding along the ground, and half of the stop-and-go a player complains about is that
+ drawing rather than the movement underneath it.
+
+ A tenth of top speed, from the physics, because that is under anything a wheel or a walk cycle
+ reads as: a unit doing 10% is covering its own length in about two seconds. Split out so the
+ threshold can be checked without a renderer, which is the only check available - a headless run
+ draws nothing, so no batch can measure this. Client-side and outside the CRC either way.
+
+ With no locomotor to ask, maxSpeed is zero and the test degenerates to "is it moving at all",
+ which is what the code did before the threshold went in and is the right answer for something
+ being carried or shoved rather than driving. */
+Bool AIState_looksLikeMoving( Real speedNow, Real maxSpeed )
+{
+ return speedNow > 0.1f * maxSpeed;
+}
+
/**
* Execute the moveTo behavior towards GoalPosition.
*/
@@ -1853,10 +1872,19 @@ StateReturnType AIInternalMoveToState::update()
obj->clearModelConditionState( MODELCONDITION_RAPPELLING );
}
}
- if (ai->getNumFramesBlocked()>LOGICFRAMES_PER_SECOND/4)
+ /* Whether the drive animation plays is a question about speed, and EA asked it about frames: a
+ quarter second of blocked frames stopped the animation whatever the unit was actually doing,
+ so a tank crawling round a jam at a third of its speed stood still on screen and slid. Half
+ of the stop-and-go a player complains about is this line rather than the movement code. Ask
+ the physics instead, through AIState_looksLikeMoving. */
+ Real speedNow = obj->getPhysics() ? obj->getPhysics()->getVelocityMagnitude() : 0.0f;
+ Real maxSpeed = 0.0f;
+ if (ai->getCurLocomotor())
+ maxSpeed = ai->getCurLocomotor()->getMaxSpeedForCondition( obj->getBodyModule()->getDamageState() );
+ if (!AIState_looksLikeMoving( speedNow, maxSpeed ))
{
obj->clearModelConditionState( MODELCONDITION_MOVING );
- }
+ }
else
{
//Clear climbing if modelConditionFlag is not climbing
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
index c5586e1da..ef55624c3 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
@@ -108,6 +108,111 @@ Bool AIUpdate_isQueued( Int queueFrames )
return queueFrames >= QUEUE_FRAMES_THRESHOLD;
}
+//
+// Following the unit in front. See calculateMaxBlockedSpeed for why EA's version (copy his speed,
+// read no distance) turns one leader's hiccup into a full stop for everybody behind him.
+//
+// FOLLOW_GAIN is per logic frame, so at 30fps a car one cell too close closes about a third of the
+// error each frame and settles inside half a second without overshooting into a collision. Higher
+// values ring; lower ones let the column concertina.
+//
+const Real FOLLOW_GAIN = 0.35f; ///< how much of the spacing error is corrected per frame
+const Real BLOCKED_HEAD_ON = -0.3f; ///< headings this opposed are a collision, not a queue
+const Real BLOCKED_SPEED_FILTER = 0.3f; ///< how much of the new ceiling the speed limit takes per frame
+
+/* Split out so the following law can be checked without a game: it is the whole of "how fast may I
+ go behind him", and a version that gets it wrong either rear-ends the leader or stops dead. */
+Real AIUpdate_followSpeed( Real leaderSpeed, Real gap, Real desiredGap )
+{
+ Real speed = leaderSpeed + FOLLOW_GAIN * (gap - desiredGap);
+ if (speed < 0.0f)
+ speed = 0.0f;
+ return speed;
+}
+
+/* The blocked speed limit, one frame at a time. EA multiplied it by 0.95 for every blocked frame
+ and by 1.05 on the way out, off a floor of a fifth of the desired speed: twenty blocked frames
+ took a unit to 36% and forty to 13%, and climbing back cost over a second. Blocked traffic
+ therefore ratcheted itself to a crawl and released in a sawtooth, which is the stop-and-go a
+ player watches. A first-order filter toward the ceiling absorbs a one-frame dip and still
+ tracks a ceiling that stays low, with no direction that is cheaper than the other. */
+Real AIUpdate_smoothBlockedSpeed( Real current, Real target, Real cap )
+{
+ // FAST_AS_POSSIBLE is a sentinel, not a speed; and no ceiling above what we want means anything
+ if (current > cap) current = cap;
+ if (target > cap) target = cap;
+ if (target < 0.0f) target = 0.0f;
+ return current + BLOCKED_SPEED_FILTER * (target - current);
+}
+
+// Overtaking - a unit blocked by traffic going its own way steering one or two footprints sideways
+// and driving in that lane - was built here and taken out again. Two 40-match batches on maps its
+// constants were never fitted to: blocked unit-frames a coin flip (thirteen matches better, seven
+// worse, one seed carrying three quarters of the mean), and stuck frames worse. The only effect
+// that reproduced was search work, about a sixth fewer cell expansions, which is not what the
+// change was for. PATHFINDING-PLAN.md P3 has the numbers; EA turned their own version off too.
+
+//
+// -tracemove [id]: one line a frame for one unit. A jam is an argument between the speed the unit
+// wants, the ceiling its last collision put on it, the decaying bump limit and the frames it has
+// spent blocked, and from outside the object none of those four is visible - the run-level counters
+// can say 40000 blocked frames and still not say which of the four zeroed the tank. The columns
+// are in the order the code applies them, so the first one that goes to zero is the culprit.
+//
+// With no id the trace latches onto the first unit that gets blocked and follows it for the rest of
+// the run: in a batch nobody knows an object id in advance, and the interesting unit is by
+// definition one that is stuck. Output only - nothing here is read back by any logic.
+//
+static ObjectID theTracedObjectID = INVALID_ID;
+
+void AIUpdate_resetMoveTrace( void )
+{
+ theTracedObjectID = INVALID_ID;
+}
+
+static void AIUpdate_traceMove( const Object *obj, Bool blocked, Int blockedFrames, Int queueFrames,
+ Real desiredSpeed, Real maxSpeed, Real maxBlockedSpeed,
+ Real bumpSpeedLimit, Bool waitingForPath, Bool hasPath,
+ Bool stuck )
+{
+ const Int wanted = TheGlobalData ? TheGlobalData->m_traceMoveID : 0;
+ if (wanted == 0)
+ return;
+
+ if (wanted > 0)
+ {
+ if (obj->getID() != (ObjectID)wanted)
+ return;
+ }
+ else
+ {
+ // no id given: the first unit to get blocked is the one we follow from then on
+ if (theTracedObjectID == INVALID_ID)
+ {
+ if (!blocked)
+ return;
+ theTracedObjectID = obj->getID();
+ }
+ else if (obj->getID() != theTracedObjectID)
+ {
+ return;
+ }
+ }
+
+ const Coord3D *pos = obj->getPosition();
+ const PhysicsBehavior *physics = obj->getPhysics();
+ const Real actualSpeed = physics ? physics->getVelocityMagnitude() : 0.0f;
+ DEBUG_LOG(("MOVETRACE %d,%d,%.2f,%.2f,%.3f,%.3f,%.3f,%.3f,%.3f,%d,%d,%d,%d,%d\n",
+ TheGameLogic->getFrame(), (Int)obj->getID(), pos->x, pos->y,
+ actualSpeed, desiredSpeed, maxSpeed, maxBlockedSpeed, bumpSpeedLimit,
+ blocked ? 1 : 0, blockedFrames, queueFrames, waitingForPath ? 1 : 0,
+ hasPath ? 1 : 0));
+ if (stuck)
+ {
+ DEBUG_LOG(("MOVETRACE %d,%d,stuck\n", TheGameLogic->getFrame(), (Int)obj->getID()));
+ }
+}
+
#ifdef _INTERNAL
// for occasional debugging...
//#pragma optimize("", off)
@@ -1304,6 +1409,19 @@ Bool AIUpdateInterface::hasHigherPathPriority(AIUpdateInterface *otherAI) const
//-------------------------------------------------------------------------------------------------
/* Returns max speed we can have and not run into unit that is blocking us.
+
+ EA set our ceiling to exactly the blocker's speed away from us and read no distance at all, so a
+ blocker that dipped for one frame stopped the follower for that frame whether it was one foot
+ behind or five - and the follower's own dip did the same to whoever was behind it. That is a
+ phantom jam: it grows as it travels backwards down a column, and it is a property of the rule
+ rather than of the traffic.
+
+ The gap term is what a following model needs and this one had none of: match the leader's speed,
+ plus a correction proportional to how much room is left. Closer than we want, give some back;
+ further, close it up. Both units then hold a spacing instead of trading full stops.
+
+ The head-on early return keeps its zero, but only for headings genuinely opposed. At exactly
+ zero it fired on anything a shade off perpendicular, which on a curve is most of a column.
*/
Real AIUpdateInterface::calculateMaxBlockedSpeed(Object *other) const
{
@@ -1313,19 +1431,21 @@ Real AIUpdateInterface::calculateMaxBlockedSpeed(Object *other) const
Coord2D vectorToOther;
vectorToOther.x = other->getPosition()->x - getObject()->getPosition()->x;
vectorToOther.y = other->getPosition()->y - getObject()->getPosition()->y;
+ Real distance = vectorToOther.length();
vectorToOther.normalize();
Real dotProduct = vectorToOther.x*otherDir.x + vectorToOther.y*otherDir.y;
- if (dotProduct<0) return 0; // They are running into us.
+ if (dotProduct<BLOCKED_HEAD_ON) return 0; // They are running into us.
Real speedFactor = dotProduct;
+ if (speedFactor < 0) speedFactor = 0; // off to one side: they are taking nothing with them
PhysicsBehavior *otherPhysics = other->getPhysics();
if (!otherPhysics) {
return m_curMaxBlockedSpeed;
- }
+ }
Coord3D otherVel = *otherPhysics->getVelocity();
otherVel.z = 0;
// Calculate how fast other is moving away from us...
- Real awaySpeed = otherVel.length() * speedFactor;
+ Real awaySpeed = otherVel.length() * speedFactor;
// Now calculate the amount we are moving relative to towards them...
dotProduct = vectorToOther.x*ourDir.x + vectorToOther.y*ourDir.y;
@@ -1334,9 +1454,17 @@ Real AIUpdateInterface::calculateMaxBlockedSpeed(Object *other) const
return m_curMaxBlockedSpeed;
}
Real maxSpeed = awaySpeed / dotProduct;
+
+ // the room between the two hulls, and the room we would like there to be
+ Real myRadius = getObject()->getGeometryInfo().getBoundingCircleRadius();
+ Real hisRadius = other->getGeometryInfo().getBoundingCircleRadius();
+ Real gap = distance - (myRadius + hisRadius);
+ Real desiredGap = 0.5f * PATHFIND_CELL_SIZE_F;
if (other->getFormationID()!=NO_FORMATION_ID && getObject()->getFormationID()==other->getFormationID()) {
- maxSpeed *= 0.55f; // don't let formations crowd each other.
+ desiredGap *= 2.0f; // don't let formations crowd each other.
}
+ maxSpeed = AIUpdate_followSpeed( maxSpeed, gap, desiredGap );
+
if (maxSpeed>m_curMaxBlockedSpeed) return m_curMaxBlockedSpeed;
return maxSpeed;
}
@@ -1543,7 +1671,7 @@ Bool AIUpdateInterface::processCollision(PhysicsBehavior *physics, Object *other
}
}
m_isBlocked = TRUE; // we are blocked.
- if (otherMoving && aiOther->isWaitingForPath())
+ if (otherMoving && aiOther->isWaitingForPath())
{
return FALSE; // let them get their path;
}
@@ -1822,8 +1950,10 @@ Bool AIUpdateInterface::computePath( PathfindServicesInterface *pathServices, Co
}
if (theNewPath==NULL && m_path==NULL) {
Real pathCostFactor = 0.0f;
- theNewPath = pathServices->findClosestPath( getObject(), m_locomotorSet, getObject()->getPosition(),
- destination, m_isBlockedAndStuck, pathCostFactor, FALSE );
+ // a unit leaving a queue is blocked in every sense that matters to the search, even though
+ // nothing has been jammed against it long enough to call it stuck
+ theNewPath = pathServices->findClosestPath( getObject(), m_locomotorSet, getObject()->getPosition(),
+ destination, m_isBlockedAndStuck || isQueuedBehindUnits(), pathCostFactor, FALSE );
m_retryPath = true;
}
TheAI->pathfinder()->setIgnoreObstacleID( INVALID_ID );
@@ -2239,12 +2369,16 @@ UpdateSleepTime AIUpdateInterface::doLocomotor( void )
// this is the only place a blocked unit is counted once per frame rather than once per
// collision pair, so it is where the traffic-jam number for the headless run comes from
Pathfinder::bumpBlockedFrame( m_isBlockedAndStuck );
+ // and for the same reason it is where the jam map is stamped: this ground was not passable
+ // this frame, whatever the cell says by the time somebody searches it
+ TheAI->pathfinder()->noteJam( m_pathfindCurCell );
}
else
{
m_blockedFrames = 0;
}
+ const Bool traceWasBlocked = m_isBlocked; // -tracemove: the flag is cleared on the next line
m_isBlocked = FALSE;
Bool blocked = m_blockedFrames > 0;
@@ -2317,26 +2451,22 @@ UpdateSleepTime AIUpdateInterface::doLocomotor( void )
if( speed == FAST_AS_POSSIBLE || speed > myMaxSpeed )
speed = myMaxSpeed;
- if (blocked && speed>m_curMaxBlockedSpeed)
+ if (blocked && speed>m_curMaxBlockedSpeed)
{
- speed = m_curMaxBlockedSpeed;
- if (m_bumpSpeedLimit>speed) {
- m_bumpSpeedLimit = speed;
- }
- m_bumpSpeedLimit *= 0.95f;
+ // track the ceiling instead of ratcheting down to it - see
+ // AIUpdate_smoothBlockedSpeed
+ m_bumpSpeedLimit = AIUpdate_smoothBlockedSpeed( m_bumpSpeedLimit, m_curMaxBlockedSpeed, speed );
speed = m_bumpSpeedLimit;
- }
- else
+ }
+ else
{
blocked = FALSE;
- if (m_bumpSpeedLimit<FAST_AS_POSSIBLE) {
- if (m_bumpSpeedLimit<speed*0.2f) {
- m_bumpSpeedLimit = speed*0.2f;
- }
- m_bumpSpeedLimit *= 1.05f;
- }
- if (speed>m_bumpSpeedLimit) {
+ if (m_bumpSpeedLimit<speed) {
+ // the same filter, now aimed at what we actually want
+ m_bumpSpeedLimit = AIUpdate_smoothBlockedSpeed( m_bumpSpeedLimit, speed, speed );
speed = m_bumpSpeedLimit;
+ } else {
+ m_bumpSpeedLimit = FAST_AS_POSSIBLE;
}
}
@@ -2401,6 +2531,13 @@ UpdateSleepTime AIUpdateInterface::doLocomotor( void )
else
getObject()->clearStatus( MAKE_OBJECT_STATUS_MASK( OBJECT_STATUS_AIRBORNE_TARGET ) );
+ // before the ceiling is thrown away for the frame - it is the value the trace is about
+ AIUpdate_traceMove( getObject(), traceWasBlocked, m_blockedFrames, m_queueFrames,
+ m_desiredSpeed,
+ m_curLocomotor->getMaxSpeedForCondition(getObject()->getBodyModule()->getDamageState()),
+ m_curMaxBlockedSpeed, m_bumpSpeedLimit, isWaitingForPath(), getPath() != NULL,
+ m_isBlockedAndStuck );
+
m_curMaxBlockedSpeed = FAST_AS_POSSIBLE;
}
diff --git a/Tools/PathLab/pathlab.py b/Tools/PathLab/pathlab.py
index efeec6ebe..48160b583 100644
--- a/Tools/PathLab/pathlab.py
+++ b/Tools/PathLab/pathlab.py
@@ -87,6 +87,25 @@ PATH_CROSSING_WINDOW: int = 12 # frames either side of an arrival t
PATH_CROSSING_MAX: int = 3 # cap, same reason the congestion cost has one
SAME_WAY: float = 0.6 # headings this aligned are a queue, not a crossing
+# Both maps above describe a plan. The congestion map says somebody's route runs through a cell and
+# the reservation map says when, and neither remembers anything that has already happened: a doorway
+# four tanks have been wedged in for two seconds is priced exactly like empty ground, because the
+# units in it have stopped and stopped units have no route left to claim. A unit repathing out of
+# the back of that queue therefore picks the same doorway, every time, at the instant its search
+# runs.
+#
+# The jam map is the memory. A blocked unit stamps the cell it is standing in, once a frame; the
+# whole map loses one everywhere every JAM_DECAY_FRAMES, so a cell carries roughly the blocked
+# unit-frames spent in it over the last JAM_MAX*JAM_DECAY_FRAMES frames. AIPathfind.cpp's m_jamMap,
+# at its constants and with its two gates: only a repath reads it, and only within JAM_RANGE cells
+# of where that repath starts. A search that is not leaving a jam keeps the plain shortest route.
+PATH_JAM_COST: int = 3 * COST_ORTHOGONAL # three cells of detour per stamp over the floor
+PATH_JAM_FLOOR: int = 3 # one unit pausing stamps 1 or 2: that is traffic
+PATH_JAM_MAX: int = 10 # the stamp saturates here
+PATH_JAM_DECAY_FRAMES: int = 8 # every cell loses one this often
+PATH_JAM_MAX_CHARGED: int = 4 # cap over the floor, same reason the others have one
+PATH_JAM_RANGE: int = 10 # cells from the start the penalty is read within
+
# Two points closer than this are the same point: a zero-length segment has no direction to take.
EPSILON: float = 1e-3
# Larger than any route this grid can produce, so it reads as "not reached yet" in the A* tables.
@@ -125,6 +144,22 @@ PARK_RETRY_LIMIT: int = 3
SWERVE_ATTEMPTS: tuple[tuple[float, float], ...] = (
(0.0, 1.0), (0.0, 0.4), (0.6, 0.8), (-0.6, 0.8), (1.2, 0.6), (-1.2, 0.6))
+# Lane changing. The engine's only answer to being blocked is to go slower, and a swerve that
+# lasts one frame is not an overtake - the unit re-aims at its waypoint next frame and files back
+# in behind the same tank. A lane is a sideways shift of the goal that is held long enough to get
+# past somebody, and it is only taken when there is a lane to take: the probe below is the
+# sandbox's isLinePassable, drawn like every other check this file makes.
+LANE_CHANGE: bool = False # --lanes
+LANE_CHANGE_AFTER_FRAMES: int = 15 # blocked this long before looking for a way round
+LANE_CHANGE_OFFSETS: tuple[float, ...] = (1.0, -1.0, 2.0, -2.0) # footprints, nearest side first
+LANE_CHANGE_LOOKAHEAD: float = 6.0 # footprints of clear line a lane has to have
+LANE_CHANGE_REACH: float = 2.5 # radii within which somebody counts as "in front"
+LANE_CHANGE_AHEAD: float = 0.5 # how far off our nose he may be and still be in the way
+LANE_CHANGE_SAME_WAY: float = 0.5 # headings this aligned are traffic, not a head-on
+LANE_HOLD_FRAMES: int = 45 # hold a lane this long, or it flickers every frame
+LANE_CHANGE_STALLED_ONLY: bool = True # overtake a queue that is stopped, not one that flows
+LANE_RAYS_KEPT: int = 24 # how many lane probes stay drawable per unit
+
# Ordering
LANES_MAX: int = 3
LANES_MIN: int = 2
@@ -339,6 +374,51 @@ def count_path_overlap(units: Sequence["Unit"]) -> int:
return sum(claimants - 1 for claimants in claims.values() if claimants > 1)
+class JamMap:
+ """Where units actually got stuck, as opposed to where they said they would drive.
+ Pathfinder::noteJam / decayJamMap, on a dict because the sandbox has no map array.
+
+ The decay runs off the frame number rather than a call count, which is what makes it
+ identical on two machines in the engine and reproducible between two sweep rows here."""
+
+ def __init__(self) -> None:
+ self.jam: dict[Cell, int] = {}
+ self.decayed_at: int = 0
+ self.peak: int = 0 # most cells jammed at once, which no engine counter reports
+
+ def note(self, cell: Cell) -> None:
+ stamp = self.jam.get(cell, 0)
+ if stamp < PATH_JAM_MAX:
+ self.jam[cell] = stamp + 1
+ self.peak = max(self.peak, len(self.jam))
+
+ def at(self, cell: Cell) -> int:
+ return self.jam.get(cell, 0)
+
+ def decay(self, frame: int) -> None:
+ """A match with nothing jammed anywhere - which is most of a match - touches nothing."""
+ if not self.jam or frame - self.decayed_at < PATH_JAM_DECAY_FRAMES:
+ return
+ self.decayed_at = frame
+ self.jam = {cell: stamp - 1 for cell, stamp in self.jam.items() if stamp > 1}
+
+ @property
+ def blocking_cells(self) -> int:
+ """Cells jammed hard enough to cost a repath anything, which is the number that matters -
+ a map full of stamps of 1 is a map with no jam on it."""
+ return sum(1 for stamp in self.jam.values() if stamp > PATH_JAM_FLOOR)
+
+
+def price_jam(jam: int) -> int:
+ """The floor is the whole design: below it a cell is traffic and costs nothing, above it the
+ cost is capped, because the A* heuristic cannot see this penalty and an uncapped one turns
+ the search into a flood."""
+ over = jam - PATH_JAM_FLOOR
+ if over <= 0:
+ return 0
+ return min(over, PATH_JAM_MAX_CHARGED) * PATH_JAM_COST
+
+
class Reservation(NamedTuple):
"""One unit's claim on one cell: when it expects to be there, and which way it is going."""
arrival: float
@@ -453,6 +533,8 @@ class PathPricing:
owner: int | None = None
reservations: ReservationMap | None = None
start_frame: float = 0.0
+ # not None only for a search leaving a jam: an ordinary order keeps the plain shortest route
+ jam: JamMap | None = None
NO_PRICING = PathPricing()
@@ -467,8 +549,10 @@ class TrafficModel:
a bare `True, False` at every call site instead."""
usage: UsageMap
reservations: ReservationMap
+ jam: JamMap = field(default_factory=JamMap)
is_congestion_charged: bool = True
is_crossing_charged: bool = True
+ is_jam_charged: bool = True
@property
def congestion_range(self) -> int:
@@ -488,6 +572,14 @@ class TrafficModel:
return PathPricing(usage=self.usage, congestion_range=self.congestion_range, owner=owner,
reservations=self.priced_reservations, start_frame=now)
+ def repath_pricing(self, owner: int, now: float) -> PathPricing:
+ """The same, plus the jam map - and this is the only search that reads it. A unit only
+ repaths here because it stopped making progress, which is the sandbox's whole notion of
+ leaving a queue; the engine gates the same cost on isQueuedBehindUnits."""
+ pricing = self.pricing_for(owner, now)
+ pricing.jam = self.jam if self.is_jam_charged else None
+ return pricing
+
def corridor_pricing(self, now: float) -> PathPricing:
"""The group corridor is one search for the whole group, so it pays no congestion - its own
units are the congestion. It still dodges other groups' moments."""
@@ -555,6 +647,10 @@ def astar(grid: Grid, start: Cell, goal: Cell, *, clearance: int = 0,
and abs(neighbour[1] - start[1]) < pricing.congestion_range):
new_cost += price_congestion(
pricing.usage.count_paths_on(neighbour, pricing.owner))
+ if pricing.jam is not None:
+ if (abs(neighbour[0] - start[0]) < PATH_JAM_RANGE
+ and abs(neighbour[1] - start[1]) < PATH_JAM_RANGE):
+ new_cost += price_jam(pricing.jam.at(neighbour))
if pricing.reservations is not None and grid.has_room(*neighbour):
when = pricing.start_frame + frames_for_cost(new_travel)
heading = (dx / STEP_LEN[step_cost], dy / STEP_LEN[step_cost])
@@ -612,7 +708,14 @@ class Unit:
index: int = 0
is_selected: bool = False
blocked_frames: int = 0 # had to slow, swerve or stop for another unit
+ blocked_run: int = 0 # consecutive such frames, which is what a lane needs
+ lane_dx: float = 0.0 # sideways shift of the goal while overtaking ...
+ lane_dy: float = 0.0
+ lane_frames: int = 0 # ... and how much longer it is held
+ lane_changes: int = 0
stuck_run: int = 0 # consecutive frames going nowhere -> repath
+ jam_priced: int = 0 # repaths that had jammed ground in front of them at all
+ jam_detours: int = 0 # ... and of those, the ones that came out avoiding it
last_dist: float | None = None # distance to the current waypoint, to notice inching
repaths: int = 0
goal: Point | None = None # where this unit was actually sent, after the spread
@@ -658,6 +761,92 @@ def resolve_overlaps(units: Sequence[Unit], grid: Grid) -> None:
second.y += uy
+def blocker_ahead(units: Sequence[Unit], mover: Unit, hx: float, hy: float) -> Unit | None:
+ """Whoever we are stuck behind: the nearest unit within a couple of radii, in front of the
+ nose rather than beside it. This is the sandbox's blockedBy."""
+ found: Unit | None = None
+ reach = LANE_CHANGE_REACH * (mover.radius * 2.0)
+ for other in units:
+ if other is mover:
+ continue
+ ox, oy = other.x - mover.x, other.y - mover.y
+ distance = math.hypot(ox, oy)
+ if distance < EPSILON or distance > reach:
+ continue
+ if (ox * hx + oy * hy) / distance < LANE_CHANGE_AHEAD:
+ continue
+ found, reach = other, distance
+ return found
+
+
+def unit_heading(unit: Unit) -> Heading | None:
+ """Where a unit is going this frame, which for a lane change is more useful than where it is."""
+ if unit.has_arrived:
+ return None
+ tx, ty = unit.path[unit.index]
+ dx, dy = tx - unit.x, ty - unit.y
+ distance = math.hypot(dx, dy)
+ if distance < EPSILON:
+ return None
+ return dx / distance, dy / distance
+
+
+def pick_lane(grid: Grid, units: Sequence[Unit], mover: Unit,
+ hx: float, hy: float) -> Point | None:
+ """Sideways, not slower. Try one footprint out on each side, then two, and take the first that
+ has a clear line three footprints ahead and nobody already sitting in it. Returns the shift
+ to add to the goal, or None when there is no lane - a doorway, a cliff, a full road - and the
+ unit has to fall back on following the man in front."""
+ footprint = mover.radius * 2.0
+ ahead = LANE_CHANGE_LOOKAHEAD * footprint
+ for offset in LANE_CHANGE_OFFSETS:
+ side = offset * footprint
+ px, py = -hy * side, hx * side
+ tip = (mover.x + px + hx * ahead, mover.y + py + hy * ahead)
+ entry = (mover.x + px + hx * footprint, mover.y + py + hy * footprint)
+ is_clear = (grid.line_passable(mover.x, mover.y, tip[0], tip[1], radius=mover.radius)
+ and not is_occupied(units, mover, entry[0], entry[1]))
+ # drawn like the planner's own checks, but a run makes thousands of these and only the
+ # last few are worth looking at
+ mover.rays.append((mover.x, mover.y, tip[0], tip[1], is_clear))
+ if len(mover.rays) > LANE_RAYS_KEPT:
+ del mover.rays[:-LANE_RAYS_KEPT]
+ if is_clear:
+ return px, py
+ return None
+
+
+def update_lane(grid: Grid, units: Sequence[Unit], mover: Unit, hx: float, hy: float) -> None:
+ """One unit's lane, one frame. A lane is dropped the moment the road ahead clears, which is
+ the sandbox's version of patching back onto the path when blockedBy goes false."""
+ ahead = blocker_ahead(units, mover, hx, hy)
+ if mover.lane_frames > 0:
+ mover.lane_frames -= 1
+ if ahead is None:
+ mover.lane_frames = 0
+ if mover.lane_frames == 0:
+ mover.lane_dx = mover.lane_dy = 0.0
+ return
+ if mover.blocked_run < LANE_CHANGE_AFTER_FRAMES or ahead is None:
+ return
+ # somebody coming the other way is a collision, and going round him is how two columns swap
+ # sides and jam worse; this reflex is for traffic that is going where we are going, slower
+ other_heading = unit_heading(ahead)
+ if other_heading is None or other_heading[0] * hx + other_heading[1] * hy < LANE_CHANGE_SAME_WAY:
+ return
+ # a queue that is moving is a queue doing its job; leaving it costs distance and gains nothing.
+ # Only a stalled one is worth going round, which is also the case the player complains about
+ if LANE_CHANGE_STALLED_ONLY and ahead.blocked_run <= 0:
+ return
+ lane = pick_lane(grid, units, mover, hx, hy)
+ if lane is None:
+ return
+ mover.lane_dx, mover.lane_dy = lane
+ mover.lane_frames = LANE_HOLD_FRAMES
+ mover.lane_changes += 1
+ mover.blocked_run = 0
+
+
def yield_for(units: Sequence[Unit], grid: Grid, mover: Unit, hx: float, hy: float) -> None:
"""A unit that has arrived is parked, not welded down: when someone still driving cannot get
past it, it steps aside. The engine does this too, and without it a tank that has finished
@@ -678,6 +867,7 @@ def yield_for(units: Sequence[Unit], grid: Grid, mover: Unit, hx: float, hy: flo
def step_units(units: Sequence[Unit], grid: Grid, *, traffic: TrafficModel, now: float) -> None:
+ traffic.jam.decay(int(now))
for unit in units:
if unit.has_arrived:
continue
@@ -701,11 +891,18 @@ def step_units(units: Sequence[Unit], grid: Grid, *, traffic: TrafficModel, now:
traffic.usage.release_before(unit.id, done)
traffic.reservations.release_before(unit.id, now)
continue
+ # sideways first: a unit that has been stuck behind slower traffic for a few frames looks
+ # for a lane beside it, and only files in behind him when there is no lane to take
+ ax, ay = dx, dy
+ if LANE_CHANGE:
+ update_lane(grid, units, unit, dx / distance, dy / distance)
+ if unit.lane_frames > 0:
+ ax, ay = dx + unit.lane_dx, dy + unit.lane_dy
# slow down behind whoever is in front, and only sidestep if that is not enough
has_moved = False
for angle, speed in SWERVE_ATTEMPTS:
cos_angle, sin_angle = math.cos(angle), math.sin(angle)
- rx, ry = dx * cos_angle - dy * sin_angle, dx * sin_angle + dy * cos_angle
+ rx, ry = ax * cos_angle - ay * sin_angle, ax * sin_angle + ay * cos_angle
turned_length = math.hypot(rx, ry)
nx = unit.x + rx / turned_length * UNIT_SPEED * speed
ny = unit.y + ry / turned_length * UNIT_SPEED * speed
@@ -715,10 +912,16 @@ def step_units(units: Sequence[Unit], grid: Grid, *, traffic: TrafficModel, now:
unit.stuck_run = 0 if is_closing else unit.stuck_run + 1
if angle or speed < 1.0:
unit.blocked_frames += 1
+ unit.blocked_run += 1
+ traffic.jam.note(cell_of(unit.x, unit.y))
+ else:
+ unit.blocked_run = 0
break
if not has_moved:
unit.blocked_frames += 1
+ unit.blocked_run += 1
unit.stuck_run += 1
+ traffic.jam.note(cell_of(unit.x, unit.y))
yield_for(units, grid, unit, dx / distance, dy / distance)
resolve_overlaps(units, grid)
@@ -748,12 +951,27 @@ def repath_stuck(grid: Grid, units: Sequence[Unit], *, traffic: TrafficModel, no
unit.index = len(unit.path)
unit.stuck_run = 0
continue
- cells, _ = astar(grid, cell_of(unit.x, unit.y), cell_of(*unit.goal),
- pricing=traffic.pricing_for(unit.id, now))
+ start_cell = cell_of(unit.x, unit.y)
+ # what the jam map is charging this search, recorded before the search so the route can be
+ # checked against it: the ground within reach that somebody is stuck on right now
+ hot = {cell for cell, stamp in traffic.jam.jam.items()
+ if stamp > PATH_JAM_FLOOR
+ and abs(cell[0] - start_cell[0]) < PATH_JAM_RANGE
+ and abs(cell[1] - start_cell[1]) < PATH_JAM_RANGE}
+ cells, _ = astar(grid, start_cell, cell_of(*unit.goal),
+ pricing=traffic.repath_pricing(unit.id, now))
unit.stuck_run = 0
unit.repaths += 1
if not cells:
continue
+ # the exit condition, counted, as a funnel: repaths that had jammed ground in front of them
+ # at all, and then the ones whose new route does not drive over any of it. The two numbers
+ # answer different questions - the first says whether the cost ever fires, the second
+ # whether it changes anything when it does.
+ if hot:
+ unit.jam_priced += 1
+ if not hot.intersection(cells):
+ unit.jam_detours += 1
points = [world_of(*cell) for cell in cells[1:]] or [unit.goal]
points[-1] = unit.goal
points, unit.rays = simplify_raycast(grid, unit.pos, points, radius=unit.radius,
@@ -1018,6 +1236,10 @@ class Measurement:
stuck: int = 0
expansions: float = 0.0
repaths: float = 0.0
+ lanes: float = 0.0
+ jam_peak: float = 0.0 # most cells jammed at once, whether or not the cost is charged
+ jam_priced: float = 0.0 # repaths with jammed ground in front of them ...
+ jam_detours: float = 0.0 # ... and the ones that came back avoiding it
def average_over(self, seeds: int, unit_count: int) -> None:
"""`stuck` is a count of units and stays whole; everything else is per seed, and the path
@@ -1031,18 +1253,23 @@ class Measurement:
self.crossings /= divisor
self.expansions /= divisor
self.repaths /= divisor
+ self.lanes /= divisor
+ self.jam_peak /= divisor
+ self.jam_priced /= divisor
+ self.jam_detours /= divisor
def measure(map_kind: str, unit_count: int, seeds: int, mode: str, *,
is_congestion_charged: bool, is_crossing_charged: bool,
- scenario: str) -> Measurement:
+ scenario: str, is_jam_charged: bool = True) -> Measurement:
"""The scenario's orders, played out, averaged over `seeds` maps."""
total = Measurement()
for seed in range(seeds):
grid = make_map(map_kind, seed=seed)
traffic = TrafficModel(UsageMap(), ReservationMap(),
is_congestion_charged=is_congestion_charged,
- is_crossing_charged=is_crossing_charged)
+ is_crossing_charged=is_crossing_charged,
+ is_jam_charged=is_jam_charged)
units, orders = build_scenario(grid, unit_count, scenario)
stats = OrderStats()
planner = order_corridor if mode == "corridor" else order_individual
@@ -1067,19 +1294,26 @@ def measure(map_kind: str, unit_count: int, seeds: int, mode: str, *,
total.stuck += sum(1 for unit in units if not unit.has_arrived)
total.expansions += stats.expansions
total.repaths += sum(unit.repaths for unit in units)
+ total.lanes += sum(unit.lane_changes for unit in units)
+ total.jam_peak += traffic.jam.peak
+ total.jam_priced += sum(unit.jam_priced for unit in units)
+ total.jam_detours += sum(unit.jam_detours for unit in units)
total.average_over(seeds, unit_count)
return total
def print_table_head() -> None:
- print(f"{'mode':<9} {'cost/cap/x':<11} {'waypts':>8} {'length':>8} {'frames':>8} "
- f"{'blocked':>9} {'overlap':>8} {'cross':>6} {'stuck':>7} {'cells':>8}")
+ print(f"{'mode':<9} {'lane':<5} {'jam':<4} {'cost/cap/x':<11} {'waypts':>8} {'length':>8} "
+ f"{'frames':>8} {'blocked':>9} {'overlap':>8} {'cross':>6} {'stuck':>7} {'cells':>8} "
+ f"{'lanes':>6} {'jamcell':>8} {'priced':>7} {'round':>6}")
-def print_row(mode: str, label: str, result: Measurement) -> None:
- print(f"{mode:<9} {label:<11} {result.waypoints:>8.1f} {result.length:>8.0f} "
+def print_row(mode: str, lane: str, jam: str, label: str, result: Measurement) -> None:
+ print(f"{mode:<9} {lane:<5} {jam:<4} {label:<11} {result.waypoints:>8.1f} {result.length:>8.0f} "
f"{result.frames:>8.0f} {result.blocked:>9.0f} {result.overlap:>8.0f} "
- f"{result.crossings:>6.0f} {result.stuck:>7d} {result.expansions:>8.0f}")
+ f"{result.crossings:>6.0f} {result.stuck:>7d} {result.expansions:>8.0f} "
+ f"{result.lanes:>6.0f} {result.jam_peak:>8.0f} {result.jam_priced:>7.1f} "
+ f"{result.jam_detours:>6.1f}")
@contextmanager
@@ -1100,6 +1334,19 @@ def tuning(*, congestion_cost: int, congestion_cap: int, crossing_cost: int,
PATH_CROSSING_WINDOW) = before
+@contextmanager
+def lane_changing(is_on: bool):
+ """Same idea as tuning(): the reflex is read inside the step loop, so a row turns it on for the
+ length of its own measurement and hands it back."""
+ global LANE_CHANGE
+ before = LANE_CHANGE
+ LANE_CHANGE = is_on
+ try:
+ yield
+ finally:
+ LANE_CHANGE = before
+
+
class SweepPoint(NamedTuple):
"""One row of --sweep. A crossing cost of 0 is the time dimension off."""
cost: int
@@ -1127,21 +1374,31 @@ def run_headless(args: argparse.Namespace, sweep: Sequence[SweepPoint]) -> None:
print(f"map {args.map} scenario {args.scenario} units {args.units} "
f"seeds {args.headless} window {args.window} frames")
print_table_head()
+ lane_settings = (False, True) if args.lanes == "both" else (args.lanes == "on",)
+ jam_settings = (False, True) if args.jam == "both" else (args.jam == "on",)
for mode in MODES:
- with tuning(congestion_cost=args.cost, congestion_cap=args.cap, crossing_cost=args.cross,
- crossing_window=args.window):
- print_row(mode, "off",
- measure(args.map, args.units, args.headless, mode,
- is_congestion_charged=False, is_crossing_charged=False,
- scenario=args.scenario))
- for point in sweep:
- with tuning(congestion_cost=point.cost, congestion_cap=point.cap,
- crossing_cost=point.crossing or args.cross, crossing_window=args.window):
- print_row(mode, f"{point.cost}/{point.cap}/{point.crossing}",
- measure(args.map, args.units, args.headless, mode,
- is_congestion_charged=True,
- is_crossing_charged=point.crossing > 0,
- scenario=args.scenario))
+ for is_lane_changing in lane_settings:
+ lane = "on" if is_lane_changing else "off"
+ for is_jam_charged in jam_settings:
+ jam = "on" if is_jam_charged else "off"
+ with lane_changing(is_lane_changing):
+ with tuning(congestion_cost=args.cost, congestion_cap=args.cap,
+ crossing_cost=args.cross, crossing_window=args.window):
+ print_row(mode, lane, jam, "off",
+ measure(args.map, args.units, args.headless, mode,
+ is_congestion_charged=False, is_crossing_charged=False,
+ is_jam_charged=is_jam_charged, scenario=args.scenario))
+ for point in sweep:
+ with tuning(congestion_cost=point.cost, congestion_cap=point.cap,
+ crossing_cost=point.crossing or args.cross,
+ crossing_window=args.window):
+ print_row(mode, lane, jam,
+ f"{point.cost}/{point.cap}/{point.crossing}",
+ measure(args.map, args.units, args.headless, mode,
+ is_congestion_charged=True,
+ is_crossing_charged=point.crossing > 0,
+ is_jam_charged=is_jam_charged,
+ scenario=args.scenario))
class Simulation:
@@ -1211,6 +1468,7 @@ RAY_BAD: Colour = (220, 90, 90)
HEAT: Colour = (200, 120, 60)
HEAT_FLOOR: Colour = (50, 28, 24) # an unused cell is still darker than the walls
HEAT_GAIN: tuple[float, float, float] = (0.8, 0.7, 0.5) # warm, so a busy cell reads as orange
+JAM_COL: Colour = (150, 60, 150) # where units are stuck, not where they plan to drive: not orange
HUD_TEXT: Colour = (200, 205, 215)
@@ -1233,6 +1491,7 @@ class Renderer:
self.font = pygame.font.SysFont("consolas", HUD_FONT_SIZE)
self.ray_detail = RayDetail.SELECTED
self.show_heat = False
+ self.show_jam = True # on by default: it is empty until something actually jams
def close(self) -> None:
pygame.quit()
@@ -1249,6 +1508,8 @@ class Renderer:
self._draw_terrain(sim.grid)
if self.show_heat:
self._draw_heat(sim)
+ if self.show_jam:
+ self._draw_jam(sim)
self._draw_crossings(sim)
self._draw_corridor(sim.stats)
if self.ray_detail is not RayDetail.OFF:
@@ -1275,6 +1536,18 @@ class Renderer:
int(HEAT_FLOOR[2] + HEAT[2] * level * HEAT_GAIN[2]))
pygame.draw.rect(self.screen, colour, self._cell_rect(cx, cy))
+ def _draw_jam(self, sim: Simulation) -> None:
+ """Ground units are stuck on, drawn only once a cell is over the floor - a map speckled
+ with stamps of 1 is a map with no jam on it and outlining every one of them says
+ nothing. This is the cost a repath is paying, made visible."""
+ for (cx, cy), stamp in sim.traffic.jam.jam.items():
+ if stamp <= PATH_JAM_FLOOR or not sim.grid.in_bounds(cx, cy):
+ continue
+ level = min(stamp - PATH_JAM_FLOOR, PATH_JAM_MAX_CHARGED) / PATH_JAM_MAX_CHARGED
+ pygame.draw.rect(self.screen, (int(JAM_COL[0] * level), int(JAM_COL[1] * level),
+ int(JAM_COL[2] * level)),
+ self._cell_rect(cx, cy))
+
def _draw_crossings(self, sim: Simulation) -> None:
# where two units still plan to be at the same moment - what the crossing cost buys out
for cx, cy in find_crossing_cells(sim.traffic.reservations):
@@ -1327,16 +1600,19 @@ class Renderer:
moving = sum(1 for unit in sim.units if not unit.has_arrived)
congestion = str(PATH_CONGESTION_COST) if sim.traffic.is_congestion_charged else "off"
crossing = str(PATH_CROSSING_COST) if sim.traffic.is_crossing_charged else "off"
+ jam = str(PATH_JAM_COST) if sim.traffic.is_jam_charged else "off"
heat = "on" if self.show_heat else "off"
lines = [
f"mode {sim.mode:<9} congestion {congestion:<3} crossing {crossing:<3} "
- f"rays {self.ray_detail.name.lower():<8} heat {heat:<3} "
- f"[1][2] [c][t][r][p] [n]map [tab]replan",
+ f"jam {jam:<3} rays {self.ray_detail.name.lower():<8} heat {heat:<3} "
+ f"[1][2] [c][t][j][k][r][p] [n]map [tab]replan",
f"corridor width {sim.stats.diameter} cells searches {sim.stats.searches} "
f"cell expansions {sim.stats.expansions} "
f"avg waypoints/unit {sim.stats.avg_waypoints:.1f}",
f"units {len(sim.units)} still moving {moving} blocked unit-frames {blocked} "
f"repaths {sum(unit.repaths for unit in sim.units)} "
+ f"jammed cells {sim.traffic.jam.blocking_cells} "
+ f"(routed round {sum(unit.jam_detours for unit in sim.units)}) "
f"crossings {count_planned_crossings(sim.traffic.reservations)} now {sim.frames} "
f"{'; '.join(sim.stats.notes[:HUD_NOTES_SHOWN])}",
]
@@ -1394,6 +1670,10 @@ class Lab:
self.view.ray_detail = RayDetail((self.view.ray_detail + 1) % len(RayDetail))
elif key == pygame.K_p:
self.view.show_heat = not self.view.show_heat
+ elif key == pygame.K_j:
+ self.sim.traffic.is_jam_charged = not self.sim.traffic.is_jam_charged
+ elif key == pygame.K_k:
+ self.view.show_jam = not self.view.show_jam
elif key == pygame.K_SPACE:
self.is_paused = not self.is_paused
elif key == pygame.K_n:
@@ -1446,13 +1726,18 @@ def main() -> None:
help="frames either side of an arrival that still count as the same moment")
parser.add_argument("--sweep", default="5/4/0,20/4/0,20/4/60,20/4/120",
help="headless only: cost/cap/crossing triples to compare (crossing 0 = off)")
+ parser.add_argument("--lanes", choices=("off", "on", "both"), default="off",
+ help="overtake instead of queueing; 'both' measures it against itself")
+ parser.add_argument("--jam", choices=("off", "on", "both"), default="on",
+ help="charge a repath for ground somebody is stuck on; 'both' compares")
args = parser.parse_args()
sweep = parse_sweep(args.sweep)
if args.headless:
run_headless(args, sweep)
return
- with tuning(congestion_cost=args.cost, congestion_cap=args.cap, crossing_cost=args.cross,
- crossing_window=args.window), Lab(args) as lab:
+ with lane_changing(args.lanes != "off"), \
+ tuning(congestion_cost=args.cost, congestion_cap=args.cap, crossing_cost=args.cross,
+ crossing_window=args.window), Lab(args) as lab:
lab.run()
diff --git a/Tools/PathLab/test_pathlab.py b/Tools/PathLab/test_pathlab.py
index e7819563f..cb17f1926 100644
--- a/Tools/PathLab/test_pathlab.py
+++ b/Tools/PathLab/test_pathlab.py
@@ -13,10 +13,12 @@ import unittest
import pathlab
from pathlab import (CELL, COST_DIAGONAL, COST_ORTHOGONAL, PATH_CONGESTION_COST,
PATH_CONGESTION_MAX_PATHS, PATH_CROSSING_COST, PATH_CROSSING_MAX,
- Grid, OrderStats, ReservationMap, TrafficModel, UsageMap,
+ PATH_JAM_COST, PATH_JAM_DECAY_FRAMES, PATH_JAM_FLOOR, PATH_JAM_MAX,
+ PATH_JAM_MAX_CHARGED, PATH_JAM_RANGE,
+ Grid, JamMap, OrderStats, ReservationMap, TrafficModel, UsageMap,
astar, build_scenario, cell_of, compute_centroid, count_planned_crossings,
find_crossing_cells, make_map, order_corridor, order_individual, parse_sweep,
- price_congestion, price_crossing, simplify_raycast, spawn_block,
+ price_congestion, price_crossing, price_jam, simplify_raycast, spawn_block,
track_reservations, tuning, world_of)
@@ -113,6 +115,73 @@ class PricingTests(unittest.TestCase):
self.assertIn((10, 10), plain)
self.assertFalse(set(priced) & set(claimed))
+ def test_jam_costs_nothing_until_it_has_lasted(self):
+ """The floor is the whole design: a unit pausing for a frame stamps 1 or 2 and that is
+ traffic. Only ground several units have been stuck on gets past the floor."""
+ self.assertEqual(price_jam(0), 0)
+ self.assertEqual(price_jam(PATH_JAM_FLOOR), 0)
+ self.assertEqual(price_jam(PATH_JAM_FLOOR + 1), PATH_JAM_COST)
+ self.assertEqual(price_jam(PATH_JAM_FLOOR + PATH_JAM_MAX_CHARGED + 9),
+ PATH_JAM_MAX_CHARGED * PATH_JAM_COST)
+
+ def test_a_jammed_doorway_is_worth_going_round_and_a_busy_one_is_not(self):
+ """The same map twice: stamps below the floor leave the straight line alone, and stamps
+ above it move the route off it. Without both halves this cost fires on traffic."""
+ grid = corridor_grid()
+ door = (10, 10)
+ jam = JamMap()
+ for _ in range(PATH_JAM_FLOOR):
+ jam.note(door)
+ pricing = pathlab.PathPricing(jam=jam)
+ # a wall with one gap: there is no way round, so the route runs through it either way
+ self.assertIn(door, astar(grid, (2, 10), (18, 10), pricing=pricing)[0])
+
+ # now on open ground, where there is somewhere else to go
+ grid = open_grid()
+ jam = JamMap()
+ for _ in range(PATH_JAM_FLOOR):
+ jam.note(door)
+ plain = astar(grid, (2, 10), (18, 10), pricing=pathlab.PathPricing(jam=jam))[0]
+ self.assertIn(door, plain) # still traffic: at the floor, nothing is charged
+ for _ in range(PATH_JAM_MAX):
+ jam.note(door)
+ priced = astar(grid, (2, 10), (18, 10), pricing=pathlab.PathPricing(jam=jam))[0]
+ self.assertNotIn(door, priced)
+
+ def test_the_jam_penalty_is_only_read_near_the_start(self):
+ """The engine charges it within PATH_QUEUE_RANGE of where the repath began, because it is
+ the unit leaving the jam that pays, not every search that crosses the map later."""
+ grid = open_grid(60)
+ far = (2 + PATH_JAM_RANGE + 4, 10)
+ jam = JamMap()
+ for _ in range(PATH_JAM_MAX):
+ jam.note(far)
+ route = astar(grid, (2, 10), (50, 10), pricing=pathlab.PathPricing(jam=jam))[0]
+ self.assertIn(far, route) # out of range: not priced, so not avoided
+
+ def test_the_jam_map_forgets_on_the_frame_number(self):
+ """The decay runs off the frame it is given rather than a call count, which is what makes
+ it the same on two machines - and what makes two sweep rows comparable here."""
+ jam = JamMap()
+ cell = (4, 4)
+ for _ in range(PATH_JAM_MAX + 5):
+ jam.note(cell)
+ self.assertEqual(jam.at(cell), PATH_JAM_MAX) # the stamp saturates
+
+ jam.decay(1) # too soon: nothing moves
+ jam.decay(PATH_JAM_DECAY_FRAMES - 1)
+ self.assertEqual(jam.at(cell), PATH_JAM_MAX)
+
+ jam.decay(PATH_JAM_DECAY_FRAMES)
+ self.assertEqual(jam.at(cell), PATH_JAM_MAX - 1)
+
+ # and it empties rather than keeping zeroes about, so a quiet map costs nothing to carry
+ for frame in range(PATH_JAM_DECAY_FRAMES, PATH_JAM_DECAY_FRAMES * (PATH_JAM_MAX + 2),
+ PATH_JAM_DECAY_FRAMES):
+ jam.decay(frame)
+ self.assertEqual(jam.jam, {})
+ self.assertEqual(jam.at(cell), 0)
+
def test_tuning_hands_the_constants_back(self):
before = (pathlab.PATH_CONGESTION_COST, pathlab.PATH_CONGESTION_MAX_PATHS,
pathlab.PATH_CROSSING_COST, pathlab.PATH_CROSSING_WINDOW)