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): lay each vehicle a parallel lane of one group route

Olcay Seygan6449f93e21d1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bb58487c2..03db89915 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -183,6 +183,7 @@ found and fixed — EA's own, not port damage.**
- A tank in a column no longer parks behind the one in front while that one drives away. Touching the tank ahead cut its speed a little more every moment and never let it come back, so once the leader had paused, the follower sat at a dead stop until their hulls came apart and then crawled back up to speed. Every pause at the head of a column rippled down it as a line of tanks standing still. The follower now picks its speed up again as soon as the one in front moves off. Across eight maps, stops of a second or more behind the unit ahead fell from 27 to 19 in a 30-unit squad and from 1169 to 781 in a 200-unit army, the longest single stop in that army went from 14.6 seconds to 9, and the last tank of the squad arrives 6.6 seconds sooner. In computer-against-computer matches, the time units spent jammed so hard that the game counted them stuck fell from about 1.3 seconds a match to half a second.
- Tanks and infantry sent together no longer trip over each other. A tank that caught up with a soldier of its own side marching the same way told him to step aside, and a soldier who steps aside forgets his route and stands for a full second before he may ask for another. In a mixed squad of 20 Crusaders and 10 Rangers every one of the 28 second-long stops across eight maps was exactly that. The tank now rolls through a soldier walking its way, the way soldiers already walk through each other; one standing still or crossing its path is still asked to move. Stops of a second or more fell from 48 to 12 in that squad and from 977 to 546 in a 200-unit army, and both arrive sooner: the last Crusader 2.5 seconds earlier, the whole army 1.9 seconds earlier on average. In computer-against-computer matches, time spent wedged fell 11%.
- Two columns that meet head-on get past each other. The game has a rule for it, written by the original team: two tanks nose to nose for a second drive through each other. A counter that reset itself every frame meant it never once fired, so the front pair stood there, sometimes for more than seven seconds, and everything behind them queued. It fires now, after a quarter of a second. Twenty tanks meeting twenty in the open used to stop 104 times and bring the last one in after 72 seconds; now they stop once, and the last one arrives after 23. Two armies of 420 crossing the map through each other get there in half the time: the Crusaders' average trip went from 167 seconds to 91, the Battlemasters' from 149 to 75.
+- A group you send round a corner goes round it side by side. Every tank used to work out its own route, every one of those routes ran over the tip of the corner, and the whole group squeezed onto that one point with the outside tanks cutting across the inside ones to reach it. Now the group takes one route and each vehicle drives its own lane of it: the outside lane swings wide, the inside one stays clear of the wall, and where the street narrows the lanes close up over a few corners rather than zigzagging. A tank whose place is short of the click stops at it, instead of driving its lane to the far end and coming back. Twenty-four tanks sent through the streets of Alpine Assault came to a dead stop 7 times a crossing instead of 10 and spent a third less time pressed against each other, and the column in the Forgotten Forest trailer scene gets its last tank home 20 seconds sooner. Infantry, and any group whose route crosses a bridge, still find their own way. A replay recorded before this change plays back differently.
- A jet shot down in the air flies on before it falls. Its wings stopped working on the frame it was hit, so it dropped almost vertically and hit the ground under the spot it was killed at, which is the one thing a plane doing three hundred knots cannot do. It keeps its lift now and gives it up over the next second or so, carrying forward and nosing over as it goes.
- And the bombers come down at all. A B-52, a Spectre gunship, a cargo plane and an A-10 all left the falling speed out of their data, and nought means the lift exactly cancels gravity: shot down, they flew on at cruising height, burning, and blew up in the air still level. Every one of them now falls at half gravity or better, and the fireball waits for the ground instead of going off on a timer somewhere over the map. Measured on the way in: a B-52 falls for 2.8 seconds and lands, where it used to detonate at a hundred feet. On the way home it still did not: after the drop a bomber flies off the map on a precise course that is allowed three times its normal lift, which held a dead one up with lift to spare. A bomber shot down after its run now comes down like one shot down before it.
diff --git a/GeneralsMD/Code/Data/Scenarios/bridgecross.txt b/GeneralsMD/Code/Data/Scenarios/bridgecross.txt
new file mode 100644
index 000000000..723881533
--- /dev/null
+++ b/GeneralsMD/Code/Data/Scenarios/bridgecross.txt
@@ -0,0 +1,18 @@
+# Bridge crossing.
+#
+# Twenty tanks, one order, over the Kandahar bridge on Golden Oasis that runs from 1826,1410 to
+# 1688,1585: how long the last of them takes to reach the far bank. The start and the goal sit 350
+# units back from each end of the deck, on its line, so the route has to go over it. The order is a
+# playermove, a right click: a script move takes retail's column branch and never reaches the crowd
+# model that decides how many abreast go over.
+#
+# generals.exe -headless -quickstart -noshellmap -observer -multiInstance -noFPSLimit
+# -map "Maps\Golden Oasis\Golden Oasis.map" -autoskirmish 2 -takeover
+# -side 0 FactionAmerica -side 1 FactionGLA -seed 1 -maxframes 3000
+# -scenario bridgecross -logPrefix bridge_
+#
+# then grep the log for HEADLESS ARRIVE. Add -showlanes for the crowd model's own trail.
+
+30 spawn 0 AmericaTankCrusader 20 2043 1136 40
+60 playermove 0 AmericaTankCrusader 1471 1859
+60 arrive 0 AmericaTankCrusader 1471 1859 200
diff --git a/GeneralsMD/Code/Data/Scenarios/towncross.txt b/GeneralsMD/Code/Data/Scenarios/towncross.txt
new file mode 100644
index 000000000..5fd09f2a0
--- /dev/null
+++ b/GeneralsMD/Code/Data/Scenarios/towncross.txt
@@ -0,0 +1,18 @@
+# Town crossing.
+#
+# Twenty-four tanks, one right click, through the streets of Alpine Assault from 760,920 to 1400,1400:
+# the same line mobattack.txt marches, which runs between the houses, so the group has to take
+# corners rather than open ground. How the column rounds a corner is the whole question, and the
+# answer shows in the blocked unit-frames on the HEADLESS PATHFIND line more than in the arrival.
+#
+# generals.exe -headless -quickstart -noshellmap -observer -multiInstance -noFPSLimit
+# -map "Maps\Alpine Assault\Alpine Assault.map" -autoskirmish 2 -takeover
+# -side 0 FactionAmerica -side 1 FactionGLA -seed 1 -maxframes 3000
+# -scenario towncross -logPrefix town_
+#
+# A playermove, a right click: a script move takes retail's column branch instead.
+
+30 spawn 0 AmericaTankCrusader 16 760 920 40
+30 spawn 0 AmericaTankPaladin 8 760 1080 40
+60 playermove 0 * 1400 1400
+60 arrive 0 * 1400 1400 250
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/CrowdModel.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/CrowdModel.h
index 64b26a6f8..05c18ee68 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/CrowdModel.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/CrowdModel.h
@@ -88,6 +88,22 @@ enum
(`members` of 0 means the caller counts them itself). */
extern Int Crowd_laneCount( Real span, Real spacing, Int members );
+/// one corner of a route, and the deck it is on
+struct CrowdRoutePoint
+{
+ Coord3D pos;
+ PathfindLayerEnum layer;
+};
+typedef std::vector<CrowdRoutePoint> CrowdRoute;
+
+/// the optimized corners of `path`, first to last
+extern void Crowd_routeFromPath( Path *path, CrowdRoute *out );
+
+/** Where a lane `offset` left of a route turns at the corner `c` between `a` and `b`: along the
+ bisector of the two legs' left normals, as far as keeps both legs `offset` away, and never
+ more than twice `offset` however sharp the turn. FALSE for a leg of no length. */
+extern Bool Crowd_laneCorner( const Coord3D& a, const Coord3D& c, const Coord3D& b, Real offset, Coord2D *shift );
+
/**
* A route, sampled, with the width of the drivable ground either side of every sample.
*
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
index b261181f3..c82768b69 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
@@ -36,6 +36,7 @@
#include "GameLogic/AIStateMachine.h"
#include "GameLogic/GameLogic.h"
#include "GameLogic/LocomotorSet.h"
+#include "GameLogic/CrowdModel.h"
class AIGroup;
class AIStateMachine;
@@ -524,7 +525,20 @@ public:
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; }
+ { m_crowdLaneIdx = 0; m_crowdLaneOf = 0; m_crowdLaneSpace = 0.0f; m_hasPendingCrowdLat = FALSE; m_crowdPlanned.clear(); }
+
+ /** The route this member's next path is to be, planned by its group rather than searched for.
+
+ Each member's own search finds the shortest way from where it stands, and the shortest way
+ round the end of a wall is past the end of the wall, so every member of a group comes round
+ a corner over the same point and the group turns it in single file. The group plans one
+ route instead and hands each member that route moved sideways by its lane, corners and all,
+ so the outside lane takes the outside of the turn. It is the member's path, not a hint
+ beside one: the path that is followed, the path progress is measured against and the path
+ the band is built on are the same thing. It is used once, for the path the order asks for;
+ any later repath is the pathfinder's. A member whose planned lane could not be laid clear of
+ the ground has none, and searches for its own. */
+ void setPlannedCrowdRoute( const CrowdRoute& route ) { m_crowdPlanned = route; }
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
@@ -770,6 +784,7 @@ private:
/// throw the measured band away; the next frame that needs one measures the new route
void crowdReleaseCorridor( void );
+ Path *crowdPlannedPath( const CrowdRoute& planned, const Coord3D& destination ); ///< the planned route as a path from here, or NULL if it no longer fits
/** 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. */
@@ -854,6 +869,7 @@ private:
Int m_crowdSample; ///< whichsample of the band we were beside last frame (search hint; -1 = no band).
Int m_crowdQueued; ///< consecutiveframes spent braking or stuck behind somebody.
Int m_crowdSide; ///< whichside we prefer to pass on, +1 left, -1 right.
+ CrowdRoute m_crowdPlanned; ///< the path the group planned for us, waiting for the move to ask for one; empty = search.
/* The rest of the crowd state is transient and deliberately not saved, for the same reason the
band itself is not: a filter, a stuck count and a half-finished backing-out manoeuvre are all
rebuilt within a second of the load, and a saved one restarts a jam that is over. */
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
index b276a718f..44d36e4db 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
@@ -1715,6 +1715,166 @@ static void crowdClearLanes( std::list<Object *>& members )
}
}
+static const Int CROWD_TRUNK_DIAMETER = 6; ///< the widest the group's route is searched at, in cells
+static const Int CROWD_PLAN_STEPS = 4; ///< a lane closes to the group's line in quarters
+
+/** One member's lane of the group's route: every corner of `trunk` moved `offset` to its left,
+ and then the member's own spot at the end.
+
+ The corner moves along the bisector of the two legs that meet there, as far as keeps both legs
+ `offset` from the group's, so the lane runs parallel to the route through the turn and the
+ outside lane goes round the outside of it. Corners behind the member are skipped, so the
+ front of the group does not drive back to the start. Returns FALSE when the lane cannot be
+ laid, and the member searches for its own path.
+
+ Where the whole offset does not fit - a wall, a building - the lane closes towards the group's
+ line in quarters, and it closes over three corners, never one: each corner is held to the
+ narrowest of itself and its two neighbours. Measured corner by corner alone, a lane down a
+ street took the full offset, half, the full offset again and none, one after the other, and a
+ tank steered down that zigzag slows for every kink in it: the town crossing arrived 7% later on
+ average for that alone. */
+static Bool crowdPlanLane( Object *unit, const CrowdRoute& trunk, Real offset, const Coord3D& goal, CrowdRoute *out )
+{
+ out->clear();
+
+ AIUpdateInterface *ai = unit->getAIUpdateInterface();
+ const LocomotorSet& loco = ai->getLocomotorSet();
+ const LocomotorSurfaceTypeMask surfaces = loco.getValidSurfaces();
+ const Bool crusher = unit->getCrusherLevel() > 0;
+ Pathfinder *pf = TheAI->pathfinder();
+
+ //--- how far each corner can move out on its own ------------------------------------------------
+ const Int corners = (Int)trunk.size();
+ std::vector<Coord2D> shifts( corners );
+ std::vector<Int> fits( corners, CROWD_PLAN_STEPS );
+ for (Int k = 1; k + 1 < corners; k++)
+ {
+ const CrowdRoutePoint& a = trunk[ k - 1 ];
+ const CrowdRoutePoint& c = trunk[ k ];
+ const CrowdRoutePoint& b = trunk[ k + 1 ];
+ fits[ k ] = 0;
+ shifts[ k ].x = 0.0f;
+ shifts[ k ].y = 0.0f;
+
+ // a corner beside a deck edge stays on the group's line: see the chain below
+ if (a.layer != c.layer || b.layer != c.layer)
+ continue;
+ if (!Crowd_laneCorner( a.pos, c.pos, b.pos, offset, &shifts[ k ] ))
+ continue;
+
+ for (Int q = CROWD_PLAN_STEPS; q > 0; q--)
+ {
+ Coord3D p = c.pos;
+ p.x += shifts[ k ].x * (Real)q / (Real)CROWD_PLAN_STEPS;
+ p.y += shifts[ k ].y * (Real)q / (Real)CROWD_PLAN_STEPS;
+ p.z = TheTerrainLogic->getLayerHeight( p.x, p.y, c.layer );
+ if (pf->validMovementPosition( crusher, c.layer, loco, &p )
+ && pf->isLinePassable( unit, surfaces, c.layer, c.pos, p, false, true ))
+ {
+ fits[ k ] = q;
+ break;
+ }
+ }
+ }
+
+ //--- and no wider at a corner than at either neighbour ------------------------------------------
+ std::vector<Int> shares( fits );
+ for (Int k = 1; k + 1 < corners; k++)
+ {
+ if (fits[ k - 1 ] < shares[ k ]) shares[ k ] = fits[ k - 1 ];
+ if (fits[ k + 1 ] < shares[ k ]) shares[ k ] = fits[ k + 1 ];
+ }
+
+ //--- then the lane itself, leg by leg from where the member stands -------------------------------
+ Coord3D prev = *unit->getPosition();
+ PathfindLayerEnum prevLayer = unit->getLayer();
+ Int prevCorner = -1; // which of the group's corners prev was laid off, if any
+ for (Int k = 1; k + 1 < corners; k++)
+ {
+ const CrowdRoutePoint& a = trunk[ k - 1 ];
+ const CrowdRoutePoint& c = trunk[ k ];
+
+ Coord2D in;
+ in.x = c.pos.x - a.pos.x;
+ in.y = c.pos.y - a.pos.y;
+ if ((c.pos.x - prev.x) * in.x + (c.pos.y - prev.y) * in.y <= 0.0f)
+ continue; // already past it
+
+ /* A leg that changes deck is driven as the group drives it or not at all. Nothing checks a
+ straight line from one deck to another, and a lane leaving the approach a body width off the
+ group's line reaches the abutment across the riverbank beside it. */
+ const Bool changesDeck = prevLayer != c.layer;
+ Bool placed = FALSE;
+ for (Int q = changesDeck ? 0 : shares[ k ]; q >= 0 && !placed; q--)
+ {
+ CrowdRoutePoint p;
+ p.layer = c.layer;
+ p.pos = c.pos;
+ p.pos.x += shifts[ k ].x * (Real)q / (Real)CROWD_PLAN_STEPS;
+ p.pos.y += shifts[ k ].y * (Real)q / (Real)CROWD_PLAN_STEPS;
+ p.pos.z = TheTerrainLogic->getLayerHeight( p.pos.x, p.pos.y, p.layer );
+
+ // the group's own leg, corner to corner, is the wide search's answer and is not asked again:
+ // that search measures clearance by diameter, and a straight-line test by body can refuse it
+ const Bool groupLeg = q == 0 && prev.x == a.pos.x && prev.y == a.pos.y;
+ if (!groupLeg && (changesDeck
+ || !pf->isLinePassable( unit, surfaces, p.layer, prev, p.pos, false, true )))
+ continue;
+ out->push_back( p );
+ prev = p.pos;
+ prevLayer = p.layer;
+ prevCorner = k;
+ placed = TRUE;
+ }
+
+ /* Nothing on this corner can be driven to from where the lane is, so the lane closes up to
+ the group's previous corner first and takes this one from there - the outside lane at a gate
+ between two fences, which it goes through behind the others and opens out again after.
+ Stepping back in to the corner the lane was laid off is the leg the first pass already
+ measured out from it, so it is not asked again; from anywhere else it is. */
+ if (!placed && a.layer == prevLayer
+ && (prevCorner == k - 1 || pf->isLinePassable( unit, surfaces, a.layer, prev, a.pos, false, true )))
+ {
+ out->push_back( a );
+ out->push_back( c );
+ prev = c.pos;
+ prevLayer = c.layer;
+ prevCorner = k;
+ placed = TRUE;
+ }
+ if (!placed)
+ return FALSE;
+ }
+
+ /* The route runs on to the click, and a member whose own spot is short of the click, or off to
+ one side of it, stops at the corner nearest its spot: driving the lane to its end and then back
+ sent a tank two hundred feet past its place and round again. */
+ while (out->size() >= 2)
+ {
+ const Coord3D& last = out->back().pos;
+ const Coord3D& before = (*out)[ out->size() - 2 ].pos;
+ const Real lastSqr = (last.x - goal.x) * (last.x - goal.x) + (last.y - goal.y) * (last.y - goal.y);
+ const Real beforeSqr = (before.x - goal.x) * (before.x - goal.x) + (before.y - goal.y) * (before.y - goal.y);
+ if (beforeSqr >= lastSqr)
+ break;
+ out->pop_back();
+ }
+
+ // home: the member's own spot round the click, from the last corner it can see it from
+ const PathfindLayerEnum goalLayer = TheTerrainLogic->getLayerForDestination( &goal );
+ while (!out->empty() && (out->back().layer != goalLayer
+ || !pf->isLinePassable( unit, surfaces, goalLayer, out->back().pos, goal, false, true )))
+ out->pop_back();
+ if (out->empty())
+ return FALSE;
+
+ CrowdRoutePoint home;
+ home.pos = goal;
+ home.layer = goalLayer;
+ out->push_back( home );
+ return TRUE;
+}
+
/** Hand every member of a group the distance it should sit off the centre of the road, for the
crowd model only.
@@ -2023,6 +2183,12 @@ void AIGroup::groupMoveToPosition( const Coord3D *p_posIn, Bool addWaypoint, Com
const Coord3D groupCenter = center;
Bool spreadLanes = groupDir.length() > 1.0f;
crowdClearLanes( m_memberList ); // this order replaces the last one, spread or no spread
+
+ // the group's one route and every member's place across it, for crowdPlanLane below
+ CrowdRoute trunkRoute;
+ std::vector<Object *> laneMembers;
+ std::vector<Real> laneOffsets;
+ Real laneSpacing = 0.0f;
if (spreadLanes)
{
groupDir.normalize();
@@ -2082,6 +2248,11 @@ void AIGroup::groupMoveToPosition( const Coord3D *p_posIn, Bool addWaypoint, Com
it carries rather than as many as its car park did. */
across[i].obj->getAIUpdateInterface()->setPendingCrowdLane( i, count, spacing );
+ // centred on the group's route, which its wide search already put in the middle of the road
+ laneMembers.push_back( across[i].obj );
+ laneOffsets.push_back( ((Real)lane - (Real)(lanes - 1) * 0.5f) * spacing );
+ laneSpacing = spacing;
+
if (TheGlobalData->m_showLanes)
{
DEBUG_LOG(("SHOWLANES unit %d lat=%.1f lane %d/%d offset=%.1f u=%.2f\n",
@@ -2123,6 +2294,70 @@ void AIGroup::groupMoveToPosition( const Coord3D *p_posIn, Bool addWaypoint, Com
}
TheAI->pathfinder()->floodGroupGoals( &goalPos, floodMembers, floodGoals );
spreadAirborneGoals( goalPos, airMembers, airGoals );
+
+ /* The route every vehicle's lane is laid across: see setPlannedCrowdRoute. Retail's group
+ trunk, the wide search that keeps a column clear of walls, from the middle of the group,
+ where the lane offsets were measured. Narrower when that finds nothing, and aimed at the
+ first free cell the flood handed out when the click itself is on a building. */
+ if (!laneMembers.empty())
+ {
+ // from the member standing nearest the middle: the middle itself can be a cliff edge or a
+ // rock, which the search starts from as ground nothing else is connected to
+ Object *trunkUnit = NULL;
+ Real bestSqr = 1.0e30f;
+ for (Int m = 0; m < (Int)laneMembers.size(); m++)
+ {
+ const Coord3D *p = laneMembers[m]->getPosition();
+ const Real d = (p->x - groupCenter.x) * (p->x - groupCenter.x) + (p->y - groupCenter.y) * (p->y - groupCenter.y);
+ if (d < bestSqr && !laneMembers[m]->isKindOf( KINDOF_INFANTRY ))
+ {
+ bestSqr = d;
+ trunkUnit = laneMembers[m];
+ }
+ }
+ const Coord3D trunkStart = (trunkUnit != NULL) ? *trunkUnit->getPosition() : groupCenter;
+
+ Path *trunk = NULL;
+ for (Int attempt = 0; attempt < 2 && trunk == NULL; attempt++)
+ {
+ const Coord3D *aim = (attempt == 0) ? pos : (floodGoals.empty() ? NULL : &floodGoals[0]);
+ if (aim == NULL)
+ break;
+ for (Int diameter = CROWD_TRUNK_DIAMETER; diameter >= 2 && trunk == NULL; diameter -= 2)
+ trunk = TheAI->pathfinder()->findGroundPath( &trunkStart, aim, diameter, false );
+ }
+ if (trunk != NULL)
+ {
+ Crowd_routeFromPath( trunk, &trunkRoute );
+ trunk->deleteInstance();
+
+ /* Not over a bridge. Every lane has to close to the group's line to get onto a deck, and
+ closing them all at the corner before it sends the whole group at one point at once:
+ twenty Crusaders over the Kandahar bridge on Golden Oasis took 2.3 times the blocked
+ frames their own paths do, and one of them never got across. */
+ for (Int k = 0; k < (Int)trunkRoute.size(); k++)
+ {
+ if (trunkRoute[k].layer > LAYER_GROUND)
+ {
+ trunkRoute.clear();
+ break;
+ }
+ }
+ }
+ if (TheGlobalData->m_showLanes)
+ {
+ Real routeLen = 0.0f;
+ for (Int k = 1; k < (Int)trunkRoute.size(); k++)
+ {
+ const Real dx = trunkRoute[k].pos.x - trunkRoute[k-1].pos.x;
+ const Real dy = trunkRoute[k].pos.y - trunkRoute[k-1].pos.y;
+ routeLen += (Real)sqrt( dx * dx + dy * dy );
+ }
+ const Real sx = pos->x - trunkStart.x, sy = pos->y - trunkStart.y;
+ DEBUG_LOG(("SHOWLANES group route: %d corners, %.0f long against %.0f straight\n", (Int)trunkRoute.size(),
+ routeLen, (Real)sqrt( sx * sx + sy * sy )));
+ }
+ }
}
Int floodCursor = 0;
Int airCursor = 0;
@@ -2154,6 +2389,29 @@ void AIGroup::groupMoveToPosition( const Coord3D *p_posIn, Bool addWaypoint, Com
dest = floodGoals[floodCursor++];
else if (airCursor < (Int)airMembers.size() && airMembers[airCursor] == theUnit)
dest = airGoals[airCursor++];
+
+ // a vehicle drives its lane of the group's route; a foot soldier walks through the crowd
+ if (!trunkRoute.empty() && !theUnit->isKindOf( KINDOF_INFANTRY ) && ai->isDoingGroundMovement())
+ {
+ for (Int m = 0; m < (Int)laneMembers.size(); m++)
+ {
+ if (laneMembers[m] != theUnit)
+ continue;
+ CrowdRoute lane;
+ const Bool laid = crowdPlanLane( theUnit, trunkRoute, laneOffsets[m], dest, &lane );
+ if (TheGlobalData->m_showLanes)
+ DEBUG_LOG(("SHOWLANES plan: unit %d offset %.1f %s, %d corners of %d\n", theUnit->getID(),
+ laneOffsets[m], laid ? "laid" : "refused", (Int)lane.size(), (Int)trunkRoute.size()));
+ if (laid)
+ {
+ ai->setPlannedCrowdRoute( lane );
+ // the lane is the path itself now, so the band rides its centre and nothing re-fits it
+ ai->setPendingCrowdLat( 0.0f );
+ ai->setPendingCrowdLane( 0, 1, laneSpacing );
+ }
+ break;
+ }
+ }
}
else
computeIndividualDestination( &dest, &goalPos, theUnit, &center, isFormation );
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/CrowdModel.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/CrowdModel.cpp
index b11ebb95d..5c5f340d8 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/CrowdModel.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/CrowdModel.cpp
@@ -68,6 +68,54 @@ static Real crowdExtent( const Object *obj, const LocomotorSet& locomotorSet, Pa
return room > 0.0f ? room : 0.0f;
}
+//-------------------------------------------------------------------------------------------------
+void Crowd_routeFromPath( Path *path, CrowdRoute *out )
+{
+ out->clear();
+ for (const PathNode *n = path->getFirstNode(); n; n = n->getNextOptimized())
+ {
+ CrowdRoutePoint p;
+ p.pos = *n->getPosition();
+ p.layer = n->getLayer();
+ out->push_back( p );
+ }
+}
+
+static const Real CROWD_LANE_MIN_COS = 0.5f; ///< a hairpin stretches a corner's offset no more than twice
+
+//-------------------------------------------------------------------------------------------------
+Bool Crowd_laneCorner( const Coord3D& a, const Coord3D& c, const Coord3D& b, Real offset, Coord2D *shift )
+{
+ Coord2D in, onward;
+ in.x = c.x - a.x; in.y = c.y - a.y;
+ onward.x = b.x - c.x; onward.y = b.y - c.y;
+ if (in.length() < 0.01f || onward.length() < 0.01f)
+ return FALSE;
+ in.normalize();
+ onward.normalize();
+
+ Coord2D miter;
+ miter.x = -in.y - onward.y;
+ miter.y = in.x + onward.x;
+ Real stretch = 1.0f;
+ if (miter.length() < 0.01f)
+ {
+ // the route doubles straight back: the lane keeps the side it was on
+ miter.x = -in.y;
+ miter.y = in.x;
+ }
+ else
+ {
+ miter.normalize();
+ const Real cosHalf = miter.x * -in.y + miter.y * in.x;
+ stretch = 1.0f / ((cosHalf > CROWD_LANE_MIN_COS) ? cosHalf : CROWD_LANE_MIN_COS);
+ }
+ const Real reach = offset * stretch;
+ shift->x = miter.x * reach;
+ shift->y = miter.y * reach;
+ return TRUE;
+}
+
//-------------------------------------------------------------------------------------------------
Bool CrowdCorridor::build( const Object *obj, const LocomotorSet& locomotorSet, Path *path )
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
index 25911b41b..23575b449 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
@@ -1652,6 +1652,7 @@ static const Real CROWD_PASS_CLEAR = 6.0f; ///< room a passing lane leaves besi
static const Real CROWD_PASS_TIGHT = 1.5f; ///< and the room it settles for rather than queue
static const Int CROWD_PASS_RETRY = 10; ///< queued this long: ask to pass again, hold or no hold
static const Real CROWD_TAPER_DIST = PATHFIND_CELL_SIZE_F * 8.0f; ///< the band closes over the last of the route
+static const Real CROWD_PLAN_END_SLACK = PATHFIND_CELL_SIZE_F * 3.0f; ///< how far the move state may move a planned route's end and it still be the same order
static const Int CROWD_BRAKE_FRAMES = 8; ///< frames of closing time a brake is allowed to read
static const Int CROWD_FAN_FRAMES = 12; ///< held up this long before spreading out
static const Real CROWD_FAN_RATE = 0.8f; ///< and then sideways at this much a frame
@@ -1966,6 +1967,10 @@ Bool AIUpdateInterface::computePath( PathfindServicesInterface *pathServices, Co
destroyPath();
}
+ // the group's plan is for the path this order asks for and no other, whichever way it is answered
+ CrowdRoute planned;
+ planned.swap( m_crowdPlanned );
+
if (canComputeQuickPath())
{
return computeQuickPath(destination);
@@ -2010,8 +2015,15 @@ Bool AIUpdateInterface::computePath( PathfindServicesInterface *pathServices, Co
return computeQuickPath(destination);
}
+ if (!planned.empty() && !m_isBlockedAndStuck)
+ theNewPath = crowdPlannedPath( planned, originalDestination );
+
PathfindLayerEnum destinationLayer = TheTerrainLogic->getLayerForDestination(destination);
- if (TheAI->pathfinder()->validMovementPosition( getObject()->getCrusherLevel()>0, destinationLayer, m_locomotorSet, destination ) == FALSE)
+ if (theNewPath != NULL)
+ {
+ // the lane the group planned for us: see setPlannedCrowdRoute
+ }
+ else if (TheAI->pathfinder()->validMovementPosition( getObject()->getCrusherLevel()>0, destinationLayer, m_locomotorSet, destination ) == FALSE)
{
theNewPath = NULL;
}
@@ -2081,6 +2093,37 @@ Bool AIUpdateInterface::computePath( PathfindServicesInterface *pathServices, Co
return FALSE;
}
+//-------------------------------------------------------------------------------------------------
+/** The route the group planned for this unit, as a path from where the unit is now.
+
+ The plan was laid at order time from where the unit stood then, and the path is asked for a
+ frame or several later, so two things are checked again rather than trusted: the first leg,
+ from here, and the end, which the move state may have nudged onto free ground since. A plan
+ that fails either is dropped for a search, which is what the unit would have had anyway. */
+//-------------------------------------------------------------------------------------------------
+Path *AIUpdateInterface::crowdPlannedPath( const CrowdRoute& planned, const Coord3D& destination )
+{
+ Object *self = getObject();
+ const CrowdRoutePoint& last = planned.back();
+ const Real endDx = last.pos.x - destination.x;
+ const Real endDy = last.pos.y - destination.y;
+ if (endDx * endDx + endDy * endDy > CROWD_PLAN_END_SLACK * CROWD_PLAN_END_SLACK)
+ return NULL; // a different order from the one this was planned for
+
+ const Coord3D *myPos = self->getPosition();
+ if (!TheAI->pathfinder()->isLinePassable( self, m_locomotorSet.getValidSurfaces(), self->getLayer(),
+ *myPos, planned.front().pos, false, true ))
+ return NULL;
+
+ Path *path = newInstance( Path );
+ path->markOptimized();
+ path->appendNode( myPos, self->getLayer() );
+ for (Int k = 0; k + 1 < (Int)planned.size(); k++)
+ path->appendNode( &planned[ k ].pos, planned[ k ].layer );
+ path->appendNode( &destination, TheTerrainLogic->getLayerForDestination( &destination ) );
+ return path;
+}
+
//-------------------------------------------------------------------------------------------------
/**
* Invoke the pathfinder to compute a path to attack the current victim.
@@ -2371,7 +2414,7 @@ void AIUpdateInterface::crowdReleaseCorridor( void )
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)
+ if (m_crowdLaneOf >= 1) // 1 is a member driving a lane its group planned: see setPlannedCrowdRoute
{
m_pendingCrowdLat = 0.0f;
m_hasPendingCrowdLat = TRUE;
@@ -6957,7 +7000,7 @@ void AIUpdateInterface::crc( Xfer *x )
void AIUpdateInterface::xfer( Xfer *xfer )
{
// version
- const XferVersion currentVersion = 14;
+ const XferVersion currentVersion = 15;
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
@@ -7259,6 +7302,22 @@ void AIUpdateInterface::xfer( Xfer *xfer )
xfer->xferBool(&m_hasSalvageReturnPosition);
}
+ if (version >= 15)
+ {
+ // a group's planned lane, which a save can fall between the order and the path it is for
+ UnsignedShort corners = (UnsignedShort)m_crowdPlanned.size();
+ xfer->xferUnsignedShort(&corners);
+ if (xfer->getXferMode() == XFER_LOAD)
+ m_crowdPlanned.resize( corners );
+ for (Int k = 0; k < (Int)corners; k++)
+ {
+ xfer->xferCoord3D(&m_crowdPlanned[ k ].pos);
+ Int layer = (Int)m_crowdPlanned[ k ].layer;
+ xfer->xferInt(&layer);
+ m_crowdPlanned[ k ].layer = (PathfindLayerEnum)layer;
+ }
+ }
+
} // end xfer
// ------------------------------------------------------------------------------------------------
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 56563abf3..afb3099af 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -12016,6 +12016,40 @@ TEST(a_group_is_never_more_than_five_lanes_wide)
CHECK_EQ( Crowd_laneCount( -50.0f, body, 4 ), 1 );
}
+TEST(a_lane_goes_round_the_outside_of_a_turn_parallel_to_the_route)
+{
+ Coord3D a, c, b;
+ a.set( 0.0f, 0.0f, 0.0f );
+ c.set( 100.0f, 0.0f, 0.0f );
+ Coord2D shift;
+
+ // straight on: the lane is the plain left normal, no stretch
+ b.set( 200.0f, 0.0f, 0.0f );
+ CHECK( Crowd_laneCorner( a, c, b, 10.0f, &shift ) );
+ CHECK_NEAR( shift.x, 0.0f, 0.001f );
+ CHECK_NEAR( shift.y, 10.0f, 0.001f );
+
+ // a right-angle turn to the right: the left lane is the outside one, and its corner sits out on
+ // the diagonal, ten from both legs - the red line of the owner's drawing, not the tip of the wall
+ b.set( 100.0f, -100.0f, 0.0f );
+ CHECK( Crowd_laneCorner( a, c, b, 10.0f, &shift ) );
+ CHECK_NEAR( shift.x, 10.0f, 0.001f );
+ CHECK_NEAR( shift.y, 10.0f, 0.001f );
+
+ // the right lane of the same turn is the inside one, pulled in off the tip by the same ten
+ CHECK( Crowd_laneCorner( a, c, b, -10.0f, &shift ) );
+ CHECK_NEAR( shift.x, -10.0f, 0.001f );
+ CHECK_NEAR( shift.y, -10.0f, 0.001f );
+
+ // a hairpin stretches the offset no further than twice
+ b.set( 0.0f, -1.0f, 0.0f );
+ CHECK( Crowd_laneCorner( a, c, b, 10.0f, &shift ) );
+ CHECK( shift.length() <= 20.001f );
+
+ // a leg of no length has no direction to be beside
+ CHECK( !Crowd_laneCorner( a, a, b, 10.0f, &shift ) );
+}
+
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