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(gameengine): rescue any unit that wants to move and cannot

Olcay Seygan5b3a0971ecfb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5bf8b25a8..5eea487ba 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -457,6 +457,26 @@ found and fixed — EA's own, not port damage.**
- A transport told to load into something it cannot enter - or into itself, which happens when it is part of the group you gave the order to - ignores the order instead of flying over and hovering beside it.
- A pilot ejecting from a wreck no longer plays a promotion sound and animation somewhere out in the map.
- A sound finishing does not take the game with it. Every sound carries a description of itself, and that description can be gone by the time the sound ends - it is dropped when the sound is renamed, cleared by hand when what it points at is about to be deleted, and absent on a sound that was queued to repeat after a delay. The 2003 code checked for that in two places and then read straight through it in fifteen others, one of which is where every finished sound goes. It crashed mid-match with a stack that is all audio and names nothing that caused it. A sound with no description is now simply not music and not speech, which is what all fifteen questions were asking; the channel it was using is still handed back, because losing one leaks a voice for the rest of the match and enough of them go quiet.
+- A guard posted at a tunnel network no longer takes the game down when its target stops existing.
+ EA's own copy of that function, the one for units guarding anywhere else, tests for it on its first
+ line; the tunnel copy read straight through the missing pointer and crashed mid-match.
+- Alt-tabbing out no longer kills the game if something needs loading while you are away. The
+ simulation keeps running while the window is not drawing, so a script can drop reinforcements in,
+ and the new unit's model asks for a texture that cannot be made because there is no graphics device
+ to make it on. The failure came back as a success with nothing attached, and the next line of code
+ used it. Two lines apart in the log: "Are we ALT-Tabbed out?" and the crash. A load that produces
+ nothing is now a failed load, which the game has always known how to handle, and the texture is
+ rebuilt when the device comes back.
+- A bad line in a data file says which line. The startup error for an unparseable block named the
+ line the block began on, which is almost never the line that is wrong, so the answer was "one of
+ these nine fields, good luck". It now also reports the line it got to and what was on it.
+- A crash inside somebody else's code now says whose. Every line of the stack that is not ours used
+ to read "Unknown" and a bare address, so a fault inside a graphics driver looked exactly like a
+ fault inside the game. Those lines now carry the file the address belongs to and the offset into
+ it, which is the difference between a report that can be acted on and one that cannot.
+- The game says so in the log when the graphics device is lost, which is what happens when you
+ alt-tab out. The recovery after that is the riskiest thing the renderer does, and until now it
+ left no trace at all in a shipping build.
- Something going wrong now writes a readable crash report.
## Units take corners wide, and drive round a jam instead of into it
@@ -508,6 +528,85 @@ found and fixed — EA's own, not port damage.**
behind another unit fell 31%. Over six 4v4 battles, where every unit is on one of two fronts, it
fell 38%, units left properly stuck fell by half, and the worst single frame of a match went from
30.6 milliseconds to 9.9.
+- A corner now costs what the vehicle takes to turn it. Every turn used to be priced the same,
+ whether the thing making it pivots on the spot or needs a second and a half to swing a hull round,
+ and the very first turn of a route was free: the one out of where the unit is standing at the
+ moment you give the order. That is why a column ordered forward would sometimes set off by turning
+ round, and why a tank was handed corners it had to stop, reverse and grind through. A turn is
+ charged at what that hull actually takes now, and the first step is charged against the way the
+ unit is already pointing. Twelve matches on the same twelve maps: time spent standing behind
+ another unit down 38%, time spent properly wedged rather than merely queuing down from 11.3 to 0.3
+ unit-frames a match, and the routing itself 20% cheaper to work out, because a route a vehicle can
+ drive is a route it does not come back and ask to have redone.
+- A group crossing open ground no longer arrives twenty abreast. Measuring the road is what stopped
+ a dozen tanks driving down a two-lane street in single file, and with nothing capping it the same
+ measurement turned an open field into a firing line wider than anything the group was walking
+ into. Five lanes is the ceiling: still a front on open ground, still narrow enough to go through a
+ base entrance without the whole group renumbering itself sideways at the gate.
+- Attack-move spreads out the way a plain move does. It is the order that expects to be interrupted,
+ and it was the one order that handed nobody a place in the formation, so a group told to fight its
+ way across the map went in single file while the same group told to walk there arrived as a front.
+- A group that has to find a new way round keeps its shape. Any new route used to drop a unit out of
+ its formation permanently: it held its place until the first thing that made it re-plan, and drove
+ down the middle of the road on its own from there on. Arriving is what ends a formation now.
+- A unit stuck behind a unit that is never going to move asks for a different route. It tries both
+ sides of the blockage first, and the outside of the whole pack, and where the road genuinely has no
+ room it now stops steering around the problem and plans another way there. The squares the jam is
+ standing on are already expensive by then, so the new route goes round it. A unit that has been
+ getting nowhere for a third of a second also used to stop looking for a way past at exactly the
+ moment it needed one; only the politeness stops now, and the looking carries on.
+- Backing out of a wedge asks the queue behind to make room first, rather than reversing into it, and
+ the unit plans a fresh route once it is out instead of driving back into the hole it just left.
+- Units keep their distance from each other and not only from whoever is exactly alongside them. A
+ neighbour half a body ahead and half a body over, closing, is the collision nothing used to see
+ coming, and it is now worth a foot of road before it is worth a stop.
+- Units no longer stop dead for traffic that was never going to hit them. Something crossing your
+ path at an angle is not something sitting in your lane, and for one build it was priced as though
+ it were: the brake reads how fast the obstruction is travelling along your route, which for a unit
+ crossing it is nothing at all, so a jeep driving across a road brought the column on it to a
+ standstill. Crossing traffic now costs a lift off the throttle, and only a unit genuinely in the
+ way can ask for a stop.
+- A unit turning on the spot is not a unit that is stuck. A heavy hull takes two seconds to come
+ about and covers no ground doing it, which the jam detector counted as being wedged, so tanks
+ halfway through a turn decided they were trapped and reversed out of a jam that did not exist.
+- A unit aims at a point it can actually drive to. The steering point sits a couple of squares
+ ahead and off to the side of the route, and it used to be checked against the width of the road
+ where the unit is standing and the width where it is aiming, but not against the gap in between.
+ Both ends being wide is not the same as the middle being wide, and the straight line between them
+ went through the corner of the building the route had gone round. That is what catching on
+ scenery looked like from the inside.
+- Those three together, over eight battles on the same eight maps with forty units moved as one
+ group every twenty seconds: time spent standing behind another unit down 7%, and no stutter added
+ to the worst frames of a match. One map of the eight got worse, which is written down rather than
+ averaged away.
+- A unit that has stopped and wants to move is never left to it. The game now checks, once a frame
+ and for every unit under orders, whether it is actually getting anywhere, and when the answer has
+ been no for a second and a half it does something about it: first a fresh route from where the
+ unit is standing, then telling whoever is crowding it to move and letting it push through, then
+ backing the body out to open ground. If it is still stuck after all that, the whole sequence runs
+ again rather than giving up. None of this waits for a collision, which is what the old machinery
+ needed and what a unit stuck on scenery never produces.
+- This is not a promise that units never get stuck. A unit walled in by buildings has nowhere to be
+ sent, and no amount of steering makes ground that is not there. What it is is a promise that
+ nothing is ignored: over twenty test battles, the longest any single unit spent wanting to move
+ and not moving was 2.9 seconds in ordinary play, and 3.4 in a battle deliberately set up to jam.
+ That number is measured at the end of every test run, so if it ever grows the run says so.
+- Units that go back and forth on the spot are counted now, which is the first step to fixing them.
+ A unit shuffling beside a building is moving on every single frame, so nothing in the game noticed
+ it: the jam detector wants a unit that has stopped. Ground covered against ground gained over three
+ seconds catches it instead, and about fifteen units a battle turn out to do it. Nothing is done
+ about it yet on purpose. Three cures were tried and measured, and all three cost more than they
+ saved: backing the unit out made everything a third worse, and forbidding it to change its mind
+ for three seconds made it queue instead. The count ships so the next attempt has a number to beat.
+- The plain version of the same question, asked of orders rather than of units: forty units sent
+ across the map at once, checked twenty seconds later, 525 orders over eight maps. Of the units
+ still carrying that order, one had not got going at all. Not one in a hundred: one. That is the
+ figure this work is held to from now on, and every test run prints it along with the reason each
+ stalled unit gave. Over those eight battles, no unit anywhere failed to move because no route
+ could be found for it, and none was jammed against another unit for a whole twenty seconds.
+- Jams in the heavy test fell 14% against the build from before all of this, and in ordinary play
+ the whole of it costs nothing measurable: same number of routes planned, same time spent planning
+ them.
## Long orders stopped hitching
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/CrowdModel.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/CrowdModel.h
index 4dce260c0..60cdf5ceb 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/CrowdModel.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/CrowdModel.h
@@ -71,9 +71,23 @@ enum
CROWD_BRIDGE_SEAL = 6,
/// how far ahead of itself a unit steers, in cells, before its own body length is added
- CROWD_LOOKAHEAD_CELLS = 2
+ CROWD_LOOKAHEAD_CELLS = 2,
+
+ /* The most lanes a group is ever laid out in, whatever the ground says. Fitting the count to
+ the band every frame took the old fixed cap off, and on open country that is a group of
+ twenty arriving as a line twenty abreast: the front is wider than anything it is walking
+ into, the flanks take the whole map's worth of fire before the middle is in range, and a
+ rank that wide cannot get through the first gap without renumbering itself completely.
+ Five is the widest that still fits through a base entrance without a re-fit, so the group
+ keeps its shape from the field to the door. */
+ CROWD_MAX_LANES = 5
};
+/** How many lanes to lay across `span` of drivable ground, `spacing` apart: what the ground holds,
+ capped at CROWD_MAX_LANES, and never more lanes than there are bodies to put in them
+ (`members` of 0 means the caller counts them itself). */
+extern Int Crowd_laneCount( Real span, Real spacing, Int members );
+
/**
* A route, sampled, with the width of the drivable ground either side of every sample.
*
@@ -132,9 +146,21 @@ public:
/// `lat`, cut down to what the ground allows at distance `along`
Real clampLatAt( Real along, Real lat ) const;
+ /** `lat`, cut down to the tightest the ground gets anywhere between `from` and `to`.
+
+ Clamping at the two ends only is what lets a unit aim across a corner: both the point it is
+ standing on and the point it is steering at are comfortably inside the band, and the pinch
+ between them is not consulted by either. The unit then drives the straight line between
+ them, which goes through the building on the corner. This is the cheap version of a line
+ of sight test - no cell lookups, just the samples that were measured when the band was
+ built. */
+ Real clampLatNarrowest( Real from, Real to, Real lat ) const;
+
/** Build from a plain polyline, with the same width everywhere: for tests, which have no Object,
- no pathfinder and no ground to probe. `layers`, when given, is one entry per point. */
- void buildForTest( const Coord3D *pts, Int count, Real halfWidth, const PathfindLayerEnum *layers = NULL );
+ no pathfinder and no ground to probe. `layers`, when given, is one entry per point, and so
+ is `halfWidths`, which overrides the single width where a test needs a pinch in the road. */
+ void buildForTest( const Coord3D *pts, Int count, Real halfWidth,
+ const PathfindLayerEnum *layers = NULL, const Real *halfWidths = NULL );
/// close the band on every bridge deck and on the ground either side of one
void sealBridges( void );
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
index dad0e5c79..2fee1a578 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
@@ -479,6 +479,8 @@ public:
Bool isQuickPathAvailable( const Coord3D *destination ) const; ///< does a path (using quick pathfind) exist between us and the destination
Int getNumFramesBlocked(void) const {return m_blockedFrames;}
Bool isBlockedAndStuck(void) const {return m_isBlockedAndStuck;}
+ /// consecutive frames this unit has wanted to move without moving; see updateProgress
+ Int getNoProgressFrames(void) const {return m_noProgress;}
/* Lanes. The route says where to go; the lane fraction says where across its width this unit
rides while it goes there - 0 hard right, 1 hard left, 0.5 the centre line, which is where
@@ -515,6 +517,13 @@ public:
at the next one. Only read under -crowd. */
void setPendingCrowdLane( Int idx, Int of, Real spacing )
{ m_crowdLaneIdx = idx; m_crowdLaneOf = of; m_crowdLaneSpace = spacing; }
+
+ /** Out of the march. The slot deliberately outlives a route - a group that repaths halfway
+ across a map keeps its formation - so an order that hands out no lanes has to say so, or a
+ unit sent off on its own would still be riding the lane it was given as part of a group
+ that has since dispersed. */
+ void clearCrowdLane( void )
+ { m_crowdLaneIdx = 0; m_crowdLaneOf = 0; m_crowdLaneSpace = 0.0f; m_hasPendingCrowdLat = FALSE; }
Real getCrowdLat( void ) const { return m_crowdLat; }
const CrowdCorridor *getCrowdCorridor( void ) const { return m_corridor; }
/** Which sample of its own band the unit was beside last frame. Priority between two units is
@@ -751,6 +760,26 @@ private:
/// throw the measured band away; the next frame that needs one measures the new route
void crowdReleaseCorridor( void );
+ /** Is this unit getting anywhere? One test, once a frame, for every unit that is trying to
+ drive somewhere, and the only place m_noProgress is written. */
+ void updateProgress( void );
+
+ /** And what to do when the answer has been no for long enough. A ladder with a rung every
+ second and a half, ending in one that always does something, so no unit can want to move
+ and be ignored for longer than that. The timing itself is `AIUpdate_stuckRung`, which is
+ a free function so a test can hold it to the promise. */
+ void stuckRescue( void );
+
+ /** TRUE when a rescue manoeuvre owns the steering this frame, in which case `goalPos` has been
+ replaced with where the unit is being sent and nothing else may touch it. */
+ Bool rescueSteer( Coord3D& goalPos );
+
+ /// Give up on the current route and ask the move state for a fresh one to the same place.
+ void crowdRepath( void );
+
+ /// Tell whoever is queued right behind us to make room, so we can back out of a jam.
+ void crowdAskBehindToBackOff( const Coord2D& tan );
+
/// TRUE when `other` gets the line and we are the one who has to do something about it
Bool crowdOutranksMe( Object *other ) const;
@@ -820,11 +849,22 @@ private:
Real m_crowdSepSmooth; ///< -crowd: low-passed sideways push from the neighbours.
Real m_crowdAim; ///< -crowd: low-passed direction the steering point is taken in, radians.
Bool m_crowdAimValid; ///< -crowd: FALSE until the filter has something to start from.
- Int m_crowdStuck; ///< -crowd: consecutive frames spent wanting to move and not moving.
- Coord3D m_crowdLastPos; ///< -crowd: where we were last frame, which is how the above is counted.
- Coord3D m_crowdEscape; ///< -crowd: the free ground a wedged unit is backing out to.
- UnsignedInt m_crowdEscapeUntil; ///< -crowd: frame that manoeuvre gives up (0 = not backing out).
- UnsignedInt m_crowdEscapeCool; ///< -crowd: no second one before this frame.
+ /* Being stuck, and getting out of it. None of this is behind -crowd: a unit that has stopped
+ without a collision to show for it is not a crowd problem, it is the problem, and until this
+ was pulled out of the crowd model it was only ever asked about units that happened to have
+ been handed a lane by a group order. */
+ Int m_noProgress; ///< consecutive frames wanting to move, not moving, not turning either.
+ Coord3D m_lastProgressPos; ///< where we were last frame, which is how the above is counted.
+ Real m_lastProgressAngle; ///< and which way we were pointing, because coming about is progress too.
+ /* Dithering: driving a long way and getting nowhere, which the frame by frame test above cannot
+ see because the unit is moving on every one of those frames. */
+ Coord3D m_ditherFrom; ///< where the current window opened.
+ UnsignedInt m_ditherFrame; ///< and when.
+ Real m_ditherTravel; ///< how much ground has actually been covered since, path length not displacement.
+ Int m_rescueStage; ///< how far up the rescue ladder this episode has climbed.
+ Coord3D m_rescueTo; ///< the free ground a wedged unit is backing out to.
+ UnsignedInt m_rescueUntil; ///< frame that manoeuvre gives up (0 = not backing out).
+ UnsignedInt m_rescueCool; ///< no second drastic thing before this frame.
Real m_bumpSpeedLimit; ///< Max speed after bumping a unit.
UnsignedInt m_ignoreCollisionsUntil; ///< Timer to cheat if we get stuck.
/**
@@ -904,6 +944,24 @@ private:
Bool m_fixLocoInPostProcess;
};
+/** Which rung of the rescue ladder a unit takes next, given how long it has wanted to move without
+ moving and how far up the ladder this episode has already climbed.
+
+ 0 is "nothing yet", 1 asks for another route, 2 asks the neighbours to move and stops bouncing
+ off them, 3 backs the body out, and -1 says start again from the bottom. It is a free function
+ with no state so the promise it makes can be tested rather than believed: the rungs come in
+ order, none is skipped, and the ladder never stops offering one. */
+extern Int AIUpdate_stuckRung( Int noProgressFrames, Int stageDone );
+
+/** Has this unit driven a long way and got nowhere?
+
+ `travelled` is the ground actually covered over the window, `net` the straight line from where
+ it started to where it ended, and `bodySize` the unit's own diameter. A unit going somewhere
+ has a net close to its travel; one shuffling back and forth beside a building has a travel of
+ several body lengths and a net of almost nothing. The body-size floor is what keeps a unit
+ that is simply slow, or stopped, out of it: those are the other test's business. */
+extern Bool AIUpdate_isDithering( Real net, Real travelled, Real bodySize );
+
//------------------------------------------------------------------------------------------------------------
// Inlines
//
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
index e19169146..7d99a5d36 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
@@ -1410,6 +1410,8 @@ static void updateHeadlessRun( void )
Pathfinder::resetMatchProfile();
// and -tracemove with no id picks its unit out of the match, not out of the shell map
AIUpdate_resetMoveTrace();
+ extern void GroupDrill_reset( void );
+ GroupDrill_reset();
}
const UnsignedInt frame = TheGameLogic->getFrame();
@@ -1472,6 +1474,16 @@ static void updateHeadlessRun( void )
// reduced the traffic jams it was supposed to reduce.
DEBUG_LOG(("HEADLESS PATHFIND: %s\n", Pathfinder::getMatchProfileReport()));
+ /* And under -groupdrill, the question the blocked counters cannot answer: of the units that were
+ marched across the map, how many were still going when the next order came, and how many had
+ stopped and stayed stopped. Time spent in traffic is one thing; never getting there at all
+ is the thing anybody actually complains about. */
+ if (TheGlobalData->m_groupDrill > 0)
+ {
+ extern const char *GroupDrill_report( void );
+ DEBUG_LOG(("HEADLESS DRILL: %s\n", GroupDrill_report()));
+ }
+
/* Stability, which is a different question from speed and is answered by the tail rather than
by the average. These two lines are the ones a stutter complaint is argued with. */
reportFrameTimeStats();
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
index fe30a88a7..ccb234ef7 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
@@ -45,6 +45,7 @@
#include "GameLogic/AI.h"
#include "GameLogic/AIPathfind.h"
+#include "GameLogic/CrowdModel.h"
#include "GameLogic/Locomotor.h"
#include "GameLogic/Module/AIUpdate.h"
#include "GameLogic/Module/BodyModule.h"
@@ -1618,10 +1619,23 @@ static Int crowdRoadLanes( Object *probe, const Coord3D& center, const Coord2D&
*bias = (leftRoom - rightRoom) * 0.5f;
- // centres, so a span exactly one spacing wide is two lanes and a span of nothing is still one
- Int lanes = (Int)((leftRoom + rightRoom) / spacing) + 1;
- if (lanes < 1) lanes = 1;
- return lanes;
+ // the cap is CROWD_MAX_LANES and it is not the ground's opinion: see the comment on it
+ return Crowd_laneCount( leftRoom + rightRoom, spacing, 0 );
+}
+
+/** Take a member out of the crowd march. A slot survives a repath - that is the whole point of it,
+ or a group that repaths mid-march loses its formation for the rest of the trip - so the only
+ thing that ends one is the next order, and this is where an order that hands out no lanes says
+ so. Without it a unit ordered somewhere on its own would still be riding a lane it was given
+ as part of a group that no longer exists. */
+static void crowdClearLanes( std::list<Object *>& members )
+{
+ for (std::list<Object *>::iterator it = members.begin(); it != members.end(); ++it)
+ {
+ AIUpdateInterface *ai = (*it)->getAIUpdateInterface();
+ if (ai != NULL)
+ ai->clearCrowdLane();
+ }
}
/** Hand every member of a group the distance it should sit off the centre of the road, for the
@@ -1635,6 +1649,8 @@ static Int crowdRoadLanes( Object *probe, const Coord3D& center, const Coord2D&
collision rules in AIUpdate::blockedBy - while reporting on the crowd model. */
static void crowdSeedLanes( std::list<Object *>& members, const Coord3D& center, const Coord3D *pos )
{
+ crowdClearLanes( members ); // whatever this order hands out replaces the last one entirely
+
Coord2D dir;
dir.x = pos->x - center.x;
dir.y = pos->y - center.y;
@@ -1898,6 +1914,8 @@ void AIGroup::groupMoveToPosition( const Coord3D *p_posIn, Bool addWaypoint, Com
groupDir.y = pos->y - center.y;
const Coord3D groupCenter = center;
Bool spreadLanes = !TheGlobalData->m_noLanePath && groupDir.length() > 1.0f;
+ if (TheGlobalData->m_crowdModel)
+ crowdClearLanes( m_memberList ); // this order replaces the last one, spread or no spread
if (spreadLanes)
{
groupDir.normalize();
@@ -2632,6 +2650,13 @@ void AIGroup::groupAttackMoveToPosition( const Coord3D *pos, Int maxShotsToFire,
Coord2D max;
getMinMaxAndCenter( &min, &max, &center );
+ /* An attack move is a march that expects to be interrupted, which is exactly the order that
+ wants the crowd model and was not getting it: nothing here handed out a lane, and a unit with
+ no lane is one crowdSteer returns out of on its first line. So a group told to fight its way
+ across a map drove there in single file while the same group told to walk there spread out. */
+ if (TheGlobalData->m_crowdModel)
+ crowdSeedLanes( m_memberList, center, pos );
+
// path the members closest to the goal first; it leaves fewer of them to collide on arrival.
MemoryPoolObjectHolder iterHolder;
SimpleObjectIterator *iter = newInstance(SimpleObjectIterator);
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/CrowdModel.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/CrowdModel.cpp
index c0458c2f7..1f9b0749c 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/CrowdModel.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/CrowdModel.cpp
@@ -358,6 +358,34 @@ void CrowdCorridor::pointAt( Real along, Real lat, Coord3D *out ) const
out->z = a.pos.z + (b.pos.z - a.pos.z) * f;
}
+//-------------------------------------------------------------------------------------------------
+Real CrowdCorridor::clampLatNarrowest( Real from, Real to, Real lat ) const
+{
+ if (to < from)
+ {
+ const Real swap = from;
+ from = to;
+ to = swap;
+ }
+
+ lat = clampLatAt( from, lat );
+ lat = clampLatAt( to, lat );
+
+ // and every whole sample in between, which is where the pinch that neither end can see lives
+ const Int n = (Int)m_samples.size();
+ for (Int k = 0; k < n; k++)
+ {
+ const Sample& s = m_samples[ k ];
+ if (s.along <= from)
+ continue;
+ if (s.along >= to)
+ break;
+ if (lat > s.left) lat = s.left;
+ if (lat < -s.right) lat = -s.right;
+ }
+ return lat;
+}
+
//-------------------------------------------------------------------------------------------------
Real CrowdCorridor::clampLatAt( Real along, Real lat ) const
{
@@ -374,7 +402,8 @@ Real CrowdCorridor::clampLatAt( Real along, Real lat ) const
}
//-------------------------------------------------------------------------------------------------
-void CrowdCorridor::buildForTest( const Coord3D *pts, Int count, Real halfWidth, const PathfindLayerEnum *layers )
+void CrowdCorridor::buildForTest( const Coord3D *pts, Int count, Real halfWidth,
+ const PathfindLayerEnum *layers, const Real *halfWidths )
{
m_samples.clear();
if (pts == NULL || count < 2)
@@ -406,14 +435,31 @@ void CrowdCorridor::buildForTest( const Coord3D *pts, Int count, Real halfWidth,
s.pos = pts[ k ];
s.tan.x = dx;
s.tan.y = dy;
- s.left = halfWidth;
- s.right = halfWidth;
+ s.left = halfWidths ? halfWidths[ k ] : halfWidth;
+ s.right = halfWidths ? halfWidths[ k ] : halfWidth;
s.along = along;
s.layer = layers ? layers[ k ] : LAYER_GROUND;
m_samples.push_back( s );
}
}
+//-------------------------------------------------------------------------------------------------
+Int Crowd_laneCount( Real span, Real spacing, Int members )
+{
+ if (spacing < 0.001f)
+ return 1;
+
+ // centres, so a span exactly one spacing wide is two lanes and a span of nothing is still one
+ Int lanes = (Int)(span / spacing) + 1;
+ if (lanes > CROWD_MAX_LANES)
+ lanes = CROWD_MAX_LANES;
+ if (members > 0 && lanes > members)
+ lanes = members;
+ if (lanes < 1)
+ lanes = 1;
+ return lanes;
+}
+
//-------------------------------------------------------------------------------------------------
Bool Crowd_outranks( const Object *big, const Object *little )
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
index 565c566eb..8475f07a5 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
@@ -325,11 +325,16 @@ AIUpdateInterface::AIUpdateInterface( Thing *thing, const ModuleData* moduleData
m_crowdSepSmooth = 0.0f;
m_crowdAim = 0.0f;
m_crowdAimValid = FALSE;
- m_crowdStuck = 0;
- m_crowdLastPos.zero();
- m_crowdEscape.zero();
- m_crowdEscapeUntil = 0;
- m_crowdEscapeCool = 0;
+ m_noProgress = 0;
+ m_lastProgressPos.zero();
+ m_lastProgressAngle = 0.0f;
+ m_ditherFrom.zero();
+ m_ditherFrame = 0;
+ m_ditherTravel = 0.0f;
+ m_rescueStage = 0;
+ m_rescueTo.zero();
+ m_rescueUntil = 0;
+ m_rescueCool = 0;
m_bumpSpeedLimit = FAST_AS_POSSIBLE;
m_ignoreCollisionsUntil = 0;
m_queueForPathFrame = 0;
@@ -1154,10 +1159,16 @@ UpdateSleepTime AIUpdateInterface::update( void )
// which we just called. thus we should
// never have worry about waking ourselves up when this changes, since
// if it changes the code will always flow thru here anyway. (srj)
- if (m_movementComplete)
+ if (m_movementComplete)
{
setQueueForPathTime(0);
+ /* Arrived, so the march is over. The slot deliberately outlives a route (see
+ crowdReleaseCorridor) and this is the other end of that: without it a unit that finished a
+ group move would still be carrying its place in a formation that has stopped existing, and
+ would ride the lane for that place the next time anything sent it anywhere. */
+ clearCrowdLane();
+
// destroy path
destroyPath();
setLocomotorGoalNone();
@@ -1560,11 +1571,22 @@ static const Real CROWD_SEP_FILTER = 0.13f; ///< how much of a frame's sideways
static const Real CROWD_AIM_CRUISE = 0.23f; ///< how fast the aim follows the route while driving (~7/sec)
static const Real CROWD_AIM_URGENT = 0.67f; ///< and while manoeuvring (~20/sec), where lag is worse than twitch
static const Real CROWD_AIM_DEAD = 0.035f; ///< two degrees: hold the wheel still rather than chase the noise
-static const Int CROWD_STUCK_PRESS = 10; ///< a third of a second of getting nowhere: stop being polite
-static const Int CROWD_STUCK_GIVEUP = 60; ///< two seconds of it: back out of wherever this is
-static const Int CROWD_ESCAPE_FRAMES = 66; ///< and spend this long doing it before giving the route another go
-static const Int CROWD_ESCAPE_COOL = 90; ///< no second attempt before this, or a wedged pair rock forever
+//-------------------------------------------------------------------------------------------------
+/* Being stuck. These are not crowd constants: every unit trying to drive somewhere is measured
+ against them, with or without -crowd. The rungs of the ladder are spaced by continued lack of
+ progress rather than by wall clock, so a unit that starts moving again drops off it at once. */
+//-------------------------------------------------------------------------------------------------
+static const Real STUCK_TURN_EPSILON = 0.004f; ///< a quarter of a degree a frame: below this the hull is not turning
+static const Int STUCK_PRESS_FRAMES = 10; ///< a third of a second of getting nowhere: stop being polite
+static const Int STUCK_REPATH_FRAMES = 45; ///< a second and a half: the ladder's first rung, and the gap between rungs
+static const Int STUCK_BACKOUT_FRAMES = 66; ///< how long a backing-out manoeuvre is given before the route is tried again
+static const Int STUCK_COOL_FRAMES = 90; ///< no second drastic thing inside this, or a wedged pair rock forever
+static const Int STUCK_CYCLE_FRAMES = 150; ///< five seconds past the last rung: run the whole ladder again
+static const Int STUCK_DITHER_FRAMES = 90; ///< three seconds is long enough to tell a shuffle from a corner
+static const Real STUCK_DITHER_RATIO = 0.3f; ///< gained less than this much of the ground it covered
static const Int CROWD_MERGE_FRAMES = 45; ///< a second and a half: how far ahead a merge is worth noticing
+static const Int CROWD_TTC_FRAMES = 21; ///< closing this fast on somebody counts as being in our way, wherever it sits
+static const Int CROWD_REPATH_QUEUE = 24; ///< queued behind traffic this long: stop steering round it and ask for a new route
//-------------------------------------------------------------------------------------------------
/* Returns TRUE if the physics collide should apply the force. Normally not.
@@ -2241,10 +2263,22 @@ void AIUpdateInterface::crowdReleaseCorridor( void )
m_crowdHoldFrame = 0;
m_crowdSepSmooth = 0.0f;
m_crowdAimValid = FALSE;
- m_crowdStuck = 0;
/* The backing-out manoeuvre survives the route. Being wedged is the one thing a new route does
not cure - the new one starts in the same hole - and a unit that repaths every second while
stuck would throw away the only rule that gets it out, once a second, forever. */
+
+ /* And so does the march. A route dies for all sorts of reasons that have nothing to do with the
+ group breaking up - the unit was blocked and repathed, an attack move stopped to shoot and
+ started again, the destination moved - and every one of them used to drop the unit out of the
+ crowd model for the rest of its life, because the lane was consumed with the old path and the
+ gate at the top of crowdSteer wants one. So the slot re-arms itself: the offset is zero
+ because the new route starts under the unit's own tracks, and the per-frame fit takes it back
+ out to its own lane within a few frames. Only the next order clears it (clearCrowdLane). */
+ if (m_crowdLaneOf > 1)
+ {
+ m_pendingCrowdLat = 0.0f;
+ m_hasPendingCrowdLat = TRUE;
+ }
}
//-------------------------------------------------------------------------------------------------
@@ -2457,6 +2491,396 @@ static Bool crowdFindEscape( Object *self, const LocomotorSet& locoSet, const Co
return FALSE;
}
+//-------------------------------------------------------------------------------------------------
+/** Is this unit getting anywhere?
+ *
+ * One test, once a frame, for everything that is trying to drive somewhere - not only for units the
+ * crowd model happens to be steering. It used to live inside crowdSteer, which meant it was only
+ * ever asked about a unit that had been handed a lane by a group order, so the computer's armies
+ * and every single unit a player ever ordered anywhere were never asked at all.
+ *
+ * Ground covered against ground asked for, and turning counts as covering ground while the hull is
+ * still swinging round towards where it wants to go. See the comment on the alignment test: any
+ * turn at all excuses a tank rocking against a wall, and no turn at all condemns a tank that is
+ * simply slow to come about.
+ */
+//-------------------------------------------------------------------------------------------------
+void AIUpdateInterface::updateProgress( void )
+{
+ Object *self = getObject();
+ const Coord3D *myPos = self->getPosition();
+ const Real facing = self->getOrientation();
+
+ const Real dx = myPos->x - m_lastProgressPos.x;
+ const Real dy = myPos->y - m_lastProgressPos.y;
+ const Real moved = (Real)sqrt( dx * dx + dy * dy );
+ const Real turned = (Real)fabs( normalizeAngle( facing - m_lastProgressAngle ) );
+
+ m_lastProgressPos = *myPos;
+ m_lastProgressAngle = facing;
+
+ /* Not trying to go anywhere: nothing to be stuck at.
+
+ Aircraft are outside this, and the attempt to bring them in is worth recording. They sit
+ outside the whole movement stack - no pathfinding, no collisions, no crowd, no traffic - so
+ nothing in the game can say whether an aircraft that wants to move is moving. Opening this
+ gate to them measured 234.4 blocked unit-frames per 1000 against the ground battle's 244.9,
+ with six of eight drill seeds bit-identical and the whole difference in the two where
+ aircraft stalled, and it stayed at 244.9 after every rung of the ladder was closed to them
+ again. So merely counting them changes the match by a route not traced here. An aircraft
+ question needs a harness that orders aircraft about, which the drill does not, and until that
+ exists this gate stays shut rather than paying 4.5% of the ground battle for a number nobody
+ can yet act on. */
+ if (!isDoingGroundMovement() || getPath() == NULL || isWaitingForPath()
+ || m_curLocomotor == NULL || m_locomotorGoalType != POSITION_ON_PATH)
+ {
+ m_noProgress = 0;
+ m_rescueStage = 0;
+ return;
+ }
+
+ const BodyDamageType damage = self->getBodyModule()->getDamageState();
+ Real asked = m_curLocomotor->getMaxSpeedForCondition( damage );
+ if (m_desiredSpeed < asked)
+ asked = m_desiredSpeed; // a unit told to go slowly is not a unit going nowhere
+ if (asked < 0.01f)
+ {
+ m_noProgress = 0;
+ m_rescueStage = 0;
+ return;
+ }
+
+ Real turnBar = STUCK_TURN_EPSILON;
+ const Real rate = m_curLocomotor->getMaxTurnRate( damage );
+ if (rate * 0.5f > turnBar)
+ turnBar = rate * 0.5f;
+
+ Bool comingAbout = FALSE;
+ if (turned >= turnBar)
+ {
+ // which way the hull is pointing against where the locomotor is being sent
+ const Coord3D *myDir = self->getUnitDirectionVector2D();
+ const Real gx = m_locomotorGoalData.x - myPos->x;
+ const Real gy = m_locomotorGoalData.y - myPos->y;
+ const Real gl = (Real)sqrt( gx * gx + gy * gy );
+ if (gl > 0.01f)
+ comingAbout = ((myDir->x * gx + myDir->y * gy) / gl) < 0.87f; // more than thirty degrees off
+ else
+ comingAbout = TRUE;
+ }
+
+ if (moved < asked * 0.2f && !comingAbout)
+ {
+ ++m_noProgress;
+ // counted from a third of a second on, so the odd frame lost to a collision is not a wedge
+ if (m_noProgress > STUCK_PRESS_FRAMES)
+ Pathfinder::bumpWedgeFrame( m_noProgress );
+ }
+ else
+ {
+ m_noProgress = 0;
+ m_rescueStage = 0;
+ }
+
+ /* ---- and the other way of getting nowhere: going back and forth ----
+ The test above asks whether the unit moved. A unit dithering beside a building moves on every
+ single frame, at full speed, and is exactly where it started three seconds later, so that test
+ passes it and no counter anywhere rises.
+
+ Ground covered against ground gained, over three seconds. A unit driving somewhere has the
+ two nearly equal; one shuffling has covered several body lengths and gained nothing. A first
+ attempt measured displacement against the speed asked for instead, which fired fifty times a
+ match on units that were merely slowing down to arrive and caught nothing: the ratio is the
+ discriminator, not the distance.
+
+ What it does about it is deliberately not "ask for a new route". Repathing is what dithering
+ is made of - two routes of nearly equal cost round opposite sides of the same building, and a
+ unit that flips between them every time it is asked - so the answer is to get the body out to
+ open ground first and let the route be planned from there. That is rung three, and this
+ hands the ladder straight to it. */
+ const UnsignedInt now = TheGameLogic->getFrame();
+ m_ditherTravel += moved;
+ if (m_ditherFrame == 0 || now < m_ditherFrame)
+ {
+ m_ditherFrame = now;
+ m_ditherFrom = *myPos;
+ m_ditherTravel = 0.0f;
+ }
+ else if (now - m_ditherFrame >= (UnsignedInt)STUCK_DITHER_FRAMES)
+ {
+ const Real ddx = myPos->x - m_ditherFrom.x;
+ const Real ddy = myPos->y - m_ditherFrom.y;
+ const Real net = (Real)sqrt( ddx * ddx + ddy * ddy );
+ const Real body = self->getGeometryInfo().getBoundingCircleRadius() * 2.0f;
+
+ /* This counts and does nothing else, on purpose, and the three things it used to do are
+ worth writing down because each of them sounded right.
+
+ Back the body out to open ground, on the theory that the ground is the problem: fired
+ about fifteen times a match and took blocked unit-frames from 234 to 317 per 1000 and
+ stalled orders from 0.2% to 1.1%. Reversing a unit that is already going back and forth
+ adds a third direction to the argument and pushes the reversal into whoever is behind it.
+
+ Then, since dithering is made of changing your mind, stop it being asked: no new route and
+ no lane change for three seconds. 255 per 1000. Better than reversing and still worse
+ than nothing, because a unit forbidden to change lanes in traffic is a unit queueing.
+
+ Then the same without the lane half, holding only the route: 245. Still worse than the 234
+ of leaving it alone. Three attempts, one direction, so the rule is a counter until
+ somebody has a fourth idea. What it is worth is knowing the number: about fifteen units a
+ match under the drill drive a long way and gain nothing, and nobody could see that at all
+ before. */
+ if (AIUpdate_isDithering( net, m_ditherTravel, body ))
+ Pathfinder::bumpDither();
+
+ m_ditherFrame = now;
+ m_ditherFrom = *myPos;
+ m_ditherTravel = 0.0f;
+ }
+}
+
+Bool AIUpdate_isDithering( Real net, Real travelled, Real bodySize )
+{
+ if (travelled < bodySize * 2.0f)
+ return FALSE; // barely moved at all: that is the other test's business
+ return net < travelled * STUCK_DITHER_RATIO;
+}
+
+//-------------------------------------------------------------------------------------------------
+/** The rescue ladder.
+ *
+ * The property this is here to provide: a unit that wants to move and is not moving has something
+ * tried on it within a second and a half, and something else every second and a half after that,
+ * ending in a rung that always does something and then starting again. It cannot guarantee that a
+ * unit never gets stuck - a unit walled in on four sides by buildings has nowhere to be sent - but
+ * it does guarantee that nothing is left sitting there with the game ignoring it.
+ *
+ * The rungs are in order of how much they disturb: ask for a different route, ask the neighbours to
+ * move and stop bouncing off them, back out to open ground. Each fires once per episode.
+ */
+//-------------------------------------------------------------------------------------------------
+Int AIUpdate_stuckRung( Int noProgressFrames, Int stageDone )
+{
+ /* The whole of the ladder's timing, as one function with no state in it, so the property it is
+ here to provide can be checked rather than asserted: every rung is reached in order, none is
+ skipped, and past the last one the ladder starts again instead of going quiet. */
+ if (stageDone >= 3)
+ return (noProgressFrames > STUCK_CYCLE_FRAMES) ? -1 : 0;
+ if (noProgressFrames < STUCK_REPATH_FRAMES)
+ return 0;
+ return stageDone + 1;
+}
+
+void AIUpdateInterface::stuckRescue( void )
+{
+ if (m_rescueUntil > 0)
+ return; // already backing out; rescueSteer is driving
+
+ const Int rung = AIUpdate_stuckRung( m_noProgress, m_rescueStage );
+ if (rung == -1)
+ {
+ // still stuck after the last rung: run the whole ladder again rather than give up on it
+ m_noProgress = 0;
+ m_rescueStage = 0;
+ return;
+ }
+ if (rung == 0)
+ return;
+
+ Object *self = getObject();
+ const UnsignedInt now = TheGameLogic->getFrame();
+ if (now < m_rescueCool)
+ return;
+
+ if (rung == 1)
+ {
+ /* Rung one: a different route, from where the unit actually is. This is the cheapest thing
+ that can possibly help and it covers the two commonest causes at once - a route through
+ something that is never going to move, and a unit that has been shoved inside an obstacle,
+ which the search itself knows how to path out of. */
+ m_rescueStage = 1;
+ crowdRepath();
+ return;
+ }
+
+ // nothing above the ground gets here at all: see the gate in updateProgress
+ if (!isDoingGroundMovement())
+ return;
+
+ if (rung == 2)
+ {
+ /* Rung two: the neighbours. Anything of ours standing within a body length is asked to move,
+ and collisions are ignored for a second so the unit can push through the gap that opens
+ instead of bouncing off the edge of it. This is the engine's own pair of tools, used here
+ in the one place that knows the unit has got nowhere for three seconds. */
+ m_rescueStage = 2;
+ const Real myR = self->getGeometryInfo().getBoundingCircleRadius();
+ const Real range = myR * 3.0f + PATHFIND_CELL_SIZE_F;
+
+ PartitionFilterRelationship fRel( self, PartitionFilterRelationship::ALLOW_ALLIES );
+ PartitionFilterAlive fAlive;
+ PartitionFilterSameMapStatus fMap( self );
+ PartitionFilter *filters[] = { &fRel, &fAlive, &fMap, NULL };
+ SimpleObjectIterator *iter = ThePartitionManager->iterateObjectsInRange( self, range, FROM_CENTER_2D, filters );
+ MemoryPoolObjectHolder hold( iter );
+
+ for (Object *o = iter->first(); o; o = iter->next())
+ {
+ if (o == self)
+ continue;
+ AIUpdateInterface *ai = o->getAI();
+ if (ai == NULL || !ai->isDoingGroundMovement() || ai->isBusy())
+ continue;
+ if (o->testStatus( OBJECT_STATUS_IS_USING_ABILITY ))
+ continue;
+ ai->aiMoveAwayFromUnit( self, CMD_FROM_AI );
+ }
+
+ setIgnoreCollisionTime( LOGICFRAMES_PER_SECOND );
+ m_rescueCool = now + LOGICFRAMES_PER_SECOND;
+ return;
+ }
+
+ /* Rung three: get the body out. Sideways first and backwards second, because the ground ahead
+ is what it is already failing to drive through. The direction is the one the locomotor is
+ being sent in, which is the route when there is one and the goal when there is not. */
+ m_rescueStage = 3;
+
+ Coord2D tan;
+ tan.x = m_locomotorGoalData.x - self->getPosition()->x;
+ tan.y = m_locomotorGoalData.y - self->getPosition()->y;
+ if (tan.length() < 0.01f)
+ {
+ const Coord3D *myDir = self->getUnitDirectionVector2D();
+ tan.x = myDir->x;
+ tan.y = myDir->y;
+ }
+ tan.normalize();
+
+ const Int firstSide = (self->getID() & 1) ? 1 : -1; // no band here to say which side has room
+ if (crowdFindEscape( self, m_locomotorSet, tan, firstSide, FALSE, &m_rescueTo ))
+ {
+ // and the queue behind has to open up, or we are reversing into it
+ crowdAskBehindToBackOff( tan );
+ Pathfinder::bumpEscape();
+ setIgnoreCollisionTime( LOGICFRAMES_PER_SECOND );
+ m_rescueUntil = now + STUCK_BACKOUT_FRAMES;
+ m_noProgress = 0;
+ }
+ else
+ {
+ // walled in on every side: the only thing left to change is where it is trying to go
+ crowdRepath();
+ }
+}
+
+//-------------------------------------------------------------------------------------------------
+Bool AIUpdateInterface::rescueSteer( Coord3D& goalPos )
+{
+ if (m_rescueUntil == 0)
+ return FALSE;
+
+ Object *self = getObject();
+ const Coord3D *myPos = self->getPosition();
+ const Real dx = m_rescueTo.x - myPos->x;
+ const Real dy = m_rescueTo.y - myPos->y;
+ const Real myR = self->getGeometryInfo().getBoundingCircleRadius();
+ const Bool arrived = (Real)sqrt( dx * dx + dy * dy ) < myR + 2.0f;
+
+ if (arrived || TheGameLogic->getFrame() >= m_rescueUntil)
+ {
+ m_rescueUntil = 0;
+ m_rescueCool = TheGameLogic->getFrame() + STUCK_COOL_FRAMES;
+ m_noProgress = 0;
+ m_rescueStage = 0;
+ /* Out of the hole, and standing beside a route that still leads back into it. Without this
+ the backing out hands the unit straight back to whatever wedged it and the pair of them
+ take turns for the rest of the match. */
+ crowdRepath();
+ return FALSE;
+ }
+
+ goalPos = m_rescueTo;
+ goalPos.z = TheTerrainLogic->getGroundHeight( goalPos.x, goalPos.y );
+ return TRUE;
+}
+
+//-------------------------------------------------------------------------------------------------
+/** Give up on this route and ask for another one, to the same place, from where the unit actually
+ is now.
+
+ Every rule in crowdSteer steers along a route somebody else chose, and there is a case none of
+ them can answer: the route leads through a unit that is never going to move. Sliding sideways
+ does not help, braking does not help, and backing out only puts the unit at the end of the
+ same route. The only answer is a different route, and the traffic map has by then been
+ stamped with exactly where the jam is, so the new one goes round it.
+
+ It is asked for rather than taken: setting the blocked count past the two seconds
+ AIInternalMoveToState already repaths on is how the move state is told, and it is deliberately
+ not m_isBlockedAndStuck - that flag patches the old route locally, which is the answer to
+ "something is in the way here" and not to "this route is no good". Plain findPath from the
+ current position, which is what the player means by pathfinding again. */
+//-------------------------------------------------------------------------------------------------
+void AIUpdateInterface::crowdRepath( void )
+{
+ Pathfinder::bumpCrowdRepath();
+ m_blockedFrames = 2 * LOGICFRAMES_PER_SECOND + 1;
+ m_isBlockedAndStuck = FALSE;
+ m_crowdQueued = 0;
+ m_noProgress = 0;
+ // one drastic thing at a time: the same cooldown that stops a wedged pair rocking forever
+ m_rescueCool = TheGameLogic->getFrame() + STUCK_COOL_FRAMES;
+}
+
+//-------------------------------------------------------------------------------------------------
+/** Ask whoever is queued directly behind us to back off.
+
+ A unit at the head of a jam cannot reverse out of it: the queue behind it is what it would be
+ reversing into, and that queue is the reason it has no room to turn either. So before backing
+ out it says so, and the engine's own "get out of my way" order does the rest. Two bodies
+ back, no further: the whole column peeling away for one wedged tank is how a jam turns into a
+ rout. This is the sandbox's jam protocol with the column arithmetic left out - the engine
+ already has an order for making room, and it does not need a second one. */
+//-------------------------------------------------------------------------------------------------
+void AIUpdateInterface::crowdAskBehindToBackOff( const Coord2D& tan )
+{
+ Object *self = getObject();
+ const Real myR = self->getGeometryInfo().getBoundingCircleRadius();
+ const Real range = myR * 4.0f + PATHFIND_CELL_SIZE_F;
+
+ PartitionFilterRelationship fRel( self, PartitionFilterRelationship::ALLOW_ALLIES );
+ PartitionFilterAlive fAlive;
+ PartitionFilterSameMapStatus fMap( self );
+ PartitionFilter *filters[] = { &fRel, &fAlive, &fMap, NULL };
+ SimpleObjectIterator *iter = ThePartitionManager->iterateObjectsInRange( self, range, FROM_CENTER_2D, filters );
+ MemoryPoolObjectHolder hold( iter );
+
+ const Coord3D *myPos = self->getPosition();
+ for (Object *o = iter->first(); o; o = iter->next())
+ {
+ if (o == self)
+ continue;
+ AIUpdateInterface *ai = o->getAI();
+ if (ai == NULL || !ai->isDoingGroundMovement() || ai->isBusy())
+ continue;
+ if (o->testStatus( OBJECT_STATUS_IS_USING_ABILITY ))
+ continue;
+
+ const Coord3D *hp = o->getPosition();
+ const Real dx = hp->x - myPos->x;
+ const Real dy = hp->y - myPos->y;
+ const Real fwd = dx * tan.x + dy * tan.y;
+ if (fwd > -myR)
+ continue; // beside us or in front: not what is boxing us in
+ const Real side = -dx * tan.y + dy * tan.x;
+ const Real hisR = o->getGeometryInfo().getBoundingCircleRadius();
+ if (fabs( side ) > myR + hisR)
+ continue; // in the next lane, not behind us
+
+ ai->aiMoveAwayFromUnit( self, CMD_FROM_AI );
+ }
+}
+
//-------------------------------------------------------------------------------------------------
void AIUpdateInterface::crowdSteer( Coord3D& goalPos, Real& speed )
{
@@ -2537,68 +2961,13 @@ void AIUpdateInterface::crowdSteer( Coord3D& goalPos, Real& speed )
const UnsignedInt now = TheGameLogic->getFrame();
- /* ---- how long this unit has been asking to move and not moving ----
- Not the same question as m_blockedFrames, which is about collisions: a unit facing the wrong
- way, one whose speed cap has been talked down to nothing by the rules below, and one wedged
- between two allies it never quite touches are all standing still without a collision to show
- for it. This counts the ground covered against the speed asked for, which catches all three
- and is the number the whole ladder below is hung off. */
- const Real dxMoved = myPos->x - m_crowdLastPos.x;
- const Real dyMoved = myPos->y - m_crowdLastPos.y;
- const Real moved = (Real)sqrt( dxMoved * dxMoved + dyMoved * dyMoved );
- if (speed > 0.01f && moved < speed * 0.2f)
- ++m_crowdStuck;
- else
- m_crowdStuck = 0;
- m_crowdLastPos = *myPos;
-
- /* ---- and what to do about it ----
- Two rungs. The first stands the courtesies down: a unit that is getting nowhere has already
- given way, braked and queued for a third of a second, and every one of those rules is now
- costing it the speed it needs to push through. The second backs it out. Two seconds of
- nothing is not traffic, it is a wedge - between two allies, in the corner of a cliff, against
- the one tank in the column that is never going to move - and no amount of steering along a
- route that leads through the wedge gets out of it. Retail's answer is to keep driving into
- whatever it is until the pathfinder notices; that works when there is a collision to count,
- and this is the case where there is not. */
- const Bool pressing = m_crowdStuck > CROWD_STUCK_PRESS;
-
- if (m_crowdEscapeUntil > 0)
- {
- const Real edx = m_crowdEscape.x - myPos->x;
- const Real edy = m_crowdEscape.y - myPos->y;
- const Bool arrived = (Real)sqrt( edx * edx + edy * edy ) < myR + 2.0f;
- if (arrived || now >= m_crowdEscapeUntil)
- {
- m_crowdEscapeUntil = 0;
- m_crowdEscapeCool = now + CROWD_ESCAPE_COOL;
- m_crowdStuck = 0;
- }
- else
- {
- // nothing else applies: the route is what it is wedged against
- goalPos = m_crowdEscape;
- goalPos.z = TheTerrainLogic->getGroundHeight( goalPos.x, goalPos.y );
- m_crowdQueued = 0;
- m_crowdAimValid = FALSE; // the aim filter is for following a route, not for getting out of a hole
- if (TheGlobalData->m_showLanes && (now % LOGICFRAMES_PER_SECOND) == 0)
- DEBUG_LOG(("SHOWLANES crowd: unit %d escape to %.0f,%.0f\n", self->getID(), goalPos.x, goalPos.y));
- return;
- }
- }
- else if (m_crowdStuck > CROWD_STUCK_GIVEUP && now >= m_crowdEscapeCool)
- {
- const Int firstSide = (here.left >= here.right) ? 1 : -1;
- const Bool sealed = (here.left <= 0.01f && here.right <= 0.01f); // a bridge, or its approach
- if (crowdFindEscape( self, m_locomotorSet, here.tan, firstSide, sealed, &m_crowdEscape ))
- {
- m_crowdEscapeUntil = now + CROWD_ESCAPE_FRAMES;
- m_crowdStuck = 0;
- return;
- }
- // walled in on all four sides: keep trying the route, and ask again in a second
- m_crowdStuck = CROWD_STUCK_GIVEUP - LOGICFRAMES_PER_SECOND;
- }
+ /* How long this unit has been asking to move and not moving is not counted here any more, and
+ neither is the backing out that answers it. Both live in updateProgress and stuckRescue,
+ which run for every unit that is trying to drive somewhere rather than only for the ones a
+ group order happened to hand a lane to. All that is left of it here is the courtesy switch:
+ a unit that has got nowhere for a third of a second has already given way, braked and queued,
+ and every one of those is now costing it the speed it needs to push through. */
+ const Bool pressing = m_noProgress > STUCK_PRESS_FRAMES;
//--- one scan, every rule reads it -------------------------------------------------------------
const Real scanRange = PATHFIND_CELL_SIZE_F * 4.0f + myR;
@@ -2623,6 +2992,7 @@ void AIUpdateInterface::crowdSteer( Coord3D& goalPos, Real& speed )
Real giveWayLat = 0.0f;
Int rank = 0; // how many held-up neighbours are ahead of us in the queue
Bool touching = FALSE; // somebody's body is inside ours right now
+ Bool crossing = FALSE; // somebody outside our lane will reach us if we both keep going
Object *joiner = NULL; // somebody coming in from the side who will cross our line
Real joinerSide = 0.0f;
Real joinerR = 0.0f;
@@ -2713,15 +3083,30 @@ void AIUpdateInterface::crowdSteer( Coord3D& goalPos, Real& speed )
}
}
- // abreast and too close: push apart
- if (gap < comfort && fabs( fwd ) < myR + hisR)
+ /* Push apart from anybody inside the comfort radius, not only from whoever is exactly
+ abreast. The abreast test was the whole of the separation rule and it is the one case
+ the collision push already handles: two bodies side by side are touching, and physics
+ sorts that out. What it missed is the case boids is actually for - a neighbour half a
+ body ahead and half a body over, converging - where nothing is touching yet and a foot
+ of lane now is worth a stop later. Weighted by how far inside the radius it is, squared,
+ so a distant neighbour is nearly free and a close one dominates. */
+ if (gap < comfort && comfort > 0.01f)
{
+ /* How much of "away from him" is sideways, which for a unit directly ahead is none of it.
+ That matters: the lane is the only thing this push can move, so a follower nose to tail
+ with the unit in front has nothing to say about which way to steer, and saying
+ something anyway is a column that snakes. */
+ const Real dist = (Real)sqrt( dx * dx + dy * dy );
Real dir;
- if (fabs( side ) > 0.01f)
- dir = (side > 0.0f) ? -1.0f : 1.0f;
- else
+ if (dist > 0.01f && fabs( side ) > 0.01f)
+ dir = -side / dist;
+ else if (fabs( fwd ) < myR + hisR)
dir = (o->getID() < self->getID()) ? -1.0f : 1.0f; // exactly abreast; somebody has to pick
- sep += dir * (comfort - gap);
+ else
+ dir = 0.0f;
+
+ Real w = (comfort - ((gap > 0.0f) ? gap : 0.0f)) / comfort;
+ sep += dir * w * w * comfort;
}
/* Something bigger coming up behind in our lane. It cannot go round us in the room it has
@@ -2763,7 +3148,28 @@ void AIUpdateInterface::crowdSteer( Coord3D& goalPos, Real& speed )
packAny = TRUE;
}
- // directly ahead, near enough to matter
+ /* Somebody we are closing on who is not in our lane: a crossing, not a queue. Time to
+ contact rather than distance, so the neighbour drifting across our nose two bodies away
+ counts and the one sitting at the same distance going the same way does not.
+
+ This eases us off and nothing more. Letting a crossing unit become the blocker below was
+ tried on 2026-09-04 and is the reason units stopped dead for no visible reason: every rule
+ under `blocker` reads the blocker's speed *along our own route*, which for something
+ crossing us is about zero, so a car passing across our nose was priced exactly like a
+ wreck sitting in our lane and the brake took us to a standstill. Crossing traffic is what
+ the merge rule above is for; all that is wanted here is a lift off the throttle. */
+ if (hisPhys != NULL && fwd > 0.0f && fabs( side ) >= myR + hisR + 1.0f)
+ {
+ const Coord3D *hv = hisPhys->getVelocity();
+ const Real dist = (Real)sqrt( dx * dx + dy * dy );
+ if (dist > 0.01f)
+ {
+ const Real closing = ((myVel.x - hv->x) * dx + (myVel.y - hv->y) * dy) / dist;
+ if (closing > 0.05f && gap < closing * (Real)CROWD_TTC_FRAMES)
+ crossing = TRUE;
+ }
+ }
+
if (fwd > 0.0f && fwd < lookAhead + hisR && fabs( side ) < myR + hisR + 1.0f)
{
if (blocker == NULL || fwd < blockerFwd)
@@ -2819,9 +3225,7 @@ void AIUpdateInterface::crowdSteer( Coord3D& goalPos, Real& speed )
wants half a lane of room over the rank it is claiming; narrowing takes effect at once,
because when the ground is gone it is gone. */
const Real span = here.left + here.right;
- Int want = (Int)(span / m_crowdLaneSpace) + 1;
- if (want < 1) want = 1;
- if (want > m_crowdLaneOf) want = m_crowdLaneOf;
+ Int want = Crowd_laneCount( span, m_crowdLaneSpace, m_crowdLaneOf );
if (m_crowdFit <= 0)
m_crowdFit = want;
@@ -2860,12 +3264,17 @@ void AIUpdateInterface::crowdSteer( Coord3D& goalPos, Real& speed )
}
}
- if (blocker != NULL && !pressing)
+ /* Passing is tried whether or not this unit is getting anywhere; only the braking and the
+ courtesies stand down when it is not. Standing the whole block down under `pressing` was
+ the reason a held-up unit drove into the back of whatever was in front of it and stayed
+ there: at ten frames of no progress it stopped looking for a way round, which is precisely
+ the moment it needs one. Nothing here costs speed - a pass is a lane, not a stop. */
+ if (blocker != NULL)
{
if (!crowdOutranksMe( blocker ))
{
// we have right of way; he is the one who has to move, and we only avoid rear-ending him
- if (blockerMoving && blockerGap < myR && blockerSpeed < cap)
+ if (blockerMoving && blockerGap < myR && blockerSpeed < cap && !pressing)
cap = blockerSpeed;
}
else
@@ -2973,7 +3382,7 @@ void AIUpdateInterface::crowdSteer( Coord3D& goalPos, Real& speed )
whole march: a unit ten units behind traffic moving at its own speed is not catching
anybody up, and pricing that gap costs 60% of the column's speed for nothing. Closing
speed and the time it leaves is the only thing worth reading. */
- if (blockerMoving)
+ if (blockerMoving && !pressing)
{
const Real want = Crowd_brakeSpeed( speed, blockerSpeed, blockerGap, CROWD_BRAKE_FRAMES );
if (want < cap)
@@ -2988,6 +3397,18 @@ void AIUpdateInterface::crowdSteer( Coord3D& goalPos, Real& speed )
else if (m_crowdQueued > 0)
--m_crowdQueued;
+ /* Queued behind something that is not going anywhere, for the best part of a second, with no
+ way round it. Everything above has already been tried by now - both sides of the blocker,
+ the outside of the whole pack, the tight pass - so the route itself is the problem, and the
+ sandbox's answer is the one taken here: ask for another one. It is cheap because it is rare
+ (once every three seconds per unit at the very most) and it is the difference between a
+ column that goes round a wreck and a column that parks behind it. */
+ if (m_crowdQueued > CROWD_REPATH_QUEUE && blocker != NULL && !blockerMoving
+ && now >= m_rescueCool && Crowd_remaining( self ) > PATHFIND_CELL_SIZE_F * 3.0f)
+ {
+ crowdRepath();
+ }
+
/* Fanning out is only worth anything while stopped. Doing it all the time is a formation, and
a formation held across a map is what drives a group into every obstacle sideways-on; the
sandbox spreads out at the back of a jam and closes up again the moment it clears. */
@@ -3032,6 +3453,26 @@ void AIUpdateInterface::crowdSteer( Coord3D& goalPos, Real& speed )
if (move < -laneRate) move = -laneRate;
m_crowdLat = m_corridor->clampLat( i, m_crowdLat + move );
+ /* The gate rule is deliberately not here. The sandbox holds a unit in the open in front of a
+ one-body-wide doorway whose far side is plugged, so the column jams outside the doorway
+ rather than in it, and that was ported on 2026-09-04 and taken straight back out on the same
+ day. Two things were wrong with it in this engine and only the first is fixable. It counted
+ a parked ally as a plug, and units that have arrived stand around near narrow ground all the
+ time, so ordinary traffic was being held for units that were never going to move. Worse, the
+ hold is a stop, a stop makes m_crowdStuck climb, ten frames of that sets `pressing`, and
+ `pressing` turns the rule off - so the unit lurched forward, stopped, lurched forward, at
+ about three times a second. A rule whose own failure mode is a stutter has to be measured
+ before it goes in, not after, and this one had never been measured on its own. */
+
+ /* Somebody is going to cross in front of us: lift off, do not stop. See the scan above for why
+ this is a cap of its own rather than another blocker. */
+ if (crossing)
+ {
+ const Real ease = speed * 0.6f;
+ if (ease < cap)
+ cap = ease;
+ }
+
// ease off through a bend, or the outside of the group is asked for a speed it cannot turn at
const Real bend = (Real)fabs( m_corridor->curvature( i ) );
if (bend > 0.15f)
@@ -3072,7 +3513,13 @@ void AIUpdateInterface::crowdSteer( Coord3D& goalPos, Real& speed )
if (leftToRun < CROWD_TAPER_DIST)
outLat *= leftToRun / CROWD_TAPER_DIST; // the band closes on the destination, so the group arrives together
- m_corridor->pointAt( wantAlong, m_corridor->clampLatAt( wantAlong, outLat ), &goalPos );
+ /* Against the narrowest ground between here and there, not against the ground at either end.
+ The unit drives the straight line to this point, and a band that is wide where it is
+ standing and wide where it is aiming can be a body's width in the middle: that line is
+ then through the corner of the building the route went round, and the unit arrives at it
+ sideways and stops. This is what "they get caught on obstacles" looked like from inside
+ the code. */
+ m_corridor->pointAt( wantAlong, m_corridor->clampLatNarrowest( myAlong, wantAlong, outLat ), &goalPos );
const Real ahead = (goalPos.x - myPos->x) * here.tan.x + (goalPos.y - myPos->y) * here.tan.y;
if (ahead >= myR || wantAlong >= routeLen)
@@ -3135,7 +3582,7 @@ void AIUpdateInterface::crowdSteer( Coord3D& goalPos, Real& speed )
: (queued ? "brake" : (blocker != NULL ? "pass" : "free"))));
DEBUG_LOG(("SHOWLANES crowd: unit %d %s sample %d lat %.1f band %.1f/%.1f lane %d/%d of %d queued %d stuck %d rank %d speed %.2f\n",
self->getID(), mode, i, m_crowdLat, here.left, here.right, laneMine, laneFit, m_crowdLaneOf,
- m_crowdQueued, m_crowdStuck, rank, speed));
+ m_crowdQueued, m_noProgress, rank, speed));
}
}
@@ -3289,6 +3736,12 @@ UpdateSleepTime AIUpdateInterface::doLocomotor( void )
if (!m_laneFractionValid && getPath() != NULL)
seedLaneFraction();
+ /* Is this unit getting anywhere, and if not, what is being done about it. Both run for every
+ unit that is trying to drive somewhere, on every frame, before anything decides where to
+ steer: the answer is what the courtesy rules and the rescue ladder are both hung off. */
+ updateProgress();
+ stuckRescue();
+
const Bool traceWasBlocked = m_isBlocked; // -tracemove: the flag is cleared on the next line
m_isBlocked = FALSE;
@@ -3385,12 +3838,19 @@ UpdateSleepTime AIUpdateInterface::doLocomotor( void )
}
}
- /* -crowd hangs here, on the two numbers about to be handed to the locomotor. The
- point on the route has already been worked out; the crowd model moves it sideways
- across the width of the road and takes speed off for whatever is in the way.
- Ground movement only - an aircraft has no road and no traffic. */
- if (TheGlobalData->m_crowdModel && isDoingGroundMovement())
- crowdSteer(goalPos, speed);
+ /* A unit backing out of somewhere is not following its route this frame, and
+ nothing else may touch the point it is being sent to. This is the one rung of
+ the rescue ladder that has to steer rather than ask, and it is here rather than
+ inside the crowd model because being wedged is not a crowd problem. */
+ if (!rescueSteer(goalPos))
+ {
+ /* -crowd hangs here, on the two numbers about to be handed to the locomotor. The
+ point on the route has already been worked out; the crowd model moves it sideways
+ across the width of the road and takes speed off for whatever is in the way.
+ Ground movement only - an aircraft has no road and no traffic. */
+ if (TheGlobalData->m_crowdModel && isDoingGroundMovement())
+ crowdSteer(goalPos, speed);
+ }
m_curLocomotor->locoUpdate_moveTowardsPosition(getObject(), goalPos,
onPathDistToGoal+getPathExtraDistance(), speed, &blocked);
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
index 70d134c8e..86c1d5cfe 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
@@ -3839,8 +3839,154 @@ static const char *getModuleProfileReport( void )
rate means nothing at all. The blocked unit-frames underneath it are the point, and they are
the first numbers this fork has ever had for the steering itself. */
//-------------------------------------------------------------------------------------------------
+/* What the drill is for, in the end: were the units that were sent somewhere still trying to get
+ there when the next order arrived, or had they stopped. Blocked unit-frames say how much time
+ was spent in traffic; this says whether the traffic was ever cleared. One entry per unit per
+ order, scored at the next tick and thrown away.
+
+ "Stalled" is deliberately not "did not arrive". Forty units sent to one point cannot all stand
+ on it, and a unit that spent the whole window fighting has not failed to move for want of a
+ route. It is "covered less than a tenth of the distance it was given", which is a unit that
+ never got going at all. */
+struct DrillOrder
+{
+ ObjectID id;
+ Coord3D dest;
+ Real startDist;
+};
+static std::vector<DrillOrder> theDrillOrders;
+static Int theDrillScored = 0;
+static Int theDrillArrived = 0;
+static Int theDrillStalled = 0;
+
+/* And why the stalled ones stalled. "1.2% never got going" is a number to be held to; it is not
+ an answer, and without this the only way to find out was to watch a match. Every unit that
+ scores as stalled is asked the six questions that can be asked from outside it, in the order
+ that makes the answer unambiguous: the first one that fits is the reason. */
+enum
+{
+ DRILL_WHY_DISABLED = 0, ///< held, EMP'd, sold, whatever: not a movement answer
+ DRILL_WHY_NOSTATE, ///< not in a move state any more, so something else took the unit over
+ DRILL_WHY_NOPATH, ///< in a move state, no path and not waiting for one: the search failed
+ DRILL_WHY_WAITING, ///< still waiting for the pathfinder
+ DRILL_WHY_BLOCKED, ///< has a path and is being collided with
+ DRILL_WHY_SILENT, ///< has a path, nothing is touching it, and it is not moving
+ DRILL_WHY_COUNT
+};
+static const char *theDrillWhyName[ DRILL_WHY_COUNT ] =
+ { "disabled", "nostate", "nopath", "waiting", "blocked", "silent" };
+static Int theDrillWhy[ DRILL_WHY_COUNT ];
+static char theDrillReport[ 256 ];
+
+const char *GroupDrill_report( void )
+{
+ Int len = sprintf( theDrillReport, "orders %d arrived %d stalled %d",
+ theDrillScored, theDrillArrived, theDrillStalled );
+ for( Int w = 0; w < DRILL_WHY_COUNT; w++ )
+ len += sprintf( theDrillReport + len, " %s %d", theDrillWhyName[ w ], theDrillWhy[ w ] );
+ return theDrillReport;
+}
+
+void GroupDrill_reset( void )
+{
+ theDrillOrders.clear();
+ theDrillScored = 0;
+ theDrillArrived = 0;
+ theDrillStalled = 0;
+ for( Int w = 0; w < DRILL_WHY_COUNT; w++ )
+ theDrillWhy[ w ] = 0;
+}
+
+/** Why is this unit, which was sent somewhere twenty seconds ago and has not moved, not moving. */
+static Int groupDrillWhyStalled( Object *obj )
+{
+ AIUpdateInterface *ai = obj->getAIUpdateInterface();
+ if (ai == NULL || obj->isDisabled())
+ return DRILL_WHY_DISABLED;
+
+ const AIStateType state = ai->getAIStateType();
+ if (state != AI_MOVE_TO && state != AI_ATTACK_MOVE_TO && state != AI_MOVE_AND_TIGHTEN
+ && state != AI_FOLLOW_PATH && state != AI_MOVE_OUT_OF_THE_WAY)
+ return DRILL_WHY_NOSTATE;
+
+ if (ai->isWaitingForPath())
+ return DRILL_WHY_WAITING;
+ if (ai->getPath() == NULL)
+ return DRILL_WHY_NOPATH;
+ if (ai->getNumFramesBlocked() > 0)
+ return DRILL_WHY_BLOCKED;
+ return DRILL_WHY_SILENT;
+}
+
+static void groupDrillScorePrevious( void )
+{
+ const Real arriveDist = PATHFIND_CELL_SIZE_F * 12.0f;
+
+ for (std::vector<DrillOrder>::iterator it = theDrillOrders.begin(); it != theDrillOrders.end(); ++it)
+ {
+ Object *obj = TheGameLogic->findObjectByID( it->id );
+ if (obj == NULL || obj->isEffectivelyDead())
+ continue; // died on the way: not a movement answer either way
+
+ /* Only units that were actually given a journey. Forty units sent to a point they are
+ already standing on shuffle a body length while the group re-forms, and against a starting
+ distance of eight world units that shuffle reads as "went nowhere": four of the first
+ seven stalls this ever reported were that. */
+ if (it->startDist < arriveDist * 2.0f)
+ continue;
+
+ const Coord3D *pos = obj->getPosition();
+ const Real dx = it->dest.x - pos->x;
+ const Real dy = it->dest.y - pos->y;
+ const Real now = (Real)sqrt( dx * dx + dy * dy );
+
+ AIUpdateInterface *ai = obj->getAIUpdateInterface();
+ const Bool doneWithIt = (ai == NULL) || (ai->getPath() == NULL && !ai->isWaitingForPath());
+
+ /* Arrived, and the second half of that is not pedantry either. Forty units cannot stand on
+ one point, so the ones that packed in around it are further from the middle than the
+ radius allows while being exactly where they meant to stop. A unit that has stopped
+ trying and is inside a quarter of the distance it was given has arrived. */
+ if (now < arriveDist || (doneWithIt && now < it->startDist * 0.25f))
+ {
+ ++theDrillScored;
+ ++theDrillArrived;
+ continue;
+ }
+
+ /* Still ours? The computer player goes on giving its teams orders of its own between drill
+ ticks, and a unit sent somewhere else is not a unit that failed to get here. Without this
+ the stalled figure was two fifths of every order given, and most of that was the AI
+ changing its mind rather than anything being stuck. */
+ Coord3D goal;
+ if (!TheAI->pathfinder()->goalPosition( obj, &goal ))
+ continue;
+ const Real gdx = goal.x - it->dest.x;
+ const Real gdy = goal.y - it->dest.y;
+ if ((Real)sqrt( gdx * gdx + gdy * gdy ) > PATHFIND_CELL_SIZE_F * 20.0f)
+ continue;
+
+ ++theDrillScored;
+ if (now > it->startDist * 0.9f)
+ {
+ ++theDrillStalled;
+ const Int why = groupDrillWhyStalled( obj );
+ ++theDrillWhy[ why ];
+ DEBUG_LOG(("DRILLSTALL frame %d unit %d %s: %s, %.0f of %.0f left at %.0f,%.0f layer %d, blocked %d noprogress %d state %d\n",
+ TheGameLogic->getFrame(), (Int)it->id, obj->getTemplate()->getName().str(),
+ theDrillWhyName[ why ], now, it->startDist, pos->x, pos->y, (Int)obj->getLayer(),
+ ai ? ai->getNumFramesBlocked() : -1,
+ ai ? ai->getNoProgressFrames() : -1,
+ ai ? (Int)ai->getAIStateType() : -1));
+ }
+ }
+ theDrillOrders.clear();
+}
+
static void groupDrillTick( void )
{
+ groupDrillScorePrevious();
+
Region3D extent;
TheTerrainLogic->getExtent( &extent );
const Real inset = PATHFIND_CELL_SIZE_F * 8.0f;
@@ -3887,6 +4033,26 @@ static void groupDrillTick( void )
dest.z = TheTerrainLogic->getGroundHeight( dest.x, dest.y );
group->groupMoveToPosition( &dest, false, CMD_FROM_AI );
+
+ // and remember who was sent where, so the next tick can ask whether they got there
+ for( Object *member = TheGameLogic->getFirstObject(); member; member = member->getNextObject() )
+ {
+ if (!group->isMember( member ))
+ continue;
+ // the order itself skips these, so counting them as sent somewhere is counting a
+ // passenger in a transport as a unit that failed to drive there
+ if (member->isDisabledByType( DISABLED_HELD ) || member->isKindOf( KINDOF_IMMOBILE ))
+ continue;
+ const Coord3D *pos = member->getPosition();
+ const Real dx = dest.x - pos->x;
+ const Real dy = dest.y - pos->y;
+ DrillOrder order;
+ order.id = member->getID();
+ order.dest = dest;
+ order.startDist = (Real)sqrt( dx * dx + dy * dy );
+ theDrillOrders.push_back( order );
+ }
+
TheAI->destroyGroup( group );
}
}
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 6ede518da..e84620617 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -8761,6 +8761,149 @@ TEST(crowd_corridor_has_no_band_on_a_bridge_or_at_its_approaches)
CHECK_NEAR( plain.at( k ).left, 15.0f, 0.001f );
}
+TEST(the_rescue_ladder_never_runs_out_of_rungs)
+{
+ /* The promise: a unit that wants to move and is not moving always has something tried on it, in
+ order, and when the ladder runs out it starts again rather than going quiet. Written against
+ the shape rather than the frame counts, so tuning the thresholds does not break the test and
+ skipping a rung does. */
+
+ // nothing at all while the unit is still getting somewhere
+ CHECK_EQ( AIUpdate_stuckRung( 0, 0 ), 0 );
+ CHECK_EQ( AIUpdate_stuckRung( 1, 0 ), 0 );
+
+ // long enough, and the rungs come one at a time and in order
+ CHECK_EQ( AIUpdate_stuckRung( 1000, 0 ), 1 );
+ CHECK_EQ( AIUpdate_stuckRung( 1000, 1 ), 2 );
+ CHECK_EQ( AIUpdate_stuckRung( 1000, 2 ), 3 );
+
+ // past the last one it restarts, and only after a further wait
+ CHECK_EQ( AIUpdate_stuckRung( 1000, 3 ), -1 );
+ CHECK_EQ( AIUpdate_stuckRung( 0, 3 ), 0 );
+
+ /* No rung is ever skipped and none is ever offered early: whatever the frame count, the answer
+ is either nothing or exactly the next one up. */
+ for (Int stage = 0; stage <= 3; stage++)
+ {
+ Int seen = 0;
+ for (Int f = 0; f < 400; f++)
+ {
+ const Int rung = AIUpdate_stuckRung( f, stage );
+ CHECK( rung == 0 || rung == stage + 1 || rung == -1 );
+ if (rung != 0)
+ ++seen;
+ }
+ // and the ladder always eventually offers something, at every stage including the last
+ CHECK( seen > 0 );
+ }
+}
+
+TEST(driving_a_long_way_and_gaining_nothing_is_not_the_same_as_being_slow)
+{
+ const Real body = 24.0f; // a tank
+
+ // going somewhere: what it covered is what it gained
+ CHECK( !AIUpdate_isDithering( 200.0f, 210.0f, body ) );
+ CHECK( !AIUpdate_isDithering( 90.0f, 100.0f, body ) );
+
+ // round a corner, so some of the travel is spent turning: still going somewhere
+ CHECK( !AIUpdate_isDithering( 140.0f, 200.0f, body ) );
+
+ // back and forth beside a building: eight body lengths covered, half a body gained
+ CHECK( AIUpdate_isDithering( 12.0f, 200.0f, body ) );
+ CHECK( AIUpdate_isDithering( 0.0f, 100.0f, body ) );
+
+ /* Slow is not dithering and neither is stopped. A unit that crept twenty units in three
+ seconds has gained everything it covered, and one that never moved has covered nothing: both
+ belong to the other test, and catching them here is what makes a rule fire on every unit
+ politely slowing down to park. */
+ CHECK( !AIUpdate_isDithering( 20.0f, 20.0f, body ) );
+ CHECK( !AIUpdate_isDithering( 0.0f, 0.0f, body ) );
+ CHECK( !AIUpdate_isDithering( 1.0f, 30.0f, body ) ); // under two body lengths of travel
+
+ // and the floor scales with the body, so infantry are not held to a tank's yardstick
+ CHECK( AIUpdate_isDithering( 1.0f, 30.0f, 6.0f ) );
+}
+
+TEST(a_steering_point_is_clamped_by_the_pinch_it_has_to_drive_through)
+{
+ /* A straight road, wide at both ends and one body wide in the middle. Clamping the aim point
+ against the ground at either end says nothing is wrong with riding 30 units off the centre
+ line, and the straight line between those two points goes through whatever is making the
+ middle narrow. That is a unit driving into the corner of a building on a route that went
+ round it. */
+ Coord3D pts[ 7 ];
+ Real width[ 7 ];
+ for (Int k = 0; k < 7; k++)
+ {
+ pts[ k ].x = (Real)k * 10.0f;
+ pts[ k ].y = 0.0f;
+ pts[ k ].z = 0.0f;
+ width[ k ] = (k == 3) ? 4.0f : 40.0f; // one sample of narrow ground in the middle
+ }
+
+ CrowdCorridor corr;
+ corr.buildForTest( pts, 7, 40.0f, NULL, width );
+ CHECK( !corr.isEmpty() );
+
+ // each end on its own allows the whole offset
+ CHECK_NEAR( corr.clampLatAt( 0.0f, 30.0f ), 30.0f, 0.001f );
+ CHECK_NEAR( corr.clampLatAt( 60.0f, 30.0f ), 30.0f, 0.001f );
+
+ // asked about the stretch that contains the pinch, it gives the pinch
+ CHECK_NEAR( corr.clampLatNarrowest( 0.0f, 60.0f, 30.0f ), 4.0f, 0.001f );
+ CHECK_NEAR( corr.clampLatNarrowest( 0.0f, 60.0f, -30.0f ), -4.0f, 0.001f );
+
+ // argument order does not matter, and a stretch past the pinch is not cut by it
+ CHECK_NEAR( corr.clampLatNarrowest( 60.0f, 0.0f, 30.0f ), 4.0f, 0.001f );
+ CHECK_NEAR( corr.clampLatNarrowest( 40.0f, 60.0f, 30.0f ), 30.0f, 0.001f );
+
+ // and it never widens anything: whatever comes back fits everywhere the walk looked
+ CHECK_NEAR( corr.clampLatNarrowest( 0.0f, 60.0f, 2.0f ), 2.0f, 0.001f );
+}
+
+TEST(a_group_is_never_more_than_five_lanes_wide)
+{
+ const Real body = 24.0f; // about a tank, which is what the spacing is measured from
+
+ // the ground decides, up to the cap: two lanes of room is two lanes
+ CHECK_EQ( Crowd_laneCount( 0.0f, body, 0 ), 1 );
+ CHECK_EQ( Crowd_laneCount( body, body, 0 ), 2 );
+ CHECK_EQ( Crowd_laneCount( body * 3.0f, body, 0 ), 4 );
+
+ // and then it stops. Open country is not a reason to arrive twenty abreast
+ CHECK_EQ( Crowd_laneCount( body * 4.0f, body, 0 ), 5 );
+ CHECK_EQ( Crowd_laneCount( body * 40.0f, body, 0 ), 5 );
+ CHECK_EQ( Crowd_laneCount( 100000.0f, body, 0 ), 5 );
+
+ // never more lanes than there are bodies to put in them
+ CHECK_EQ( Crowd_laneCount( body * 40.0f, body, 3 ), 3 );
+ CHECK_EQ( Crowd_laneCount( body * 40.0f, body, 9 ), 5 );
+
+ // degenerate inputs are one lane, not a division by zero or a negative count
+ CHECK_EQ( Crowd_laneCount( body * 4.0f, 0.0f, 4 ), 1 );
+ CHECK_EQ( Crowd_laneCount( -50.0f, body, 4 ), 1 );
+}
+
+TEST(a_turn_costs_what_the_hull_takes_to_swing_it)
+{
+ // chassis is the cost of one radian: a hull that drives 40 units while turning one radian
+ CHECK_EQ( Pathfinder_turnCost( 1.0f, 40, 60 ), 40 );
+ CHECK_EQ( Pathfinder_turnCost( 0.5f, 40, 60 ), 20 );
+
+ // the caps bite, and they are the two different ones the search uses
+ CHECK_EQ( Pathfinder_turnCost( 3.14159f, 40, 60 ), 60 );
+ CHECK_EQ( Pathfinder_turnCost( 3.14159f, 40, 28 ), 28 );
+
+ // a hull that turns on the spot pays nothing, and so does the switch being off
+ CHECK_EQ( Pathfinder_turnCost( 3.14159f, 0, 60 ), 0 );
+ CHECK_EQ( Pathfinder_turnCost( 0.0f, 40, 60 ), 0 );
+
+ // never negative, whatever it is handed
+ CHECK_EQ( Pathfinder_turnCost( -1.0f, 40, 60 ), 0 );
+ CHECK( Pathfinder_turnCost( 2.0f, 3, 60 ) >= 0 );
+}
+
TEST(crowd_brake_only_reads_closing_time)
{
const Int frames = 8;
diff --git a/ai-batch.ps1 b/ai-batch.ps1
index 4c2f5c8b4..9924729a0 100644
--- a/ai-batch.ps1
+++ b/ai-batch.ps1
@@ -93,7 +93,12 @@ for ($i = 0; $i -lt $Runs; $i++) {
# rather than an AI against an idle human seat (see the observer note in setupAutoSkirmish).
# -multiInstance: the single-instance guard counts a headless run as "Generals is already
# running" and bails at once, so a batch cannot be measured while a copy of the game is open
- $args = @("-headless", "-quickstart", "-noshellmap", "-observer", "-multiInstance")
+ # -noFPSLimit uncaps the renderer. A headless run has no renderer and already ticks its logic
+ # every pass, so it changes nothing here; it is passed anyway so that dropping -headless (which
+ # is how a renderer or stutter question is measured) does not quietly put the run back behind
+ # the monitor's refresh. Game speed is untouched - that is -fps, and moving it would make this
+ # batch incomparable with every earlier one.
+ $args = @("-headless", "-quickstart", "-noshellmap", "-observer", "-multiInstance", "-noFPSLimit")
if ($Map) {
# -map wants the path the map cache holds, and WinMain's tokenizer honours double quotes -
# which every shipped map name needs, because they all have a space in them.
@@ -138,7 +143,9 @@ for ($i = 0; $i -lt $Runs; $i++) {
# what the pathfinder did over the whole match, for comparing a pathing change against its
# baseline: search time and count say what it cost, nopath/outofcells say whether it broke,
# blocked/stuck say whether the traffic jams it was aimed at actually got shorter
- $pf = [pscustomobject]@{ FindMs = 0.0; Finds = 0; Expands = 0; NoPath = 0; OutOfCells = 0; Blocked = 0; Stuck = 0 }
+ $pf = [pscustomobject]@{ FindMs = 0.0; Finds = 0; Expands = 0; NoPath = 0; OutOfCells = 0; Blocked = 0; Stuck = 0
+ Wedge = 0; WedgeWorst = 0; Escapes = 0; Repaths = 0
+ Dithers = 0; Orders = 0; Arrived = 0; Stalled = 0 }
# THREADING-ROADMAP.md section 0: the per-scope frame cost, present only in a PERF_TIMERS
# build (-Exe generals_perf.exe), and the job pool's own report, present in every build.
$perf = @{}
@@ -171,6 +178,12 @@ for ($i = 0; $i -lt $Runs; $i++) {
$why = $Matches[1]
$frames = [int]$Matches[2]
}
+ elseif ($line -match "HEADLESS DRILL: orders (\d+) arrived (\d+) stalled (\d+)") {
+ # -groupdrill only: did the units that were marched across the map get there
+ $pf.Orders = [int]$Matches[1]
+ $pf.Arrived = [int]$Matches[2]
+ $pf.Stalled = [int]$Matches[3]
+ }
elseif ($line -match "HEADLESS PATHFIND: (.*)") {
$report = $Matches[1]
# "queue 6000x/47 find 2313x/0 ... expand 11414x | nopath 0 outofcells 0 blocked 17 stuck 0"
@@ -188,6 +201,13 @@ for ($i = 0; $i -lt $Runs; $i++) {
if ($report -match "outofcells (\d+)") { $pf.OutOfCells = [int]$Matches[1] }
if ($report -match "blocked (\d+)") { $pf.Blocked = [int]$Matches[1] }
if ($report -match "stuck (\d+)") { $pf.Stuck = [int]$Matches[1] }
+ # the crowd model's own three: a unit stopped with nothing to blame it on, the backing-out
+ # manoeuvres that answers, and the routes given up on entirely
+ if ($report -match "wedge (\d+)") { $pf.Wedge = [int]$Matches[1] }
+ if ($report -match "worst (\d+)") { $pf.WedgeWorst = [int]$Matches[1] }
+ if ($report -match "escape (\d+)") { $pf.Escapes = [int]$Matches[1] }
+ if ($report -match "repath (\d+)") { $pf.Repaths = [int]$Matches[1] }
+ if ($report -match "dither (\d+)") { $pf.Dithers = [int]$Matches[1] }
}
elseif ($line -match "HEADLESS PLAYER (\d+) '(.*?)': (\w+) \| score (\d+) \| money (\d+) earned (\d+) spent \| units (\d+) built (\d+) lost (\d+) killed peak (\d+)") {
$slots[[int]$Matches[1]] = [pscustomobject]@{
@@ -259,6 +279,29 @@ if ($pfRows.Count -gt 0) {
$totFrames = ($pfRows | Measure-Object Frames -Sum).Sum
$totBlocked = ($pfRows | ForEach-Object { $_.Pf.Blocked } | Measure-Object -Sum).Sum
Write-Host ("blocked unit-frames per 1000 logic frames: {0:n1}" -f (1000.0 * $totBlocked / $totFrames))
+
+ # and the half of it a collision never sees: stopped with nothing to blame, and what was done
+ # about it. Only the crowd model counts these, so a run without -crowd reports zeroes.
+ $totWedge = ($pfRows | ForEach-Object { $_.Pf.Wedge } | Measure-Object -Sum).Sum
+ # the worst is the one that matters: the rescue ladder promises nothing is left wanting to move
+ # and not moving for longer than its own cycle, and this is the number that holds it to it
+ $worstWedge = ($pfRows | ForEach-Object { $_.Pf.WedgeWorst } | Measure-Object -Maximum).Maximum
+ Write-Host ("wedged unit-frames per 1000 logic frames: {0:n1} | worst single wedge {1} frames ({2:n1}s) | escapes {3} repaths {4} dithers {5} per match" -f
+ (1000.0 * $totWedge / $totFrames),
+ $worstWedge, ($worstWedge / 30.0),
+ (& $avg { param($p) $p.Escapes }),
+ (& $avg { param($p) $p.Repaths }),
+ (& $avg { param($p) $p.Dithers }))
+
+ # -groupdrill only: the plainest question there is. Of every unit sent across the map, how many
+ # were still going when the next order came, and how many had stopped and stayed stopped.
+ $totOrders = ($pfRows | ForEach-Object { $_.Pf.Orders } | Measure-Object -Sum).Sum
+ if ($totOrders -gt 0) {
+ $totArrived = ($pfRows | ForEach-Object { $_.Pf.Arrived } | Measure-Object -Sum).Sum
+ $totStalled = ($pfRows | ForEach-Object { $_.Pf.Stalled } | Measure-Object -Sum).Sum
+ Write-Host ("group orders: {0:n0} scored, {1:n1}% reached the destination, {2:n1}% never got going" -f
+ $totOrders, (100.0 * $totArrived / $totOrders), (100.0 * $totStalled / $totOrders))
+ }
}
# Stability. A mean frame time is the statistic that hides a stutter, so this reports the tail:
@@ -319,5 +362,10 @@ $rows | Select-Object Seed, Cells, Why, Frames, Wall,
@{n="NoPath";e={ if ($_.Pf) { $_.Pf.NoPath } }},
@{n="OutOfCells";e={ if ($_.Pf) { $_.Pf.OutOfCells } }},
@{n="Blocked";e={ if ($_.Pf) { $_.Pf.Blocked } }},
- @{n="Stuck";e={ if ($_.Pf) { $_.Pf.Stuck } }} | Export-Csv -Path $csv -NoTypeInformation
+ @{n="Stuck";e={ if ($_.Pf) { $_.Pf.Stuck } }},
+ @{n="Wedge";e={ if ($_.Pf) { $_.Pf.Wedge } }},
+ @{n="WedgeWorst";e={ if ($_.Pf) { $_.Pf.WedgeWorst } }},
+ @{n="Escapes";e={ if ($_.Pf) { $_.Pf.Escapes } }},
+ @{n="Repaths";e={ if ($_.Pf) { $_.Pf.Repaths } }},
+ @{n="Dithers";e={ if ($_.Pf) { $_.Pf.Dithers } }} | Export-Csv -Path $csv -NoTypeInformation
Write-Host "per-match rows: $csv"
diff --git a/replay-check.ps1 b/replay-check.ps1
index cf69e1415..83228ef5f 100644
--- a/replay-check.ps1
+++ b/replay-check.ps1
@@ -57,7 +57,10 @@ $lastReplay = Join-Path $replayDir "00000000.rep"
function Invoke-Run([string[]] $extra, [string] $prefix)
{
- $args = @("-headless", "-quickstart", "-noshellmap", "-multiInstance",
+ # -noFPSLimit for the same reason as in ai-batch.ps1: headless does not need it, and a run that
+ # has its window back must not be paced by the monitor. It cannot touch the logic, so the CRC
+ # this script compares is unaffected either way.
+ $args = @("-headless", "-quickstart", "-noshellmap", "-multiInstance", "-noFPSLimit",
"-maxframes", $MaxFrames, "-logPrefix", $prefix) + $extra + $ExtraArgs
$proc = Start-Process -FilePath $exePath -ArgumentList $args -WorkingDirectory $RunDir -PassThru
$proc.WaitForExit()