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.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
refactor(ai): take the group movement rework back out
Olcay Seyganad2c878f61de
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8eede3d82..9710f1c94 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -472,10 +472,6 @@ found and fixed — EA's own, not port damage.**- Our own rescue for narrow routes searched 140,513 squares in 285ms; it is gone.- The coarse route is widened along its whole length, not just at the start.- The main search stops after 20,000 squares and hands back a partial route.-- Units heading the same way take the lane beside the traffic instead of joining the back of it. Ground another unit is already driving over costs a little to plan through, so a column spreads into parallel lanes at the gate it forms at. Over twenty-four full matches the time units spend standing behind each other dropped by a third, and the searches to do it cost 6% more squares - the price is capped, or a crowded route would be worth walking around the map to avoid.-- A unit that has stood behind another one for a second and a half stops waiting and plans its own way round it. For that one route, ground somebody else is parked on costs real money, so the tank at the back pulls out of the line, drives past the ones standing in it and rejoins in front, instead of idling until the line decides to move. Two things had been holding it there. The engine only counted you as blocked while you were actually touching the unit ahead, and a tank in a queue does not touch every frame - it creeps up, nudges, backs off its speed, drifts apart, touches again - so the count kept resetting to zero and the two-second rule that asks for a new route never fired at all; it now decays instead of resetting, so touching more often than you clear still gets you there. And a unit approaching something to shoot refused to re-plan for as long as its target stood still, which is precisely the case where a dozen tanks arrive at the same building and stack up behind each other. Over forty-eight full matches the time units spend standing behind each other fell on both halves of the batch, and the worst jam in it was halved; the searches that do it never once came back with no route.-- A group you send across the map travels abreast instead of nose to tail. Up to forty units it is given one corridor wide enough for the whole group and split into columns, so it crosses a gap side by side and the outside of the column takes the wider way round. Where the ground is too tight for a full-width corridor - a bridge, a ramp, a gap between two cliffs - the group is given the widest corridor that fits instead of being dropped back to every unit for itself, which is what used to turn exactly those crossings into a single queue. The columns then close up to whatever width the ground allows and open out again on the far side, and a unit whose place in the column would put it in a cliff or a wall takes the middle of the road instead of driving into the rock and stopping. The gap between columns is measured off the units you actually selected rather than fixed at a guess that was narrower than a tank, so a group of tanks spreads wider than a group of scout cars and side by side means side by side instead of a trip spent shoving. Two units sharing a column drive one line, in file, which is what a column is for, and they arrive on that same spacing rather than piling onto one spot. The route itself is straightened as it is handed out: a corner is only driven if it is a real corner, so a group crossing open ground goes in long straight runs rather than nodding left and right the whole way, which is both faster and how a column of tanks is supposed to look. That corridor is only skipped for selections larger than any hand ever drags a box around.-- Routes now look ahead in time, not just in space. Every unit on the move leaves a note of *when* it expects to be on each square and which way it will be facing, and a route that would put you on a square somebody else wants at that same moment, coming the other way, costs extra to plan. Traffic going your way is free - the unit in front of you is about to not be there, and a queue along one road is what a road is for. So two groups sent through each other pick their gaps before they meet instead of grinding to a halt nose to nose in the middle. In the model of this movement code, sixteen units crossing each other on open ground cut the time spent standing still by a quarter, arrived sooner, and the planning itself cost under one percent more.- Long turns went from 513 to 201, and the worst from 2,976ms to 243ms.- The distance guess now prices diagonals and turns, so the search actually steers.- The straight-line shortcut only runs from a square closer than anything tried before.@@ -492,8 +488,7 @@ found and fixed — EA's own, not port damage.**- The terrain's lowest-point sweep is read along the grain now.- A computer player choosing where to put a building could freeze the picture for a twentieth of a second. When the spot in its plan is taken it looks outwards for a free one, and on a skirmish map that search reaches most of the way across the terrain: three and a half thousand candidate positions, each a full check of whether a building fits there, all inside a single frame. It now walks one ring of that search per frame and carries on next frame from where it stopped, so it settles on the same spot it always would have, a fraction of a second later.- An angry mob added up its members' health every frame, and so did every other mob on the map. Seventy-three of them in one frame cost 32 milliseconds - two frames of budget spent on a health bar and a rule about clicking. Each mob now does it five times a second, and they take turns, so the cost never lands on one frame.-- A single unit ordered to move was given a formation. The wide corridor a group gets, so it can travel abreast and take the wider way round, was being computed for selections of one, at twice the cost of that unit's own route and to no purpose. One unit now just drives.-- Those three together, over four seven-minute four-way battles: frames that missed a sixtieth of a second fell from 15 to 6, frames over a thirtieth from 3 to 1, and the slowest one frame in a thousand from 13.3 milliseconds to 10.5. The average is unchanged, which is the point - none of this was traded for anything.+- Those two, together with a third that has since been taken out again with the rest of the group movement work, over four seven-minute four-way battles: frames that missed a sixtieth of a second fell from 15 to 6, frames over a thirtieth from 3 to 1, and the slowest one frame in a thousand from 13.3 milliseconds to 10.5. The average is unchanged, which is the point - none of this was traded for anything.- Every unit on the move re-checked the entire road ahead of it, every single frame. A tank sent across the map holds one long straight leg of its route, and each frame it asked whether that whole leg - three hundred squares of it - was clear, walking every square and testing a block of twenty-five around each one. That one question was a sixth of the game's entire running time. It now looks twenty squares ahead, which is thirty frames of driving, and asks again next frame like it always did. Units also drive better for it, not worse: over four battles the time spent standing behind each other fell 10% and the number left properly stuck fell from 296 a match to 10.- Sending a group across the map could freeze the picture for a twenty-fifth of a second. The wide corridor a group travels down is its own search, the most expensive kind the game runs, and it was the only one in the pathfinder allowed to run without a limit - a three-unit team once spent 40 milliseconds on one. It now gives up after a set amount of looking and the group falls back to individual routes, which is what happens on ground too tight for a corridor anyway.- The movement code was timing itself thirty thousand times a frame. Reading the clock that often cost 4.6% of the whole game to measure something already counted for free.@@ -526,14 +521,12 @@ found and fixed — EA's own, not port damage.**- That found every multiplayer replay falsely accusing itself of desync since 2003.- Every fix was proved by putting the bug back and watching the test fail.- No debugger here: a crash symboliser, a sampling profiler, probes in live matches.-- Reverted and recorded: wide FOV, four pathfinding experiments, tree shadows.+- Reverted and recorded: wide FOV, the whole group movement rework, tree shadows.- The three-piece command bar was reverted once, for having nowhere to put the painting of the bar, and is back now that the painting has been cut into three to match. Each piece is fitted by matching it against the artwork it was cut from rather than by eye: the eyeballed fit was four percent out, which nobody sees on the metal and everybody sees on the money readout.- The opponent's decisions are argued with a number: 20 headless matches per change, same seeds, win rate and match length before and after.- That caught two changes that looked right and measured catastrophic - a wave that waited jammed the whole production line, and a retreat rule that counted buildings as gunfire sent every attack home. Both showed up as twenty matches with zero kills.- Massing an army before attacking is written and measured but switched off: it needs somewhere to wait that is not the production queue.-- The self-play harness cannot see a traffic jam. Leaving a queue was measured over ninety-six matches and thirty-three of the forty-eight maps came out bit-identical, because a computer opponent moves five units at a time and never forms the queue a human makes by dragging a box round fifteen tanks. Where a jam did occur it got better, and nothing regressed, but the honest statement is that the number is thin: the rule fires about twice a match against the machine, and the case it was written for is one a person creates. Each unit that takes the way round says so in the log.-- Then it was asked to swing wider, and four ways of doing that were tried and thrown away. Charging more than double for driving over somebody gave the same routes to one square in fifty-six thousand, and so did looking half again as far ahead: past the point where going round is cheaper than going through, paying more does not move the line further out. Planning a lane's clearance around the traffic, and giving up on the queue half a second sooner, both did change the routes, and both made units wait longer than doing nothing at all - spread them harder and they park across each other, which is the same wall the lane-picking above ran into. A unit that leaves a queue has to leave it late and by the shortest way round, or it is not saving anyone time.-- Overtaking was built after that and taken out again. A unit held up by traffic going its own way would steer a tank width or two sideways and drive in that lane, which is what a person does in a queue and looks exactly right when you watch it happen. It got argued with the same way as everything else: forty matches on maps its numbers had never been fitted to, against the same build without it. Five of the forty were thrown out because two batches had been run at once and fought over the same generated map, and the first reading of the results was mostly made of matches that never started. Of the thirty-five left, nineteen came out identical, ten of the rest got better and six got worse, and one single match carried five sixths of the average improvement. The time units spend properly stuck went the wrong way, which is the one column the thing had been rebuilt to protect. EA wrote a version of this in 2003 and switched theirs off too.+- The whole of the group movement work is out of the game again, and that is the largest single thing this list has taken back. Lanes priced by how many other units already plan to drive over a square, a unit giving up on a queue and planning its way round, the shared corridor a selection travels down, routes priced by when somebody else will be standing on a square, spacing measured off the units you selected: all of it built, all of it measured, all of it removed. What sank it was that the self-play harness cannot see a traffic jam. A computer opponent moves five units at a time and never forms the queue a person makes by dragging a box round fifteen tanks, so thirty-three of forty-eight maps came out bit-identical over ninety-six matches and the rule fired about twice a match. Then it was asked to swing wider, and four ways of doing that were tried and thrown away - two changed nothing at all, two made units wait longer than doing nothing. Overtaking went the same way over forty matches, with the time units spend properly stuck moving in the wrong direction, which is the one column it had been rebuilt to protect. EA wrote a version of that in 2003 and switched theirs off too. The speed work underneath it stayed; the behaviour is retail's again, and this is a problem to come back to with a way of measuring it that a machine opponent cannot flatter.- Bugs deliberately left alone are pinned by a test documenting the behaviour.- Infantry shadows were fixed in the wrong place first, and nobody has eyeballed them yet.- The shade under smoke vanished between builds and was rewritten from these notes.@@ -544,8 +537,7 @@ found and fixed — EA's own, not port damage.**- One thing did come out of it: sixteen thousand five hundred lock operations per frame, all on the same lock, every time a scrap of memory is taken or given back. That is the next thing worth chasing.- Then the question changed from "how fast" to "how steady", and the stopwatch had to change with it: an average is exactly the number that hides a stutter. The game now keeps the shape of every frame it draws and reports the worst ones, with the name of what took the time. The building-foundation freeze above was found that way, in one run, having been in the game since 2003.- The self-play harness can set up teams now, which it never could: every computer opponent used to fight every other one. Eight players in a free-for-all spread the fighting over the whole map, and that is not the load anybody complains about - 4v4 puts every unit on one of two fronts, which is where they bunch up. That is now one switch, and it is how the numbers above were checked at the heavy end.-- A second pass with the same tool named three more, and the log did the work each time rather than anyone guessing: the computer player's search for somewhere to build, the angry mob's health count, and a group order for one unit. A fourth is named and not fixed - a computer team sent across the map on its approach path spends 40 milliseconds finding the wide corridor for it, once or twice a match, and that is one search rather than a mistake repeated. It is the next one.-- Two switches that were written into the code years ago, described in a comment and then never connected to anything, now work: one turns the shared group corridor off, the other turns off pricing a route by when other units will be standing in it. Both matter because a change to movement can only be argued with a before and after in the same build - two separate builds differ in more than the thing being measured. The first thing they measured: turning the corridor off costs 13% more time with units standing behind each other, and saves nine tenths of the stutters.+- A second pass with the same tool named two more, and the log did the work each time rather than anyone guessing: the computer player's search for somewhere to build, and the angry mob's health count. A third is named and not fixed - a computer team sent across the map on its approach path spends 40 milliseconds finding the wide corridor for it, once or twice a match, and that is one search rather than a mistake repeated. It is the next one.- Group movement was asked one more question and answered no. The idea was to stop treating the route as a line and treat it as a band: every unit holds a sideways position inside it and drifts away from whichever side ahead is busiest, so a queue drains outwards where there is room and files up where there is not. It was built in the movement sandbox and measured against the columns the game ships, 96 layouts counted one at a time, at four different drift speeds. It is worse at every speed, and steadily worse the harder it pushes. The columns stay.---diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.hindex e8eaa5a17..6c999f454 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h@@ -114,8 +114,6 @@ public:Bool m_useDrawModuleLOD;Bool m_useHeatEffects;Bool m_useFpsLimit;- Bool m_useGroupPaths; ///< false = -nogrouppath: every unit solves its own path, no shared corridor- Bool m_useCrossingCost; ///< false = -nocrosstime: the reservation map is still kept, but no search reads itBool m_dumpAssetUsage;Int m_framesPerSecondLimit;Int m_chipSetType; ///<See W3DShaderManager::ChipsetType for optionsdiff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.hindex e07cda81a..d9cfb2a46 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AI.h@@ -1239,7 +1239,6 @@ private:UnsignedInt m_id; ///< the unique ID of this groupPath *m_groundPath; ///< Group ground path.- Int m_groundPathDiameter; ///< width in cells the group corridor was actually found at.mutable VecObjectID m_lastRequestedIDList; ///< this is used so we can return by reference, saving a copy};diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.hindex ab9c7ff31..04971e3bf 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h@@ -31,8 +31,6 @@#ifndef _PATHFIND_H_#define _PATHFIND_H_-#include <vector>-#include "Common/GameType.h"#include "Common/GameMemory.h"#include "Common/Snapshot.h"@@ -42,7 +40,6 @@class Bridge;class Object;-class Path;class Weapon;class PathfindZoneManager;@@ -198,40 +195,6 @@ struct ClosestPointOnPathInfoPathfindLayerEnum layer;};-//------------------------------------------------------------------------------------------------------------/**- * One live path's claim on one pathfind cell: the logic frame its owner expects to be standing- * there, and which way it is going when it arrives.- *- * The congestion map (Pathfinder::m_pathUsage) has no clock in it, so a cell somebody will drive- * over in ten seconds costs exactly as much as one they are sitting in now. That is the right- * answer for "is this ground spoken for" and the wrong one for "will we be on it at the same- * moment" - which is the whole difference between a shared road, where units queue nose to tail- * and everyone gets through, and a crossing, where two columns arrive from different directions- * and stop each other dead.- *- * The heading is why a reservation stores more than a time. Units following each other down one- * road are in the same cells at nearly the same moments and must not be charged for it; the- * expensive case is two of them wanting a cell at the same moment while going different ways.- */-struct PathReservation-{- const Path* m_owner; ///< the path that claimed this cell (identity only)- ICoord2D m_cell;- UnsignedInt m_frame; ///< logic frame the owner expects to reach m_cell- Real m_headingX; ///< normalized direction of travel on arrival- Real m_headingY;- Int m_nextInBucket; ///< next reservation in this hash bucket, -1 = end of chain-};--/// The crossing penalty, split out of examineNeighboringCells so the cap is testable.-extern Int Pathfinder_crossingPenalty( Int conflicts );--/// Do these two claims on one cell clash - same moment, and not going the same way?-extern Bool Pathfinder_reservationsClash( UnsignedInt frameA, Real headingAX, Real headingAY,- UnsignedInt frameB, Real headingBX, Real headingBY );-/*** This class encapsulates a "path" returned by the Pathfinder.*/@@ -241,7 +204,6 @@ public:Path();PathNode *getFirstNode( void ) { return m_path; }- const PathNode *getFirstNode( void ) const { return m_path; }PathNode *getLastNode( void ) { return m_pathTail; }void updateLastNode( const Coord3D *pos );@@ -266,10 +228,6 @@ public:/// Given a location, return closest location on path, and along-path dist to end as function resultvoid markOptimized(void) {m_isOptimized = true;}- Bool isUsageRegistered(void) const {return m_usageHead != NULL;}- const PathNode *getUsageHead(void) const {return m_usageHead;}- void setUsageHead(const PathNode *node) const {m_usageHead = node;}-protected:// snapshot interfacevirtual void crc( Xfer *xfer );@@ -284,7 +242,6 @@ protected:PathNode* m_pathTail;Bool m_isOptimized; ///< True if the path has been optimizedBool m_blockedByAlly; ///< An ally needs to move off of this path.- mutable const PathNode *m_usageHead; ///< First raw node still counted in Pathfinder's congestion map (NULL = not registered); cells behind the unit are released as it advances, ~Path releases the rest.// caching info for computePointOnPath.Bool m_cpopValid;Int m_cpopCountdown; ///< We only return the same cpop MAX_CPOP times. It is occasionally possible to get stuck.@@ -323,13 +280,6 @@ protected:UnsignedShort m_totalCost, m_costSoFar; ///< cost estimates for A* search- /* Distance travelled to reach this cell, in the same units as m_costSoFar but with none of the- penalties in it. The penalties are money, not ground: a detour taken to dodge someone must- not also make the search believe it arrives eight cells later than it does, and the crossing- cost below turns this number into an arrival frame. Only the main ground search maintains- it; every other search leaves it at zero and charges no crossing cost. */- UnsignedShort m_travelSoFar;-/// have to include cell's coordinates, since cells are often accessed via pointer onlyICoord2D m_pos;@@ -438,11 +388,9 @@ public:inline Bool getClosed(void) const {return m_info->m_closed;}inline UnsignedInt getCostSoFar(void) const {return m_info->m_costSoFar;}inline UnsignedInt getTotalCost(void) const {return m_info->m_totalCost;}- inline UnsignedInt getTravelSoFar(void) const {return m_info->m_travelSoFar;}inline void setCostSoFar(UnsignedInt cost) { if( m_info ) m_info->m_costSoFar = cost;}inline void setTotalCost(UnsignedInt cost) { if( m_info ) m_info->m_totalCost = cost;}- inline void setTravelSoFar(UnsignedInt travel) { if( m_info ) m_info->m_travelSoFar = travel;}void setParentCell(PathfindCell* parent);void clearParentCell(void);@@ -766,20 +714,16 @@ public:static const char *getProfileReport( void ); ///< "patch 12x/3.1 attack 4x/8.0", empty when idle//- // The same tallies summed over a whole match, plus the three counts that say whether a- // pathing change made things worse rather than merely different: searches that ran the cell- // pool dry, requests that came back with no path at all, and unit-frames lost to standing- // behind another unit. A headless batch prints these at the end of the run, so a change to- // path cost can be argued with numbers instead of with how the paths looked.+ // The same tallies summed over a whole match, plus the counts that say whether a pathing+ // change made things worse rather than merely different: searches that ran the cell pool dry,+ // requests that came back with no path at all, and unit-frames lost to standing behind+ // another unit. A headless batch prints these at the end of the run, so a change to path cost+ // can be argued with numbers instead of with how the paths looked.//static void resetMatchProfile( void ); ///< zero the match totals (start of a headless run)static const char *getMatchProfileReport( void );static void bumpNoPath( void ); ///< a path request came back emptystatic void bumpBlockedFrame( Bool stuck ); ///< one unit-frame spent blocked by another unit- static void bumpQueueDetour( void ); ///< a unit gave up on its queue and repathed round it-- void noteJam( const ICoord2D& cell ); ///< one blocked unit-frame, stamped where it happened- void decayJamMap( void ); ///< age the whole map; call once per logic framevoid processPathfindQueue(void); ///< Process some or all of the queued pathfinds.void forceMapRecalculation( ); ///< Force pathfind map recomputation. If region is given, only that area is recomputed@@ -820,21 +764,7 @@ public:Bool worldToCell( const Coord3D *pos, ICoord2D *cell ); ///< Given a world position, return grid cell coordinateconst ICoord2D *getExtent(void) const {return &m_extent.hi;}-- /// Congestion map: how many live unit paths run through each cell. A* charges extra per path, so- /// units ordered along the same route spread into parallel lanes instead of stacking on one line.- void registerPathUsage( const Path *path, const Object *obj );- void unregisterPathUsage( const Path *path );- void releasePathUsageBefore( const Path *path, const PathNode *node ); ///< unit has passed everything before node- void adjustPathUsage( const PathNode *from, const PathNode *to, Int delta ); ///< [from, to) raw nodes, +1/-1-- /// Reservation map: *when* each live path expects to be in each cell, and going which way. A*- /// charges extra where somebody else wants the same cell at the same moment on a different- /// heading, which is a crossing; two units queued along one road never pay it.- void reservePathTiming( const Path *path, const Object *obj ); ///< stamp arrival frames for the whole path- void releaseReservations( const Path *path, const PathNode *from, const PathNode *to ); ///< [from, to) raw nodes- Int countCrossingReservations( Int x, Int y, UnsignedInt frame, Real headingX, Real headingY ) const;-+void setIgnoreObstacleID( ObjectID objID ); ///< if non-zero, the pathfinder will ignore the given obstaclevoid setIgnoreUnderConstruction( Bool ignore ); ///< if true, half-built structures are not obstacles to this searchBool builderMayCross( const PathfindCell *cell ) const; ///< is this obstacle cell a structure the builder now searching may walk over?@@ -1002,27 +932,6 @@ private:/// This uses WAY too much memory. Should at least be array of pointers to cells w/ many fewer cellsPathfindCell *m_blockOfMapCells; ///< Pathfinding map - contains iconic representation of the mapPathfindCell **m_map; ///< Pathfinding map indexes - contains matrix indexing into the map.- UnsignedByte *m_pathUsage; ///< Congestion map, (hi.x+1)*(hi.y+1), indexed [x*(hi.y+1)+y]- Int getPathUsage( Int x, Int y ) const;-- UnsignedByte *m_jamMap; ///< Jam map, same shape and indexing: where units are actually stuck- Int m_jamCells; ///< non-zero cells in it, so an unjammed match never sweeps the map- UnsignedInt m_jamDecayFrame; ///< logic frame the last decay ran on- Int getJam( Int x, Int y ) const;-- //- // Reservation map. A dense per-cell array would be a second whole-map allocation to hold a few- // thousand live claims, so the claims live in a pool and are found through a fixed hash of the- // cell coordinate. The A* only ever probes it for a cell the congestion map already says a live- // path runs through - the two maps stamp exactly the same cells - so the hash is walked on the- // handful of cells where a crossing is even possible and nowhere else.- //- enum {PATH_RESERVATION_BUCKETS = 2048}; ///< power of two: the hash is masked, not divided- std::vector<PathReservation> m_reservations; ///< pool; a free entry is linked into m_firstFreeReservation- Int m_firstFreeReservation; ///< head of the free list, -1 = grow the pool- Int m_reservationBuckets[PATH_RESERVATION_BUCKETS]; ///< cell hash -> first reservation, -1 = empty- static Int reservationBucketOf( Int x, Int y );- void resetReservations( void ); ///< drop every claim: the map underneath them is goneIRegion2D m_extent; ///< Grid extent limitsIRegion2D m_logicalExtent; ///< Logical grid extent limitsdiff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.hindex 143b0a54d..5403115f4 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h@@ -478,17 +478,6 @@ public:Bool isQuickPathAvailable( const Coord3D *destination ) const; ///< does a path (using quick pathfind) exist between us and the destinationInt getNumFramesBlocked(void) const {return m_blockedFrames;}Bool isBlockedAndStuck(void) const {return m_isBlockedAndStuck;}- //- // m_blockedFrames is zeroed by a single frame without a collision, and a unit queued behind- // another one does not collide every frame - it creeps, touches, backs off its speed and- // touches again - so the counter almost never reaches the two seconds that force a repath,- // and the queue stands there. m_queueFrames counts the same collisions and decays instead- // of resetting, so a unit that touches more often than it clears climbs to the threshold.- // That is what says "I am in a line, not in traffic".- //- Bool isQueuedBehindUnits(void) const;- Int getNumFramesQueued(void) const {return m_queueFrames;}- void spendQueueCredit(void); ///< a path was computed; the detour has had its chanceBool canComputeQuickPath(void); ///< Returns true if we can quickly comput a path. Usually missiles & the like that just move straight to the destination.Bool computeQuickPath(const Coord3D *destination); ///< Computes a quick path to the destination.@@ -741,7 +730,6 @@ private:ICoord2D m_pathfindGoalCell; ///< Cell we are moving towards.ICoord2D m_pathfindCurCell; ///< Cell we are currently occupying.Int m_blockedFrames; ///< Number of frames we've been blocked.- Int m_queueFrames; ///< blocked frames, decayed rather than reset - see isQueuedBehindUnitsReal m_curMaxBlockedSpeed; ///< Max speed we can have and not run into blocking things.Real m_bumpSpeedLimit; ///< Max speed after bumping a unit.UnsignedInt m_ignoreCollisionsUntil; ///< Timer to cheat if we get stuck.diff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cppindex fc9734d04..4b28504c1 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp@@ -1252,33 +1252,6 @@ Int parseNoFPSLimit(char *args[], int num)return 1;}-/* -nogrouppath and -nocrosstime are the control arms for the two group-movement mechanisms this- fork added on top of retail, in one binary. Without them the only way to measure either is two- exes, and two exes differ in more than the thing being measured.-- -nogrouppath drops the shared corridor: every unit in a selection solves its own path and the- congestion cost is all that holds the column apart, which is what retail does for a formation- and what PathLab calls single mode. -nocrosstime keeps the reservation map but stops any- search reading it, so a route is priced for ground another unit's path covers and not for the- moment it will be there. */-Int parseNoGroupPath(char *args[], int num)-{- if (TheWritableGlobalData)- {- TheWritableGlobalData->m_useGroupPaths = FALSE;- }- return 1;-}--Int parseNoCrossingCost(char *args[], int num)-{- if (TheWritableGlobalData)- {- TheWritableGlobalData->m_useCrossingCost = FALSE;- }- return 1;-}-/* -headless is the unattended-run switch: no frame is ever drawn, the logic tick runs flat outinstead of being paced against wall clock, audio is silenced, and the process quits by itselfthe moment the match is decided. A window and a D3D device are still created - W3D reaches into@@ -1712,8 +1685,6 @@ static CommandLineParam params[] ={ "-slowframe", parseSlowFrame },{ "-teams", parseTeams },{ "-aislice", parseAISlice },- { "-nogrouppath", parseNoGroupPath },- { "-nocrosstime", parseNoCrossingCost },{ "-replay", parseReplay },{ "-netgame", parseNetGame },{ "-netslot", parseNetSlot },diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cppindex e226ba1c8..a972d2884 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp@@ -630,8 +630,6 @@ GlobalData::GlobalData()m_useDrawModuleLOD = FALSE;m_useHeatEffects = TRUE;m_useFpsLimit = FALSE;- m_useGroupPaths = TRUE;- m_useCrossingCost = TRUE;m_dumpAssetUsage = FALSE;m_framesPerSecondLimit = 0;m_chipSetType = 0;diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cppindex 89b4e8b80..7fa5cff1a 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AI.cpp@@ -376,9 +376,6 @@ void AI::update( void )Int64 start, afterPathfind, end;QueryPerformanceCounter( (LARGE_INTEGER *)&start );- // age the record of where units have been getting stuck, before any search reads it- m_pathfinder->decayJamMap();-// Do pathfinding.m_pathfinder->processPathfindQueue();diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cppindex 046e79e3e..e51f00b4c 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp@@ -77,7 +77,6 @@ AIGroup::AIGroup( void ){// DEBUG_LOG(("***AIGROUP %x is being constructed.\n", this));m_groundPath = NULL;- m_groundPathDiameter = 0;m_speed = 0.0f;m_matchSpeeds = TRUE;m_dirty = false;@@ -521,11 +520,6 @@ void AIGroup::computeIndividualDestination( Coord3D *dest, const Coord3D *groupDstatic const Int PATH_DIAMETER_IN_CELLS = 6;-/* A player's selection keeps its shape - a shared wide corridor split into columns for a move, the- centroid offsets for an attack move - up to this many members. Past it the shape is what breaks:- two hundred units strung out along an arc, three hundred with no workable goal cell at all. */-static const Int MAX_MEMBERS_FOR_GROUP_LANES = 40;-//-------------------------------------------------------------------------------------------------// Internal function for moving a group of infantry as a column.//@@ -607,7 +601,6 @@ Bool AIGroup::friend_computeGroundPath( const Coord3D *pos, CommandSourceType cmdistSqr = dx*dx+dy*dy;}if (distSqr < sqr(TheAI->getAiData()->m_minDistanceForGroup)) {- DEBUG_LOG(("GROUPPATH probe: too close, distSqr %f min %f\n", distSqr, sqr(TheAI->getAiData()->m_minDistanceForGroup)));return false;}if (distSqr>sqr(TheAI->getAiData()->m_distanceRequiresGroup)) {@@ -642,28 +635,10 @@ Bool AIGroup::friend_computeGroundPath( const Coord3D *pos, CommandSourceType cm}if (isPassable) closeEnough = true;}- if (!closeEnough) {- DEBUG_LOG(("GROUPPATH probe: not closeEnough, infantry %d vehicles %d\n", numInfantry, numVehicles));- return false;- }-- // A corridor six cells wide does not exist on every route - a bridge, a ramp or a gap between- // two cliffs is narrower than sixty world units, and findGroundPath then returns NULL. Retail- // gave up there and let every member solve its own path to the same point, which is exactly the- // single file this is trying to avoid: the group is at its most cramped precisely where it most- // needs to be told who drives where. So ask for a narrower corridor before giving up, and- // remember the width that answered - the columns below are spaced against it, not against six.- const Int groupPathDiameters[3] = { PATH_DIAMETER_IN_CELLS, 4, 3 };- for (Int w = 0; w < 3; ++w) {- m_groundPathDiameter = groupPathDiameters[w];- m_groundPath = TheAI->pathfinder()->findGroundPath(¢er, pos, m_groundPathDiameter, false);- DEBUG_LOG(("GROUPPATH probe: findGroundPath diameter %d -> %s\n", m_groundPathDiameter, m_groundPath?"path":"NULL"));- if (m_groundPath) {- return true;- }- }- m_groundPathDiameter = 0;- return false;+ if (!closeEnough) return false;++ m_groundPath = TheAI->pathfinder()->findGroundPath(¢er, pos, PATH_DIAMETER_IN_CELLS, false);+ return m_groundPath!=NULL;}@@ -1166,51 +1141,6 @@ void AIGroup::friend_moveFormationToPos( const Coord3D *pos, CommandSourceType c}}-/**- * Is there room for this unit, centred on spot, across its own width along normal?- * The corridor is wide enough for the group, but a lane offset is a blind sideways step off the- * path the pathfinder actually checked, and a tank is wider than the cell that step lands in.- */-static Bool laneSpotIsClear( Object *unit, const Coord3D *spot, const Coord2D *normal, Real halfWidth )-{- AIUpdateInterface *ai = unit->getAIUpdateInterface();- if (ai == NULL) return false;- Pathfinder *pathfinder = TheAI->pathfinder();- const Bool isCrusher = unit->getCrusherLevel() > 0;- const PathfindLayerEnum layer = unit->getLayer();- if (!pathfinder->validMovementPosition( isCrusher, layer, ai->getLocomotorSet(), spot )) {- return false;- }- Coord3D edge = *spot;- edge.x += halfWidth * normal->x;- edge.y += halfWidth * normal->y;- if (!pathfinder->validMovementPosition( isCrusher, layer, ai->getLocomotorSet(), &edge )) {- return false;- }- edge = *spot;- edge.x -= halfWidth * normal->x;- edge.y -= halfWidth * normal->y;- return pathfinder->validMovementPosition( isCrusher, layer, ai->getLocomotorSet(), &edge );-}--/**- * Perpendicular distance of pt from the segment from a to b, in 2d.- */-static Real distanceFromSegment( const Coord3D *a, const Coord3D *b, const Coord3D *pt )-{- Real dx = b->x - a->x;- Real dy = b->y - a->y;- Real lenSqr = dx*dx + dy*dy;- if (lenSqr < 1.0f) {- dx = pt->x - a->x;- dy = pt->y - a->y;- return sqrtf(dx*dx + dy*dy);- }- Real cross = (pt->x - a->x)*dy - (pt->y - a->y)*dx;- if (cross < 0) cross = -cross;- return cross / sqrtf(lenSqr);-}-//-------------------------------------------------------------------------------------------------// Internal function for moving a group of vehicles as a column.//@@ -1261,12 +1191,11 @@ Bool AIGroup::friend_moveVehicleToPos( const Coord3D *pos, CommandSourceType cmdendNode = NULL;}if (startNode==NULL || endNode==NULL) {- DEBUG_LOG(("VEHCOLUMN probe: corridor too short to take a heading from\n"));m_groundPath->deleteInstance();m_groundPath = NULL;return false;}-+Coord2D startVector;startVector.x = startNode->getPosition()->x - startPoint.x;startVector.y = startNode->getPosition()->y - startPoint.y;@@ -1288,7 +1217,6 @@ Bool AIGroup::friend_moveVehicleToPos( const Coord3D *pos, CommandSourceType cmdendVectorNormal.normalize();Int unitsToPath = 0;- Real maxUnitRadius = 0.0f;Bool useEndVector = false;// Move.MemoryPoolObjectHolder iterHolder;@@ -1328,9 +1256,6 @@ Bool AIGroup::friend_moveVehicleToPos( const Coord3D *pos, CommandSourceType cmd// Sort by the dot product of normal.iter->insert((*i), dx*startVectorNormal.x+dy*startVectorNormal.y);unitsToPath++;- if ((*i)->getGeometryInfo().getBoundingCircleRadius() > maxUnitRadius) {- maxUnitRadius = (*i)->getGeometryInfo().getBoundingCircleRadius();- }// If units are closer to the end vector than the start vector, use the end vector.Real distToEndSqr;@@ -1347,10 +1272,8 @@ Bool AIGroup::friend_moveVehicleToPos( const Coord3D *pos, CommandSourceType cmd}if (unitsToPath<TheAI->getAiData()->m_minVehiclesForGroup) {- DEBUG_LOG(("VEHCOLUMN probe: only %d vehicles, need %d\n", unitsToPath, TheAI->getAiData()->m_minVehiclesForGroup));return false;}- DEBUG_LOG(("VEHCOLUMN probe: laying %d vehicles into columns\n", unitsToPath));Object *theUnit;if (useEndVector) {@@ -1481,16 +1404,13 @@ Bool AIGroup::friend_moveVehicleToPos( const Coord3D *pos, CommandSourceType cmdcurIndex = 0;Int columnFactor[5] = {0,0,0,0,0};- // A lane is only a lane if the widest thing in the group fits in it with room to steer. Two- // cells was a guess, and it is narrower than a tank; this is measured off the units that were- // actually ordered, so a group of tanks spreads wider than a group of humvees.- const Real laneSpacing = 2.0f*maxUnitRadius + 0.5f*PATHFIND_CELL_SIZE_F;PathfindLayerEnum layer = TheTerrainLogic->getLayerForDestination(pos);for (theUnit = iter2->first(); theUnit; theUnit = iter2->next()){AIUpdateInterface *ai = theUnit->getAIUpdateInterface();Int tmp = ai->getTmpValue();Int threeColumnDelta = tmp>>16;+ Int columnDelta = (Short)(tmp & 0xFFFF);Int factor = columnFactor[threeColumnDelta+2];columnFactor[threeColumnDelta+2] = factor+1;@@ -1498,21 +1418,6 @@ Bool AIGroup::friend_moveVehicleToPos( const Coord3D *pos, CommandSourceType cmdPathNode *node = startNode;PathNode *previousNode = m_groundPath->getFirstNode();Coord3D prevPos = *theUnit->getPosition();- // Every waypoint kept is a turn taken: the unit stops steering for the horizon and steers for- // the next point instead. The corridor hands out one point per path node, and most of them sit- // on or near the straight line through their neighbours - a wobble the driver pays for and- // nobody asked for. This is the raycast simplification every modern pathfinder ends with: a- // point is dropped when the straight line past it is one this unit can actually drive- // (isLinePassable, which is the raycast) and it does not pull the route more than a lane- // width off the corridor the pathfinder cleared. A cheap distance test comes first so the- // common case - a point that barely bends anything - never pays for a line check.- const Real straightenTolerance = 0.5f*PATHFIND_CELL_SIZE_F;- const Int maxStraightenRun = 16;- const LocomotorSurfaceTypeMask surfaces = ai->getLocomotorSet().getValidSurfaces();- const PathfindLayerEnum unitLayer = theUnit->getLayer();- Coord3D pendingPos;- Bool havePending = false;- Int straightenRun = 0;while (node) {Coord3D dest = *node->getPosition();PathNode *tmpNode;@@ -1535,34 +1440,16 @@ Bool AIGroup::friend_moveVehicleToPos( const Coord3D *pos, CommandSourceType cmdcornerVector.x = nextNode->getPosition()->x - previousNode->getPosition()->x;cornerVector.y = nextNode->getPosition()->y - previousNode->getPosition()->y;- // Retail drove the corridor in two lanes a cell and a half either side of its centre and- // nudged alternate units half a cell sideways on top of that, which is narrower than the- // units themselves: side by side they overlapped, so a group crossing open ground spent- // the trip shoving. Lanes are a whole unit apart plus a little air instead (laneSpacing),- // so a lane is somewhere a tank actually fits, and there is no half-cell nudge - two- // units sharing a lane drive one line, in file, which is what a lane is for.- Real lateral = laneSpacing * threeColumnDelta;-- // The lane is a sideways step off the line the pathfinder checked, so it can land in a- // cliff or a building even though the corridor as a whole was passable - and a tank- // wedged against terrain is worse than a tank in a queue. Give the step back rather than- // take it blindly: full width, then half, then none, which is the corridor centre the- // path already proved. Trying half before giving up matters at the pinch points, where- // there is room for a nudge but not for a whole lane.- const Real halfWidth = theUnit->getGeometryInfo().getBoundingCircleRadius();- Coord3D laneDest = dest;- for (Int shrink = 0; shrink < 3; ++shrink) {- Real tryLateral = lateral;- if (shrink == 1) tryLateral = lateral * 0.5f;- if (shrink == 2) tryLateral = 0.0f;- laneDest = dest;- laneDest.x += tryLateral * cornerVectorNormal.x;- laneDest.y += tryLateral * cornerVectorNormal.y;- if (tryLateral == 0.0f || laneSpotIsClear( theUnit, &laneDest, &cornerVectorNormal, halfWidth )) {- break;- }+ Real offset = PATHFIND_CELL_SIZE_F*1.5f;+ dest.x += offset * columnDelta * cornerVectorNormal.x;+ dest.y += offset * columnDelta * cornerVectorNormal.y;+ if (factor&1) {+ dest.x += 0.5f*PATHFIND_CELL_SIZE_F * cornerVectorNormal.x;+ dest.y += 0.5f*PATHFIND_CELL_SIZE_F * cornerVectorNormal.y;+ } else {+ dest.x -= 0.5f*PATHFIND_CELL_SIZE_F * cornerVectorNormal.x;+ dest.y -= 0.5f*PATHFIND_CELL_SIZE_F * cornerVectorNormal.y;}- dest = laneDest;Coord2D curVector;curVector.x = dest.x-prevPos.x;@@ -1570,24 +1457,8 @@ Bool AIGroup::friend_moveVehicleToPos( const Coord3D *pos, CommandSourceType cmdclampToMap(&dest, controllingPlayerType);// Make sure that this dest is going in the same direction as the vector.if (cornerVector.x*curVector.x + cornerVector.y*curVector.y > 0) {- if (!havePending) {- pendingPos = dest;- havePending = true;- straightenRun = 0;- } else if (straightenRun < maxStraightenRun &&- (distanceFromSegment( &prevPos, &dest, &pendingPos ) < straightenTolerance ||- (distanceFromSegment( &prevPos, &dest, &pendingPos ) < laneSpacing &&- TheAI->pathfinder()->isLinePassable( theUnit, surfaces, unitLayer,- prevPos, dest, false, true )))) {- // prevPos -> dest is drivable without the point in between; drop it and hold the turn.- pendingPos = dest;- straightenRun++;- } else {- path.push_back( pendingPos );- prevPos = pendingPos;- pendingPos = dest;- straightenRun = 0;- }+ path.push_back( dest );+ prevPos = dest;}node=node->getNextOptimized();@@ -1600,10 +1471,6 @@ Bool AIGroup::friend_moveVehicleToPos( const Coord3D *pos, CommandSourceType cmd}}}- if (havePending) {- // the last corridor point is never dropped - it is what aims the unit at the goal.- path.push_back( pendingPos );- }Coord3D dest = *pos;if (threeColumnDelta<-3) threeColumnDelta=-3;@@ -1612,16 +1479,11 @@ Bool AIGroup::friend_moveVehicleToPos( const Coord3D *pos, CommandSourceType cmdif (unitsToPath<5) {offset = PATHFIND_CELL_SIZE_F*1.5f;}- // Same rule as the lanes: a cell and a half is less than a tank, so four tanks arriving on- // that spacing arrive on top of each other and finish the trip pushing.- if (offset < laneSpacing) {- offset = laneSpacing;- }dest.x += offset * threeColumnDelta * endVectorNormal.x;dest.y += offset * threeColumnDelta * endVectorNormal.y;if (factor&1) {- dest.x += 0.5f*laneSpacing * endVectorNormal.x;- dest.y += 0.5f*laneSpacing * endVectorNormal.y;+ dest.x += PATHFIND_CELL_SIZE_F * endVectorNormal.x;+ dest.y += PATHFIND_CELL_SIZE_F * endVectorNormal.y;}#if 0LocomotorPriority movePriority = LOCO_MOVES_MIDDLE;@@ -1730,36 +1592,16 @@ void AIGroup::groupMoveToPosition( const Coord3D *p_posIn, Bool addWaypoint, Com// holding a shape. Explicit formations - the ones the player asked for by name - still keep// theirs, and the AI still moves its teams the old way.//- // That was too wide a net. Only a selection far larger than anyone drags a box around fails to- // fit its shape, and paying for it at every size cost the one thing the group path is for: a- // dozen tanks sent across a map all solve the same A* and drive down the single cheapest line- // nose to tail, because the congestion cost can only push a lane a cell or two aside. Below the- // cap they get the retail answer instead - one corridor wide enough for the group- // (PATH_DIAMETER_IN_CELLS), split into columns, so the group crosses a gap abreast and some of- // it takes the wider way round.- //- const Bool gatherOnPoint = ( cmdSource == CMD_FROM_PLAYER && !isFormation &&- m_memberListSize > MAX_MEMBERS_FOR_GROUP_LANES );+ const Bool gatherOnPoint = ( cmdSource == CMD_FROM_PLAYER && !isFormation );- /* The corridor and the orders that ride on it, timed: it is one search plus a move order for+ /* The group path and the orders that ride on it, timed: it is one search plus a move order forevery member, all of it inside the one logic frame the order arrives on, and a skirmish AI- team taking an approach path is the slowest frame left in a four-player match. The probe has- always printed what this block decided; it now prints what it cost as well. */+ team taking an approach path is the slowest frame left in a four-player match. */#ifdef DEBUG_LOGGINGInt64 corridorStart, corridorEnd, corridorFreq;QueryPerformanceCounter( (LARGE_INTEGER *)&corridorStart );#endif- /* A group of one is not a group. The corridor is a wide search plus a set of lanes to spread a- selection across, and a single unit uses neither: it drives the centre line, which is the- route its own path would have taken, and the search cost twice what that path costs. Two- Twilight Flame matches issue 65 group orders and 18 of them are for one unit, six of those- slow enough to log - 44ms of corridor searching to move one tank. Below two members the unit- falls through to the move loop and paths for itself, which is what retail did with it.-- -nogrouppath is the control arm for the rest: no shared corridor at any size, every unit- solves its own path below. */- if (!addWaypoint && !isFormation && !gatherOnPoint && m_memberListSize > 1 &&- TheGlobalData->m_useGroupPaths) {+ if (!addWaypoint && !isFormation && !gatherOnPoint) {friend_computeGroundPath(pos, cmdSource);didInfantry = friend_moveInfantryToPos(pos, cmdSource);didVehicles = friend_moveVehicleToPos(pos, cmdSource);@@ -1770,9 +1612,6 @@ void AIGroup::groupMoveToPosition( const Coord3D *p_posIn, Bool addWaypoint, Comconst Real corridorMS = corridorFreq > 0? (Real)((double)(corridorEnd - corridorStart) * 1000.0 / (double)corridorFreq) : 0.0f;#endif- DEBUG_LOG(("GROUPMOVE probe: members %d src %d gatherOnPoint %d formation %d waypoint %d corridor %d infantry %d vehicles %d took %.1fms\n",- m_memberListSize, (Int)cmdSource, gatherOnPoint?1:0, isFormation?1:0, addWaypoint?1:0,- m_groundPath!=NULL?1:0, didInfantry?1:0, didVehicles?1:0, corridorMS));if (m_dirty)recompute();@@ -2559,11 +2398,10 @@ void AIGroup::groupAttackMoveToPosition( const Coord3D *pos, Int maxShotsToFire,// As with a plain move (see groupMoveToPosition): a player's attack move sends everyone to// the point and lets each unit take the nearest free cell to it, rather than holding the// selection's shape on the way in - which a large group could only do by spreading along- // an arc. And, as there, only a selection past the cap actually has that problem: under it- // the shape is what keeps the group off one another's path on the way in.+ // an arc.//Coord3D dest;- if (cmdSource == CMD_FROM_PLAYER && m_memberListSize > MAX_MEMBERS_FOR_GROUP_LANES)+ if (cmdSource == CMD_FROM_PLAYER)dest = goalPos;elsecomputeIndividualDestination( &dest, &goalPos, theUnit, ¢er, FALSE );diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cppindex cad7c5b81..9e8612dba 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp@@ -147,8 +147,8 @@ static char thePFReport[ 512 ];// The per-frame tallies above are zeroed every frame, so they only ever describe the one frame// that happened to run over budget. These carry the same numbers for the whole match, which is// what a headless batch needs: two builds are compared on total search size and total time, not-// on whichever frame got logged. Plus the three counts that say a pathing change made things-// worse rather than merely different.+// on whichever frame got logged. Plus the counts that say a pathing change made things worse+// rather than merely different.static __int64 thePFMatchTicks[ PF_SLOTS ];static Int thePFMatchCalls[ PF_SLOTS ];static char thePFMatchReport[ 1024 ];@@ -156,7 +156,6 @@ static Int thePFOutOfCells = 0; ///< a search ran the shared cell-info pool drstatic Int thePFNoPath = 0; ///< a unit asked for a path and got nothing backstatic Int thePFBlockedFrames = 0; ///< unit-frames spent standing behind another unitstatic Int thePFStuckFrames = 0; ///< of those, the ones where the blocker was not moving either-static Int thePFQueueDetours = 0; ///< units that gave up on a queue and repathed round itinline void pfBump( Int slot ) { thePFCalls[ slot ]++; }@@ -346,7 +345,6 @@ m_path(NULL),m_pathTail(NULL),m_isOptimized(FALSE),m_blockedByAlly(FALSE),-m_usageHead(NULL),m_cpopRecentStart(NULL),m_cpopCountdown(MAX_CPOP),m_cpopValid(FALSE)@@ -361,10 +359,7 @@ Path::~Path( void ){PathNode *node, *nextNode;- if (m_usageHead && TheAI && TheAI->pathfinder())- TheAI->pathfinder()->unregisterPathUsage(this);-- // delete all of the path nodes+ // delete all of the path nodesfor( node = m_path; node; node = nextNode ){nextNode = node->getNext();@@ -557,13 +552,10 @@ void Path::appendNode( const Coord3D *pos, PathfindLayerEnum layer )void Path::updateLastNode( const Coord3D *pos ){PathfindLayerEnum layer = TheTerrainLogic->getLayerForDestination(pos);- // Keep the congestion map honest: uncount the old tail cell, recount the new one.- if (m_usageHead) TheAI->pathfinder()->adjustPathUsage(m_pathTail, NULL, -1);if (m_pathTail) {m_pathTail->setPosition(pos);m_pathTail->setLayer(layer);}- if (m_usageHead) TheAI->pathfinder()->adjustPathUsage(m_pathTail, NULL, +1);if (m_isOptimized && m_pathTail){PathNode *node = m_path;@@ -1056,9 +1048,6 @@ void Path::computePointOnPath(#ifdef CPOP_STARTS_FROM_PREV_SEGm_cpopRecentStart = closeNode;#endif- // Everything before the closest segment is behind us - stop charging others for it.- if (m_usageHead && closeNode)- TheAI->pathfinder()->releasePathUsageBefore(this, closeNode);//// Compute the goal movement position for this agent@@ -1355,9 +1344,8 @@ PathfindCellInfo *PathfindCellInfo::getACellInfo(PathfindCell *cell,const ICoordinfo->m_nextOpen = NULL;info->m_prevOpen = NULL;info->m_pathParent = NULL;- info->m_costSoFar = 0;+ info->m_costSoFar = 0;info->m_totalCost = 0;- info->m_travelSoFar = 0;info->m_open = 0;info->m_closed = 0;info->m_openBucket = 0;@@ -1437,7 +1425,6 @@ Bool PathfindCell::startPathfind( PathfindCell *goalCell )m_info->m_pathParent = NULL;m_info->m_costSoFar = 0; // start node, no cost to get herem_info->m_totalCost = 0;- m_info->m_travelSoFar = 0; // ... and no ground covered yet, which is when the search startsif (goalCell) {m_info->m_totalCost = costToGoal( goalCell );}@@ -2044,175 +2031,6 @@ PathfindCell *PathfindCell::removeFromClosedList( PathfindCell *list )const Int COST_ORTHOGONAL = 10;const Int COST_DIAGONAL = 14;-/* What another unit's live path through a cell of our footprint costs us: half an orthogonal step- per path, so a second unit heading the same way would rather take the lane beside the queue- than join it. That is the whole mechanism against traffic jams.-- Measured, not guessed. Headless 4-brutal matches, same seeds per value, counting unit-frames- spent standing behind another unit per 1000 logic frames (24 matches per value):- 0 (retail) 32,6 blocked (2,9 of them stuck) 62.736 cell expansions 203ms per match- 5 23,3 (2,5) 66.310 240ms- 10 20,8 (36,4) 67.861 227ms- and over 12 matches per value, reaching further up the range: 20 -> 21,5 blocked / 90.901- expansions, 40 -> 19,6 / 91.922.-- 5 is the pick, not 10. "Blocked" is a unit waiting behind a moving unit, which is traffic;- "stuck" is a unit waiting behind one that is not moving either, which is a real jam. At 10 the- jams multiply by twelve for another 2,5 points of traffic - the lanes spread far enough that- units park across each other. At 5 the jams stay at retail level and a third of the waiting- goes away for 6% more search.-- nopath and out-of-cells stayed at 0 at every value. That is what the first attempt at this got- wrong: uncapped, nine tanks crossing a map exhausted the cell pool and came back with no path- at all, because the A* heuristic cannot see this cost and the search floods. RANGE and- MAX_PATHS below are what bound it. */-const Int PATH_CONGESTION_COST = 5;-const Int PATH_CONGESTION_RANGE = 30; ///< cells from the start within which other paths cost anything-const Int PATH_CONGESTION_MAX_PATHS = 4; ///< the penalty stops growing past this many paths in a footprint--/* The cost above is about where other units are *going*. This one is about where they are- standing right now, and it is only paid by a unit that has already given up on the queue it is- in (AIUpdateInterface::isQueuedBehindUnits). Every other search keeps the retail flat cost.-- A cell holding another unit costs 3*COST_DIAGONAL = 42 in retail, which is four cells of ground.- That is enough to prefer the lane beside a single parked tank and nowhere near enough to walk- round a column of six: driving through them is 42 a cell, but the way round is a hundred cells- of open ground the search has to be paid to take. For the one search that gets it, occupied- ground costs 162 instead, which buys about sixteen cells of detour per unit in the way - a tank- pulls out of the line, drives right round the ones standing in it and comes back in front.-- Bounded to the cells near the start for the reason the congestion comment gives: the A*- heuristic cannot see this cost, so an unbounded version of it floods the search. The window- has to hold the whole queue, though, or the unit plans around the tank in front of it and- rejoins the same line two cells later: sixteen cells is a hundred and sixty world units, which- is a column of five tanks plus the room to swing round it.-- These two numbers are where the sweep stopped, and it is worth saying what is on the other side- of them, because "swing wider" sounds free and is not. Four ways to widen it, same 24 seeds,- blocked unit-frames per 1000 logic frames and cell expansions per match - retail, with none of- this, is 34,2:- 50 over 10 cells (this) 28,8 56.784- cost 50 -> 120 28,4 56.783- range 10 -> 16 28,6 56.763- a cell of clearance around- the traffic, not just the- cells it stands on 33,6 56.661- threshold 40 -> 25 frames 40,6 64.383-- One cell of difference in 56.784 is the same routes to within rounding, twice over: the cost- saturates the way the crossing cost saturates at 60, because past the point where going round- is cheaper than going through, paying more does not move the line further out - the route is- already the widest the ground offers. The range is inert for the same reason.-- The two that do change something both make it worse, and in the same way the congestion cost- does at 10: spread them harder and they park across each other. A cell of clearance sends the- detour wide enough to meet the next lane's traffic, and firing sooner pulls units out of lines- that were about to clear - that one is worse than doing nothing at all. A unit that leaves a- queue has to leave it late and by the shortest way round, or it is not saving anyone time. */-const Int PATH_QUEUE_COST = 5*COST_ORTHOGONAL;-const Int PATH_QUEUE_RANGE = 10; ///< cells from the start within which standing units cost extra--/* Both costs above describe a moment. The congestion map says somebody's path runs through a cell,- the queue cost says somebody is standing in it right now, and neither remembers anything: a- doorway that has been solid for two seconds is priced exactly like one a tank has just rolled- into. A unit repathing out of a queue therefore keeps choosing the doorway its own column is- wedged in, because at the instant the search runs the cells past the jam are empty.-- The jam map is the memory. Every blocked unit stamps the cell it is standing in, once a frame,- and the whole map loses one everywhere every JAM_DECAY_FRAMES - so a cell holds roughly the- blocked unit-frames spent in it over the last JAM_MAX*JAM_DECAY_FRAMES frames, which is 80- frames, a bit under three seconds. Integer and quantised on the frame number, because a- real-valued decay read by the search is a desync waiting for a machine with a different FPU.-- JAM_FLOOR is the "three or more" gate: one unit pausing for a frame is traffic and stamps 1 or- 2, and only ground that several units have been stuck on, or one has been stuck on for a while,- gets past 3 and costs anything. Like every other cost here it is capped, for the reason the- congestion comment gives at length - the A* heuristic cannot see it, so an uncapped version- floods the search. */-const Int PATH_JAM_COST = 3*COST_ORTHOGONAL; ///< per blocked unit-frame above the floor-const Int PATH_JAM_FLOOR = 3; ///< stamps below this are traffic, not a jam-const Int PATH_JAM_MAX = 10; ///< the stamp saturates here-const Int PATH_JAM_DECAY_FRAMES = 8; ///< every cell loses one stamp this often-const Int PATH_JAM_MAX_CHARGED = 4; ///< the penalty stops growing past this much over the floor--/* Split out for the same reason as the congestion penalty: the floor and the cap are the whole of- the design, and a version without either is a search that floods or a cost that fires on- ordinary traffic. */-Int Pathfinder_jamPenalty( Int jam )-{- Int over = jam - PATH_JAM_FLOOR;- if (over <= 0)- return 0;- if (over > PATH_JAM_MAX_CHARGED)- over = PATH_JAM_MAX_CHARGED;- return over * PATH_JAM_COST;-}--/* Split out of examineNeighboringCells so the cap is testable: the cap is the only thing keeping- this cost from flooding the search, since the heuristic cannot see it. */-Int Pathfinder_congestionPenalty( Int usage, Int costPerPath )-{- if (usage <= 0)- return 0;- if (usage > PATH_CONGESTION_MAX_PATHS)- usage = PATH_CONGESTION_MAX_PATHS;- return usage * costPerPath;-}--/* The congestion cost above has no clock in it, and that is the one thing it cannot be taught: a- cell is either spoken for or it is not, so a road two columns share ten seconds apart is priced- exactly like the intersection they both want at once. Pricing it harder does not separate them,- it just makes every road expensive.-- The reservation map adds the clock - each live path stamps the frame it expects to reach each of- its cells, and this cost is paid only where somebody else wants that cell inside a window of the- same moment *and* is going a different way. Nose to tail down one road is a queue and a queue is- what a road is for; two columns meeting at right angles is the case worth buying out.-- Swept in Tools/PathLab (the same grid, costs and cap in Python) with --scenario cross, two groups- of eight sent to each other's corner across eight open layouts:- crossing cost blocked unit-frames frames to arrive real crossings search cost- 0 984 545 12 --- 60 741 531 11 +1%- 120 and 240 route identically to 60 - it saturates - and below 60 the effect fades out. On- the choke and twogaps layouts it is neutral, which is the point of the two gates below.-- Two gates, each of which was measured before it was kept:-- - Only traffic that is not going your way (PATH_CROSSING_SAME_WAY, headings within about 53- degrees). Charging everyone who shares a cell at the same moment charges a queue: the first- version of this priced hundreds of following-traffic pairs per run instead of the ten to- seventeen real crossings.- - Only where there is room to dodge, which here is the cell not being pinched. Pricing a- two-cell doorway does not spread anyone out - there is nowhere to spread to - it just sends- them to the next doorway to queue at that one instead.-- The cap is here for the same reason the congestion cap is: the A* heuristic cannot see this cost,- so an uncapped one widens the search until it floods the cell pool and comes back with no path. */-const Int PATH_CROSSING_COST = 60; ///< per clashing claim - six cells of detour, and it saturates there-const Int PATH_CROSSING_WINDOW = 12; ///< frames either side of an arrival that still count as the same moment-const Int PATH_CROSSING_MAX = 3; ///< the penalty stops growing past this many clashes in a cell-const Real PATH_CROSSING_SAME_WAY = 0.6f; ///< headings this aligned are a queue, not a crossing--Int Pathfinder_crossingPenalty( Int conflicts )-{- if (conflicts <= 0)- return 0;- if (conflicts > PATH_CROSSING_MAX)- conflicts = PATH_CROSSING_MAX;- return conflicts * PATH_CROSSING_COST;-}--Bool Pathfinder_reservationsClash( UnsignedInt frameA, Real headingAX, Real headingAY,- UnsignedInt frameB, Real headingBX, Real headingBY )-{- // UnsignedInt frames: subtract the smaller one, never negate.- UnsignedInt apart = (frameA > frameB) ? (frameA - frameB) : (frameB - frameA);- if (apart >= (UnsignedInt)PATH_CROSSING_WINDOW)- return false;- return headingAX*headingBX + headingAY*headingBY <= PATH_CROSSING_SAME_WAY;-}-const Real COST_TO_DISTANCE_FACTOR = 1.0f/10.0f;const Real COST_TO_DISTANCE_FACTOR_SQR = COST_TO_DISTANCE_FACTOR*COST_TO_DISTANCE_FACTOR;@@ -4403,7 +4221,7 @@ void PathfindLayer::classifyWallMapCell( Int i, Int j , PathfindCell *cell, Obje//----------------------- Pathfinder ----------------------------------------Pathfinder::Pathfinder( void ) :m_map(NULL), m_pathUsage(NULL), m_jamMap(NULL)+Pathfinder::Pathfinder( void ) :m_map(NULL){debugPath = NULL;PathfindCellInfo::allocateCellInfos();@@ -4440,7 +4258,6 @@ void Pathfinder::resetMatchProfile( void )thePFNoPath = 0;thePFBlockedFrames = 0;thePFStuckFrames = 0;- thePFQueueDetours = 0;}void Pathfinder::bumpNoPath( void )@@ -4455,11 +4272,6 @@ void Pathfinder::bumpBlockedFrame( Bool stuck )thePFStuckFrames++;}-void Pathfinder::bumpQueueDetour( void )-{- thePFQueueDetours++;-}-const char *Pathfinder::getMatchProfileReport( void ){__int64 freq = 0;@@ -4483,8 +4295,8 @@ const char *Pathfinder::getMatchProfileReport( void )len += oneLen;}if( len < (Int)sizeof( thePFMatchReport ) - 64 )- sprintf( thePFMatchReport + len, "| nopath %d outofcells %d blocked %d stuck %d queuedetour %d",- thePFNoPath, thePFOutOfCells, thePFBlockedFrames, thePFStuckFrames, thePFQueueDetours );+ sprintf( thePFMatchReport + len, "| nopath %d outofcells %d blocked %d stuck %d",+ thePFNoPath, thePFOutOfCells, thePFBlockedFrames, thePFStuckFrames );return thePFMatchReport;}@@ -4524,21 +4336,10 @@ void Pathfinder::reset( void )delete []m_blockOfMapCells;m_blockOfMapCells = NULL;}- if (m_map) {+ if (m_map) {delete [] m_map;m_map = NULL;}- if (m_pathUsage) {- delete [] m_pathUsage;- m_pathUsage = NULL;- }- if (m_jamMap) {- delete [] m_jamMap;- m_jamMap = NULL;- }- m_jamCells = 0;- m_jamDecayFrame = 0;- resetReservations();Int i;for (i=0; i<=LAYER_LAST; i++) {@@ -5268,12 +5069,6 @@ void Pathfinder::newMap( void )for (i=0; i<=bounds.hi.x; i++) {m_map[i] = &m_blockOfMapCells[i*(bounds.hi.y+1)];}- m_pathUsage = MSGNEW("PathfindMapCells") UnsignedByte[(bounds.hi.x+1)*(bounds.hi.y+1)];- memset(m_pathUsage, 0, (bounds.hi.x+1)*(bounds.hi.y+1));- m_jamMap = MSGNEW("PathfindMapCells") UnsignedByte[(bounds.hi.x+1)*(bounds.hi.y+1)];- memset(m_jamMap, 0, (bounds.hi.x+1)*(bounds.hi.y+1));- m_jamCells = 0;- m_jamDecayFrame = 0;for (i=0; i<LAYER_LAST; i++) {if (!m_layers[i].isUnused()) {m_layers[i].allocateCells(&m_extent);@@ -5936,245 +5731,7 @@ void Pathfinder::snapClosestGoalPosition(Object *obj, Coord3D *pos)//DEBUG_LOG(("Couldn't find goal.\n"));}-//--------------------------------------------------------------------------------------------------// Congestion map. Each registered path stamps the cell under every raw node (one per A* cell).-Int Pathfinder::getPathUsage( Int x, Int y ) const-{- if (!m_pathUsage || x < m_extent.lo.x || x > m_extent.hi.x || y < m_extent.lo.y || y > m_extent.hi.y)- return 0;- return m_pathUsage[x*(m_extent.hi.y+1)+y];-}--void Pathfinder::adjustPathUsage( const PathNode *from, const PathNode *to, Int delta )-{- if (!m_pathUsage) return; // map torn down; counts went with it- for (const PathNode *node = from; node && node != to; node = node->getNext()) {- ICoord2D cell;- if (worldToCell(node->getPosition(), &cell)) continue; // off map- UnsignedByte &u = m_pathUsage[cell.x*(m_extent.hi.y+1)+cell.y];- if (delta > 0) { if (u < 255) u++; }- else { if (u > 0) u--; }- }-}--void Pathfinder::registerPathUsage( const Path *path, const Object *obj )-{- if (!path || path->isUsageRegistered() || !m_pathUsage || !path->getFirstNode()) return;- adjustPathUsage(path->getFirstNode(), NULL, +1);- path->setUsageHead(path->getFirstNode());- reservePathTiming(path, obj);-}--void Pathfinder::unregisterPathUsage( const Path *path )-{- if (!path || !path->isUsageRegistered()) return;- adjustPathUsage(path->getUsageHead(), NULL, -1);- releaseReservations(path, path->getUsageHead(), NULL);- path->setUsageHead(NULL);-}--void Pathfinder::releasePathUsageBefore( const Path *path, const PathNode *node )-{- if (!path || !path->isUsageRegistered() || !node) return;- // node must lie at or after the head; if the unit got shoved back behind it, nothing new to release.- const PathNode *n = path->getUsageHead();- while (n && n != node) n = n->getNext();- if (!n) return;- adjustPathUsage(path->getUsageHead(), node, -1);- releaseReservations(path, path->getUsageHead(), node);- path->setUsageHead(node);-}--//--------------------------------------------------------------------------------------------------// Jam map. Same cells again, holding what actually happened rather than what somebody planned.-Int Pathfinder::getJam( Int x, Int y ) const-{- if (!m_jamMap || x < m_extent.lo.x || x > m_extent.hi.x || y < m_extent.lo.y || y > m_extent.hi.y)- return 0;- return m_jamMap[x*(m_extent.hi.y+1)+y];-}--/* One blocked unit, one frame, one cell. Called from doLocomotor, which is the only place a unit- is counted once per frame instead of once per collision pair - a cell where two units keep- bumping each other must not stamp twice as fast as a cell where one is wedged against a wall. */-void Pathfinder::noteJam( const ICoord2D& cell )-{- if (!m_jamMap) return;- if (cell.x < m_extent.lo.x || cell.x > m_extent.hi.x ||- cell.y < m_extent.lo.y || cell.y > m_extent.hi.y) return;- UnsignedByte &jam = m_jamMap[cell.x*(m_extent.hi.y+1)+cell.y];- if (jam == 0)- m_jamCells++;- if (jam < PATH_JAM_MAX)- jam++;-}--/* The decay, once every PATH_JAM_DECAY_FRAMES, off the logic frame number so that every machine- does it on the same frame. A whole-map sweep is a quarter of a megabyte on a big map, which is- why m_jamCells is kept: a match with nothing jammed anywhere - which is most of a match - does- not touch the map at all. */-void Pathfinder::decayJamMap( void )-{- if (!m_jamMap || m_jamCells == 0) return;- UnsignedInt now = TheGameLogic->getFrame();- if (now - m_jamDecayFrame < (UnsignedInt)PATH_JAM_DECAY_FRAMES) return;- m_jamDecayFrame = now;-- const Int cells = (m_extent.hi.x+1)*(m_extent.hi.y+1);- Int nonZero = 0;- for (Int i = 0; i < cells; i++)- {- if (m_jamMap[i] == 0)- continue;- if (--m_jamMap[i] > 0)- nonZero++;- }- m_jamCells = nonZero;-}--//--------------------------------------------------------------------------------------------------// Reservation map. Same cells as the congestion map, one entry each, plus the frame and heading.-Int Pathfinder::reservationBucketOf( Int x, Int y )-{- // two odd multipliers and a xor: cheap, and it scatters the neighbouring cells a search walks.- UnsignedInt hash = ((UnsignedInt)x * 73856093u) ^ ((UnsignedInt)y * 19349663u);- return (Int)(hash & (UnsignedInt)(PATH_RESERVATION_BUCKETS-1));-}--void Pathfinder::resetReservations( void )-{- m_reservations.clear();- m_firstFreeReservation = -1;- for (Int i = 0; i < PATH_RESERVATION_BUCKETS; i++)- m_reservationBuckets[i] = -1;-}--/**- * Stamp an arrival frame and a heading onto every raw node of a freshly built path.- *- * The times come off the raw node list rather than the optimized one the unit actually drives:- * the two agree to within the corners the optimizer cuts, and the raw list is what the congestion- * map already stamps, so a claim and a usage count are put down and taken up together for the- * whole life of the path.- */-void Pathfinder::reservePathTiming( const Path *path, const Object *obj )-{- if (!obj || !obj->getAIUpdateInterface()) return;-- const Locomotor *loco = obj->getAIUpdateInterface()->getCurLocomotor();- if (!loco) return;- Real speed = loco->getMaxSpeedForCondition(obj->getBodyModule()->getDamageState());- if (speed < 0.01f) return; // a unit that cannot move is never anywhere at a particular moment-- UnsignedInt now = TheGameLogic->getFrame();- Real distance = 0.0f;- // the heading a cell is claimed on is the one the unit leaves it on, so the first node has a real- // direction (a unit sitting on a crossing is crossing it) and only the last node inherits.- Real headingX = 0.0f;- Real headingY = 0.0f;- for (const PathNode *node = path->getFirstNode(); node; node = node->getNext()) {- Real segment = 0.0f;- if (node->getNext()) {- Real dx = node->getNext()->getPosition()->x - node->getPosition()->x;- Real dy = node->getNext()->getPosition()->y - node->getPosition()->y;- segment = (Real)sqrt(dx*dx + dy*dy);- if (segment > 0.0f) {- headingX = dx/segment;- headingY = dy/segment;- }- }-- ICoord2D cell;- if (!worldToCell(node->getPosition(), &cell)) { // worldToCell returns true when off map- /* One claim per path per cell, because that is what releaseReservations takes back. A- path that doubles back over a cell it already claimed would otherwise leave the second- claim behind for good, and a claim nobody can release makes that cell expensive to- everybody forever. */- Bool alreadyClaimed = false;- for (Int walk = m_reservationBuckets[reservationBucketOf(cell.x, cell.y)]; walk >= 0;- walk = m_reservations[walk].m_nextInBucket) {- if (m_reservations[walk].m_owner == path &&- m_reservations[walk].m_cell.x == cell.x && m_reservations[walk].m_cell.y == cell.y) {- alreadyClaimed = true;- break;- }- }- if (alreadyClaimed) {- distance += segment;- continue;- }-- Int index = m_firstFreeReservation;- if (index >= 0) {- m_firstFreeReservation = m_reservations[index].m_nextInBucket;- } else {- index = (Int)m_reservations.size();- m_reservations.push_back(PathReservation());- }- PathReservation &reservation = m_reservations[index];- reservation.m_owner = path;- reservation.m_cell = cell;- reservation.m_frame = now + (UnsignedInt)(distance/speed);- reservation.m_headingX = headingX;- reservation.m_headingY = headingY;-- Int bucket = reservationBucketOf(cell.x, cell.y);- reservation.m_nextInBucket = m_reservationBuckets[bucket];- m_reservationBuckets[bucket] = index;- }- distance += segment;- }-}--/**- * Drop this path's claims on the raw nodes [from, to) - the range adjustPathUsage just uncounted.- */-void Pathfinder::releaseReservations( const Path *path, const PathNode *from, const PathNode *to )-{- if (m_reservations.empty()) return;- for (const PathNode *node = from; node && node != to; node = node->getNext()) {- ICoord2D cell;- if (worldToCell(node->getPosition(), &cell)) continue; // off map, so nothing was claimed- Int bucket = reservationBucketOf(cell.x, cell.y);- Int prev = -1;- for (Int index = m_reservationBuckets[bucket]; index >= 0; ) {- PathReservation &reservation = m_reservations[index];- Int next = reservation.m_nextInBucket;- if (reservation.m_owner == path && reservation.m_cell.x == cell.x && reservation.m_cell.y == cell.y) {- if (prev < 0)- m_reservationBuckets[bucket] = next;- else- m_reservations[prev].m_nextInBucket = next;- reservation.m_owner = NULL;- reservation.m_nextInBucket = m_firstFreeReservation;- m_firstFreeReservation = index;- break; // one claim per path per cell- }- prev = index;- index = next;- }- }-}--/**- * How many other paths want this cell at about this frame, coming from a different direction.- */-Int Pathfinder::countCrossingReservations( Int x, Int y, UnsignedInt frame, Real headingX, Real headingY ) const-{- Int conflicts = 0;- for (Int index = m_reservationBuckets[reservationBucketOf(x, y)]; index >= 0;- index = m_reservations[index].m_nextInBucket) {- const PathReservation &reservation = m_reservations[index];- if (reservation.m_cell.x != x || reservation.m_cell.y != y)- continue; // another cell that hashed here- if (Pathfinder_reservationsClash(frame, headingX, headingY,- reservation.m_frame, reservation.m_headingX, reservation.m_headingY))- conflicts++;- }- return conflicts;-}--/**+/*** Returns coordinates of goal.**/@@ -7154,24 +6711,8 @@ Int Pathfinder::examineNeighboringCells(PathfindCell *parentCell, PathfindCell *{pfBump( PF_EXPAND );Bool canPathThroughUnits = false;- // world units per frame, for turning a distance travelled into the frame we get there.- // Zero switches the crossing cost off for this search: without a speed there is no clock.- Real crossingSpeed = 0.0f;- // nonzero only for a unit that has decided to leave the queue it is standing in; see- // PATH_QUEUE_COST- Int queueCost = 0;if (obj && obj->getAIUpdateInterface()) {- if (obj->getAIUpdateInterface()->isQueuedBehindUnits())- queueCost = PATH_QUEUE_COST;canPathThroughUnits = obj->getAIUpdateInterface()->canPathThroughUnits();- // Our own current path must not repel us while we repath (the caller only destroys it- // once the new one is built). O(1) after the first neighbour expansion of a search.- unregisterPathUsage(obj->getAIUpdateInterface()->getPath());- // getCurLocomotor, not getCurLocomotorSpeed: the latter DEBUG_LOGs when there is none.- const Locomotor *loco = obj->getAIUpdateInterface()->getCurLocomotor();- // -nocrosstime leaves the speed at zero, which is this search's switch for "no clock"- if (loco && TheGlobalData->m_useCrossingCost)- crossingSpeed = loco->getMaxSpeedForCondition(obj->getBodyModule()->getDamageState());}Bool isCrusher = obj ? obj->getCrusherLevel() > 0 : false;/* The straight-line-to-goal probe below walks every cell between this cell and the goal and@@ -7320,13 +6861,7 @@ Int Pathfinder::examineNeighboringCells(PathfindCell *parentCell, PathfindCell *info.layer = parentCell->getLayer();info.centerInCell = centerInCell;info.radius = radius;- /* The two guards below were written to switch this off outside a small box around the- start, which only means something if it is on inside that box. EA initialised it to- false, so both branches assigned the same value, the guards were dead and the main A*- has never been able to see a moving unit at all: a queued tank repathed with the queue- invisible and got the line it was already standing in handed back. Only the cells- next to the start, and only for a unit that does not drive through people. */- info.considerTransient = !canPathThroughUnits;+ info.considerTransient = false;info.acceptableSurfaces = locomotorSet.getValidSurfaces();Int dx = newCellCoord.x-startCellNdx.x;Int dy = newCellCoord.y-startCellNdx.y;@@ -7348,9 +6883,8 @@ Int Pathfinder::examineNeighboringCells(PathfindCell *parentCell, PathfindCell *if (!newCell->hasInfo()) {if (!newCell->allocateInfo(newCellCoord)) {// Out of cells for pathing...- DEBUG_LOG(("CONGEST probe: out of pathfind cells after %d cells\n", cellCount));return cellCount;- }+ }cellCount++;}@@ -7358,54 +6892,6 @@ Int Pathfinder::examineNeighboringCells(PathfindCell *parentCell, PathfindCell *if (info.allyMoving && dx<10 && dy<10) {newCostSoFar += 3*COST_DIAGONAL;}- // leaving the queue: the ground the units in front of us are standing on is worth- // going round, for this search only- if (queueCost && dx<PATH_QUEUE_RANGE && dy<PATH_QUEUE_RANGE- && (info.allyMoving || info.allyFixedCount>0)) {- newCostSoFar += queueCost;- }- // ...and the ground they have been stuck on for the last couple of seconds, which is not- // the same ground: a doorway empties for a frame every time the jam shuffles, and the- // search that runs in that frame is the one that routes another unit into it. Only the- // unit leaving a queue pays this, for the same reason it is the only one paying the cost- // above - every other search keeps retail's routes.- if (queueCost && m_jamMap && dx<PATH_QUEUE_RANGE && dy<PATH_QUEUE_RANGE) {- newCostSoFar += Pathfinder_jamPenalty( getJam(newCellCoord.x, newCellCoord.y) );- }- if (m_pathUsage && dx < PATH_CONGESTION_RANGE && dy < PATH_CONGESTION_RANGE) {- // Other units' live paths through our footprint: pay per path so we pick a parallel- // lane. Capped, because the heuristic does not know about this cost and an uncapped- // penalty inflates the search toward a full flood - nine tanks sent across the map- // used to exhaust the cell pool (no path) and hitch the frame. The group corridor- // already holds the group apart, so this cost only has to break the tie where lanes- // form: it stops thirty cells out, where the map has not started pinching yet.- Int usage = 0;- Int above = radius + (centerInCell ? 1 : 0);- for (Int ux = newCellCoord.x-radius; ux < newCellCoord.x+above; ux++)- for (Int uy = newCellCoord.y-radius; uy < newCellCoord.y+above; uy++)- usage += getPathUsage(ux, uy);- newCostSoFar += Pathfinder_congestionPenalty( usage, PATH_CONGESTION_COST );- }- //- // The same ground, with the clock on. m_pathUsage is the gate: the two maps stamp exactly- // the same cells, so a cell no live path runs through cannot hold a reservation and the- // hash is never touched for it - the probe below runs on the handful of cells where a- // crossing is even possible. Pinched cells are skipped because there is nowhere to dodge- // to in a doorway: charging one there does not spread anyone out, it sends them to the- // next doorway to queue at that one instead.- //- UnsignedInt newTravelSoFar = parentCell->getTravelSoFar() +- ((delta[i].x == 0 || delta[i].y == 0) ? COST_ORTHOGONAL : COST_DIAGONAL);- if (crossingSpeed > 0.01f && !newCell->getPinched() && getPathUsage(newCellCoord.x, newCellCoord.y) > 0) {- // travel is in cost units and a cell of cost is a cell of ground, so distance is- // newTravelSoFar cells worth of PATHFIND_CELL_SIZE / COST_ORTHOGONAL.- Real distance = newTravelSoFar * (PATHFIND_CELL_SIZE_F / (Real)COST_ORTHOGONAL);- UnsignedInt arrival = TheGameLogic->getFrame() + (UnsignedInt)(distance/crossingSpeed);- Real length = (delta[i].x == 0 || delta[i].y == 0) ? 1.0f : 1.414214f;- Int conflicts = countCrossingReservations( newCellCoord.x, newCellCoord.y, arrival,- delta[i].x/length, delta[i].y/length );- newCostSoFar += Pathfinder_crossingPenalty( conflicts );- }if (newCell->getType() == PathfindCell::CELL_CLIFF && !newCell->getPinched() ) {Coord3D fromPos;fromPos.x = parentCell->getXIndex() * PATHFIND_CELL_SIZE_F ;@@ -7486,7 +6972,6 @@ Int Pathfinder::examineNeighboringCells(PathfindCell *parentCell, PathfindCell *}}newCell->setCostSoFar(newCostSoFar);- newCell->setTravelSoFar(newTravelSoFar); // ground covered, with none of the penalties in it// keep track of path we're building - point back to cell we moved here fromnewCell->setParentCell(parentCell) ;if (m_isTunneling) {@@ -8382,8 +7867,8 @@ Path *Pathfinder::findGroundPath( const Coord3D *from,The cap is a fixed cell count, so it stops at the same cell on every machine and in everyreplay. Hitting it means the group gets no corridor at that width: AIGroup then tries 4 and- 3 cells wide, and if none of them answers, every member paths for itself - which is what- -nogrouppath does deliberately, and what retail did whenever the ground was too tight. */+ 3 cells wide, and if none of them answers, every member paths for itself, which is what+ retail did whenever the ground was too tight. */enum { MAX_GROUND_PATH_CELLS = 3000 };//@@ -10344,8 +9829,6 @@ Path *Pathfinder::buildActualPath( const Object *obj, LocomotorSurfaceTypeMask a// cleanup the path by checking line of sightpath->optimize(obj, acceptableSurfaces, blocked);- registerPathUsage(path, obj);-#if defined _DEBUG || defined _INTERNALif (TheGlobalData->m_debugAI==AI_DEBUG_PATHS){@@ -11585,12 +11068,11 @@ Path *Pathfinder::getMoveAwayFromPath(Object* obj, Object *otherObj,ICoord2D startCellNdx;Coord3D startPos = *obj->getPosition();if (!centerInCell) {- // same EA typo as in patchPath: the second increment is the y half-cellstartPos.x += PATHFIND_CELL_SIZE_F*0.5f;- startPos.y += PATHFIND_CELL_SIZE_F*0.5f;+ startPos.x += PATHFIND_CELL_SIZE_F*0.5f;}worldToCell(&startPos, &startCellNdx);- PathfindCell *parentCell = getClippedCell( obj->getLayer(), obj->getPosition() );+ PathfindCell *parentCell = getClippedCell( obj->getLayer(), obj->getPosition() );if (parentCell == NULL)return false;if (!obj->getAIUpdateInterface()) {@@ -11762,10 +11244,8 @@ Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSetICoord2D startCellNdx;Coord3D startPos = *obj->getPosition();if (!centerInCell) {- // EA incremented x twice; the second one is the y half-cell, and without it the start cell- // of every even-footprint unit is one cell off along one axis onlystartPos.x += PATHFIND_CELL_SIZE_F*0.5f;- startPos.y += PATHFIND_CELL_SIZE_F*0.5f;+ startPos.x += PATHFIND_CELL_SIZE_F*0.5f;}worldToCell(&startPos, &startCellNdx);//worldToCell(obj->getPosition(), &startCellNdx);@@ -11805,24 +11285,6 @@ Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSet}#endif- /* How far from the start a moving unit still counts as being in the way. EA's fixed two cells- is the distance a tank covers in well under the second that passes between deciding to leave- a queue and getting the new path, so by the time the path came back the unit it was supposed- to route around had left the window and the patch went straight back into the line. Scale it- with the footprint and with how far this unit travels while it waits, and cap it: past six- cells the search is being told to avoid ground that will be empty by the time it gets there. */- Int transientWindow = 2 + radius;- {- const Locomotor *loco = obj->getAIUpdateInterface()->getCurLocomotor();- if (loco) {- Real speed = loco->getMaxSpeedForCondition(obj->getBodyModule()->getDamageState());- transientWindow += REAL_TO_INT(speed * LOGICFRAMES_PER_SECOND / PATHFIND_CELL_SIZE_F);- }- const Int TRANSIENT_WINDOW_MAX = 6;- if (transientWindow > TRANSIENT_WINDOW_MAX)- transientWindow = TRANSIENT_WINDOW_MAX;- }-PathNode *startNode;Coord3D goalPos = *originalPath->getLastNode()->getPosition();Real goalDeltaSqr = sqr(goalPos.x-currentPosition.x) + sqr(goalPos.y - currentPosition.y);@@ -11846,8 +11308,8 @@ Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSet#endifInt dx = cellCoord.x-startCellNdx.x;Int dy = cellCoord.y-startCellNdx.y;- if (dx<-transientWindow || dx>transientWindow) info.considerTransient = false;- if (dy<-transientWindow || dy>transientWindow) info.considerTransient = false;+ if (dx<-2 || dx>2) info.considerTransient = false;+ if (dy<-2 || dy>2) info.considerTransient = false;if (!checkForMovement(obj, info)) {break;}@@ -11905,7 +11367,6 @@ Path *Pathfinder::patchPath( const Object *obj, const LocomotorSet& locomotorSet// cleanup the path by checking line of sightpath->optimize(obj, locomotorSet.getValidSurfaces(), blocked);- registerPathUsage(path, obj);cleanOpenAndClosedLists();parentCell->releaseInfo();candidateGoal->releaseInfo();diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cppindex 4d030b69f..1c1efc6bd 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp@@ -1761,25 +1761,6 @@ void AIInternalMoveToState::onExit( StateExitType status )}}-/* Does this unit look like it is moving, to a player watching it? EA answered with a frame count -- a quarter of a second of blocked frames cleared MODELCONDITION_MOVING - and a frame count is not- a speed. A tank easing round a jam at a third of its top speed is moving; it was drawn parked- and sliding along the ground, and half of the stop-and-go a player complains about is that- drawing rather than the movement underneath it.-- A tenth of top speed, from the physics, because that is under anything a wheel or a walk cycle- reads as: a unit doing 10% is covering its own length in about two seconds. Split out so the- threshold can be checked without a renderer, which is the only check available - a headless run- draws nothing, so no batch can measure this. Client-side and outside the CRC either way.-- With no locomotor to ask, maxSpeed is zero and the test degenerates to "is it moving at all",- which is what the code did before the threshold went in and is the right answer for something- being carried or shoved rather than driving. */-Bool AIState_looksLikeMoving( Real speedNow, Real maxSpeed )-{- return speedNow > 0.1f * maxSpeed;-}-/*** Execute the moveTo behavior towards GoalPosition.*/@@ -1838,14 +1819,7 @@ StateReturnType AIInternalMoveToState::update()forceRecompute = true;}Bool blocked=false;- // isQueuedBehindUnits is the intermittent case the two-second rule misses: a unit shuffling- // along at the back of a column touches the one in front every few frames, never for two- // seconds together, and used to stay in the line for as long as the line existed. Throttled- // to once a second because not every state answers a forced recompute by actually computing- // one - the ones that decline (tightening, pursuing) would otherwise be asked every frame.- Bool queued = ai->isQueuedBehindUnits()- && TheGameLogic->getFrame() - m_blockedRepathTimestamp > LOGICFRAMES_PER_SECOND;- if (ai->isBlockedAndStuck() || ai->getNumFramesBlocked()>2*LOGICFRAMES_PER_SECOND || queued) {+ if (ai->isBlockedAndStuck() || ai->getNumFramesBlocked()>2*LOGICFRAMES_PER_SECOND) {forceRecompute = true;blocked = true;m_blockedRepathTimestamp = TheGameLogic->getFrame();@@ -1872,19 +1846,10 @@ StateReturnType AIInternalMoveToState::update()obj->clearModelConditionState( MODELCONDITION_RAPPELLING );}}- /* Whether the drive animation plays is a question about speed, and EA asked it about frames: a- quarter second of blocked frames stopped the animation whatever the unit was actually doing,- so a tank crawling round a jam at a third of its speed stood still on screen and slid. Half- of the stop-and-go a player complains about is this line rather than the movement code. Ask- the physics instead, through AIState_looksLikeMoving. */- Real speedNow = obj->getPhysics() ? obj->getPhysics()->getVelocityMagnitude() : 0.0f;- Real maxSpeed = 0.0f;- if (ai->getCurLocomotor())- maxSpeed = ai->getCurLocomotor()->getMaxSpeedForCondition( obj->getBodyModule()->getDamageState() );- if (!AIState_looksLikeMoving( speedNow, maxSpeed ))+ if (ai->getNumFramesBlocked()>LOGICFRAMES_PER_SECOND/4){obj->clearModelConditionState( MODELCONDITION_MOVING );- }+ }else{//Clear climbing if modelConditionFlag is not climbing@@ -2455,23 +2420,12 @@ Bool AIAttackApproachTargetState::computePath()AIUpdateInterface *ai = getMachineOwner()->getAI();- if (ai->isBlockedAndStuck())+ if (ai->isBlockedAndStuck()){forceRepath = true;// Intense logging. jba//CRCDEBUG_LOG(("AIAttackApproachTargetState::computePath - stuck, recomputing for object %d\n", getMachineOwner()->getID()));}- //- // This state is where a group of tanks piles up nose to tail, and it is the one state that- // could not get itself out. The base move state asks for a repath after two seconds of being- // blocked; this override ignored that, and the "victim has not moved, so do not re-path" bail- // below then held every tank behind the ones in front for as long as the target stood still.- // A unit that has given up on its queue repaths whatever the victim is doing.- //- if (ai->isQueuedBehindUnits())- {- forceRepath = true;- }if (m_waitingForPath) return true;if (!forceRepath && ai->getPath()==NULL && !ai->isWaitingForPath())diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cppindex e6335f988..a2880b109 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp@@ -73,91 +73,65 @@#define SLEEPY_AI-//-// Leaving a queue. A unit standing behind another one collides, backs its speed off, drifts-// apart, and collides again a few frames later, so m_blockedFrames - which a single clean frame-// zeroes - rarely reaches the two seconds that force a repath. The column therefore sits.-// m_queueFrames counts the same collisions but decays by one per clear frame instead of resetting,-// so a unit touching more often than it clears climbs; one that is genuinely moving falls to zero.-// Past the threshold the unit repaths once, and that search prices the traffic beside it (see-// PATH_QUEUE_COST in AIPathfind.cpp) so the route it gets back leaves the line instead of-// rejoining it.-//-// The threshold is under the two-second rule on purpose: a unit that is being reliably crushed-// against a blocker every frame still hits the old rule first, and this only catches the-// intermittent case the old rule misses. The ceiling stops a unit wedged for a minute from-// carrying a minute of credit into open ground.-//-enum-{- QUEUE_FRAMES_THRESHOLD = 40, ///< about 1.3 seconds of mostly-blocked frames- QUEUE_FRAMES_CEILING = 80-};+#ifdef _INTERNAL+// for occasional debugging...+//#pragma optimize("", off)+//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes")+#endif-/* Split out so the climb-and-decay can be checked on its own: it is the whole of the "am I in a- line" decision, and a version that gets it wrong either never fires or fires on open ground. */-Int AIUpdate_queueFrameStep( Int queueFrames, Bool blocked )+//-------------------------------------------------------------------------------------------------+AIUpdateModuleData::AIUpdateModuleData(){- if (blocked)- return queueFrames < QUEUE_FRAMES_CEILING ? queueFrames + 1 : QUEUE_FRAMES_CEILING;- return queueFrames > 0 ? queueFrames - 1 : 0;+ //m_locomotorTemplates -- nothing to do+ for (int i = 0; i < MAX_TURRETS; i++)+ m_turretData[i] = NULL;+ m_autoAcquireEnemiesWhenIdle = 0;+ m_moodAttackCheckRate = LOGICFRAMES_PER_SECOND * 2;+#ifdef ALLOW_SURRENDER+ m_surrenderDuration = LOGICFRAMES_PER_SECOND * 120;+#endif++ m_forbidPlayerCommands = FALSE;+ m_turretsLinked = FALSE;}-Bool AIUpdate_isQueued( Int queueFrames )+//-------------------------------------------------------------------------------------------------+AIUpdateModuleData::~AIUpdateModuleData(){- return queueFrames >= QUEUE_FRAMES_THRESHOLD;+ for (int i = 0; i < MAX_TURRETS; i++)+ {+ if (m_turretData[i])+ {+ TurretAIData* td = const_cast<TurretAIData*>(m_turretData[i]);+ if (td)+ td->deleteInstance();+ }+ }}-//-// Following the unit in front. See calculateMaxBlockedSpeed for why EA's version (copy his speed,-// read no distance) turns one leader's hiccup into a full stop for everybody behind him.-//-// FOLLOW_GAIN is per logic frame, so at 30fps a car one cell too close closes about a third of the-// error each frame and settles inside half a second without overshooting into a collision. Higher-// values ring; lower ones let the column concertina.-//-const Real FOLLOW_GAIN = 0.35f; ///< how much of the spacing error is corrected per frame-const Real BLOCKED_HEAD_ON = -0.3f; ///< headings this opposed are a collision, not a queue-const Real BLOCKED_SPEED_FILTER = 0.3f; ///< how much of the new ceiling the speed limit takes per frame--/* Split out so the following law can be checked without a game: it is the whole of "how fast may I- go behind him", and a version that gets it wrong either rear-ends the leader or stops dead. */-Real AIUpdate_followSpeed( Real leaderSpeed, Real gap, Real desiredGap )-{- Real speed = leaderSpeed + FOLLOW_GAIN * (gap - desiredGap);- if (speed < 0.0f)- speed = 0.0f;- return speed;-}--/* The blocked speed limit, one frame at a time. EA multiplied it by 0.95 for every blocked frame- and by 1.05 on the way out, off a floor of a fifth of the desired speed: twenty blocked frames- took a unit to 36% and forty to 13%, and climbing back cost over a second. Blocked traffic- therefore ratcheted itself to a crawl and released in a sawtooth, which is the stop-and-go a- player watches. A first-order filter toward the ceiling absorbs a one-frame dip and still- tracks a ceiling that stays low, with no direction that is cheaper than the other. */-Real AIUpdate_smoothBlockedSpeed( Real current, Real target, Real cap )-{- // FAST_AS_POSSIBLE is a sentinel, not a speed; and no ceiling above what we want means anything- if (current > cap) current = cap;- if (target > cap) target = cap;- if (target < 0.0f) target = 0.0f;- return current + BLOCKED_SPEED_FILTER * (target - current);-}--// Overtaking - a unit blocked by traffic going its own way steering one or two footprints sideways-// and driving in that lane - was built here and taken out again. Two 40-match batches on maps its-// constants were never fitted to: blocked unit-frames a coin flip (thirteen matches better, seven-// worse, one seed carrying three quarters of the mean), and stuck frames worse. The only effect-// that reproduced was search work, about a sixth fewer cell expansions, which is not what the-// change was for. PATHFINDING-PLAN.md P3 has the numbers; EA turned their own version off too.+//-------------------------------------------------------------------------------------------------+const LocomotorTemplateVector* AIUpdateModuleData::findLocomotorTemplateVector(LocomotorSetType t) const+{+ if (m_locomotorTemplates.empty())+ return NULL;++ LocomotorTemplateMap::const_iterator it = m_locomotorTemplates.find(t);+ if (it == m_locomotorTemplates.end())+ {+ return NULL;+ }+ else+ {+ return &(*it).second;+ }+}//// -tracemove [id]: one line a frame for one unit. A jam is an argument between the speed the unit// wants, the ceiling its last collision put on it, the decaying bump limit and the frames it has-// spent blocked, and from outside the object none of those four is visible - the run-level counters-// can say 40000 blocked frames and still not say which of the four zeroed the tank. The columns-// are in the order the code applies them, so the first one that goes to zero is the culprit.+// spent blocked, and from outside the object none of those is visible - the run-level counters+// can say 40000 blocked frames and still not say which of them zeroed the tank. The columns are+// in the order the code applies them, so the first one that goes to zero is the culprit.//// With no id the trace latches onto the first unit that gets blocked and follows it for the rest of// the run: in a batch nobody knows an object id in advance, and the interesting unit is by@@ -170,7 +144,7 @@ void AIUpdate_resetMoveTrace( void )theTracedObjectID = INVALID_ID;}-static void AIUpdate_traceMove( const Object *obj, Bool blocked, Int blockedFrames, Int queueFrames,+static void AIUpdate_traceMove( const Object *obj, Bool blocked, Int blockedFrames,Real desiredSpeed, Real maxSpeed, Real maxBlockedSpeed,Real bumpSpeedLimit, Bool waitingForPath, Bool hasPath,Bool stuck )@@ -202,10 +176,10 @@ static void AIUpdate_traceMove( const Object *obj, Bool blocked, Int blockedFramconst Coord3D *pos = obj->getPosition();const PhysicsBehavior *physics = obj->getPhysics();const Real actualSpeed = physics ? physics->getVelocityMagnitude() : 0.0f;- DEBUG_LOG(("MOVETRACE %d,%d,%.2f,%.2f,%.3f,%.3f,%.3f,%.3f,%.3f,%d,%d,%d,%d,%d\n",+ DEBUG_LOG(("MOVETRACE %d,%d,%.2f,%.2f,%.3f,%.3f,%.3f,%.3f,%.3f,%d,%d,%d,%d\n",TheGameLogic->getFrame(), (Int)obj->getID(), pos->x, pos->y,actualSpeed, desiredSpeed, maxSpeed, maxBlockedSpeed, bumpSpeedLimit,- blocked ? 1 : 0, blockedFrames, queueFrames, waitingForPath ? 1 : 0,+ blocked ? 1 : 0, blockedFrames, waitingForPath ? 1 : 0,hasPath ? 1 : 0));if (stuck){@@ -213,61 +187,8 @@ static void AIUpdate_traceMove( const Object *obj, Bool blocked, Int blockedFram}}-#ifdef _INTERNAL-// for occasional debugging...-//#pragma optimize("", off)-//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes")-#endif-//--------------------------------------------------------------------------------------------------AIUpdateModuleData::AIUpdateModuleData()-{- //m_locomotorTemplates -- nothing to do- for (int i = 0; i < MAX_TURRETS; i++)- m_turretData[i] = NULL;- m_autoAcquireEnemiesWhenIdle = 0;- m_moodAttackCheckRate = LOGICFRAMES_PER_SECOND * 2;-#ifdef ALLOW_SURRENDER- m_surrenderDuration = LOGICFRAMES_PER_SECOND * 120;-#endif-- m_forbidPlayerCommands = FALSE;- m_turretsLinked = FALSE;-}--//--------------------------------------------------------------------------------------------------AIUpdateModuleData::~AIUpdateModuleData()-{- for (int i = 0; i < MAX_TURRETS; i++)- {- if (m_turretData[i])- {- TurretAIData* td = const_cast<TurretAIData*>(m_turretData[i]);- if (td)- td->deleteInstance();- }- }-}--//--------------------------------------------------------------------------------------------------const LocomotorTemplateVector* AIUpdateModuleData::findLocomotorTemplateVector(LocomotorSetType t) const-{- if (m_locomotorTemplates.empty())- return NULL;-- LocomotorTemplateMap::const_iterator it = m_locomotorTemplates.find(t);- if (it == m_locomotorTemplates.end())- {- return NULL;- }- else- {- return &(*it).second;- }-}--//--------------------------------------------------------------------------------------------------/*static*/ void AIUpdateModuleData::buildFieldParse(MultiIniFieldParse& p)+/*static*/ void AIUpdateModuleData::buildFieldParse(MultiIniFieldParse& p){ModuleData::buildFieldParse(p);@@ -380,7 +301,6 @@ AIUpdateInterface::AIUpdateInterface( Thing *thing, const ModuleData* moduleDatam_pathfindGoalCell.x = m_pathfindGoalCell.y = -1;m_pathfindCurCell.x = m_pathfindCurCell.y = -1;m_blockedFrames = 0;- m_queueFrames = 0;m_curMaxBlockedSpeed = 0;m_bumpSpeedLimit = FAST_AS_POSSIBLE;m_ignoreCollisionsUntil = 0;@@ -1422,19 +1342,6 @@ Bool AIUpdateInterface::hasHigherPathPriority(AIUpdateInterface *otherAI) const//-------------------------------------------------------------------------------------------------/* Returns max speed we can have and not run into unit that is blocking us.-- EA set our ceiling to exactly the blocker's speed away from us and read no distance at all, so a- blocker that dipped for one frame stopped the follower for that frame whether it was one foot- behind or five - and the follower's own dip did the same to whoever was behind it. That is a- phantom jam: it grows as it travels backwards down a column, and it is a property of the rule- rather than of the traffic.-- The gap term is what a following model needs and this one had none of: match the leader's speed,- plus a correction proportional to how much room is left. Closer than we want, give some back;- further, close it up. Both units then hold a spacing instead of trading full stops.-- The head-on early return keeps its zero, but only for headings genuinely opposed. At exactly- zero it fired on anything a shade off perpendicular, which on a curve is most of a column.*/Real AIUpdateInterface::calculateMaxBlockedSpeed(Object *other) const{@@ -1444,21 +1351,19 @@ Real AIUpdateInterface::calculateMaxBlockedSpeed(Object *other) constCoord2D vectorToOther;vectorToOther.x = other->getPosition()->x - getObject()->getPosition()->x;vectorToOther.y = other->getPosition()->y - getObject()->getPosition()->y;- Real distance = vectorToOther.length();vectorToOther.normalize();Real dotProduct = vectorToOther.x*otherDir.x + vectorToOther.y*otherDir.y;- if (dotProduct<BLOCKED_HEAD_ON) return 0; // They are running into us.+ if (dotProduct<0) return 0; // They are running into us.Real speedFactor = dotProduct;- if (speedFactor < 0) speedFactor = 0; // off to one side: they are taking nothing with themPhysicsBehavior *otherPhysics = other->getPhysics();if (!otherPhysics) {return m_curMaxBlockedSpeed;- }+ }Coord3D otherVel = *otherPhysics->getVelocity();otherVel.z = 0;// Calculate how fast other is moving away from us...- Real awaySpeed = otherVel.length() * speedFactor;+ Real awaySpeed = otherVel.length() * speedFactor;// Now calculate the amount we are moving relative to towards them...dotProduct = vectorToOther.x*ourDir.x + vectorToOther.y*ourDir.y;@@ -1467,17 +1372,9 @@ Real AIUpdateInterface::calculateMaxBlockedSpeed(Object *other) constreturn m_curMaxBlockedSpeed;}Real maxSpeed = awaySpeed / dotProduct;-- // the room between the two hulls, and the room we would like there to be- Real myRadius = getObject()->getGeometryInfo().getBoundingCircleRadius();- Real hisRadius = other->getGeometryInfo().getBoundingCircleRadius();- Real gap = distance - (myRadius + hisRadius);- Real desiredGap = 0.5f * PATHFIND_CELL_SIZE_F;if (other->getFormationID()!=NO_FORMATION_ID && getObject()->getFormationID()==other->getFormationID()) {- desiredGap *= 2.0f; // don't let formations crowd each other.+ maxSpeed *= 0.55f; // don't let formations crowd each other.}- maxSpeed = AIUpdate_followSpeed( maxSpeed, gap, desiredGap );-if (maxSpeed>m_curMaxBlockedSpeed) return m_curMaxBlockedSpeed;return maxSpeed;}@@ -1620,34 +1517,7 @@ Bool AIUpdateInterface::needToRotate(void)//--------------------------------------------------------------------------------------------------/* Returns TRUE if this unit has spent long enough standing behind other units to call it a queue- rather than a moment of traffic. See QUEUE_FRAMES_THRESHOLD at the top of this file. */-Bool AIUpdateInterface::isQueuedBehindUnits(void) const-{- return AIUpdate_isQueued( m_queueFrames );-}--//--------------------------------------------------------------------------------------------------/* Called at the end of every path computation. The search that just ran is the detour, so the- credit is spent and the unit counts again from zero to decide whether it worked - without this- a queued unit asks for a new path on every frame for as long as it is queued. It is also where- the headless run's "queuedetour" count comes from: how often a unit gave up on the line it was- standing in, which is the number that says whether a change to the threshold did anything. */-void AIUpdateInterface::spendQueueCredit(void)-{- if (isQueuedBehindUnits())- {- Pathfinder::bumpQueueDetour();- // the headless counter only prints at the end of an unattended run, and this behaviour is- // something you watch happen in a real game - so say it in the log too, once per detour- DEBUG_LOG(("QUEUE DETOUR: frame %d, '%s' %d leaving a queue\n", TheGameLogic->getFrame(),- getObject()->getTemplate()->getName().str(), getObject()->getID()));- }- m_queueFrames = 0;-}--//--------------------------------------------------------------------------------------------------/* Returns TRUE if the physics collide should apply the force. Normally not.+/* Returns TRUE if the physics collide should apply the force. Normally not.Also determines whether objects are blocked, and if so, if they are stuck. jba.*/Bool AIUpdateInterface::processCollision(PhysicsBehavior *physics, Object *other){@@ -1684,7 +1554,7 @@ Bool AIUpdateInterface::processCollision(PhysicsBehavior *physics, Object *other}}m_isBlocked = TRUE; // we are blocked.- if (otherMoving && aiOther->isWaitingForPath())+ if (otherMoving && aiOther->isWaitingForPath()){return FALSE; // let them get their path;}@@ -1887,7 +1757,6 @@ Bool AIUpdateInterface::computeQuickPath( const Coord3D *destination )m_pathTimestamp = TheGameLogic->getFrame();m_blockedFrames = 0;- spendQueueCredit();m_isBlockedAndStuck = FALSE;return TRUE;}@@ -1898,6 +1767,7 @@ Bool AIUpdateInterface::computeQuickPath( const Coord3D *destination )*/Bool AIUpdateInterface::computePath( PathfindServicesInterface *pathServices, Coord3D *destination ){+if (!m_isBlockedAndStuck) {destroyPath();}@@ -1963,10 +1833,8 @@ Bool AIUpdateInterface::computePath( PathfindServicesInterface *pathServices, Co}if (theNewPath==NULL && m_path==NULL) {Real pathCostFactor = 0.0f;- // a unit leaving a queue is blocked in every sense that matters to the search, even though- // nothing has been jammed against it long enough to call it stuck- theNewPath = pathServices->findClosestPath( getObject(), m_locomotorSet, getObject()->getPosition(),- destination, m_isBlockedAndStuck || isQueuedBehindUnits(), pathCostFactor, FALSE );+ theNewPath = pathServices->findClosestPath( getObject(), m_locomotorSet, getObject()->getPosition(),+ destination, m_isBlockedAndStuck, pathCostFactor, FALSE );m_retryPath = true;}TheAI->pathfinder()->setIgnoreObstacleID( INVALID_ID );@@ -2010,7 +1878,6 @@ Bool AIUpdateInterface::computePath( PathfindServicesInterface *pathServices, Com_pathTimestamp = TheGameLogic->getFrame();m_blockedFrames = 0;- spendQueueCredit();m_isBlockedAndStuck = FALSE;if (m_path)return TRUE;@@ -2030,11 +1897,10 @@ Bool AIUpdateInterface::computeAttackPath( PathfindServicesInterface *pathServic{// jba intense debug//CRCDEBUG_LOG(("Info - RePathing very quickly %d, %d.\n", m_pathTimestamp, TheGameLogic->getFrame()));- if (m_path && m_isBlockedAndStuck)+ if (m_path && m_isBlockedAndStuck){setIgnoreCollisionTime(2*LOGICFRAMES_PER_SECOND);m_blockedFrames = 0;- spendQueueCredit();m_isBlocked = FALSE;m_isBlockedAndStuck = FALSE;return TRUE;@@ -2247,7 +2113,6 @@ Bool AIUpdateInterface::computeAttackPath( PathfindServicesInterface *pathServicm_pathTimestamp = TheGameLogic->getFrame();m_blockedFrames = 0;- spendQueueCredit();m_isBlockedAndStuck = FALSE;//CRCDEBUG_LOG(("AIUpdateInterface::computeAttackPath() done\n"));if (m_path)@@ -2375,16 +2240,12 @@ UpdateSleepTime AIUpdateInterface::doLocomotor( void )chooseGoodLocomotorFromCurrentSet();- m_queueFrames = AIUpdate_queueFrameStep( m_queueFrames, m_isBlocked );if (m_isBlocked){++m_blockedFrames;// this is the only place a blocked unit is counted once per frame rather than once per// collision pair, so it is where the traffic-jam number for the headless run comes fromPathfinder::bumpBlockedFrame( m_isBlockedAndStuck );- // and for the same reason it is where the jam map is stamped: this ground was not passable- // this frame, whatever the cell says by the time somebody searches it- TheAI->pathfinder()->noteJam( m_pathfindCurCell );}else{@@ -2464,22 +2325,26 @@ UpdateSleepTime AIUpdateInterface::doLocomotor( void )if( speed == FAST_AS_POSSIBLE || speed > myMaxSpeed )speed = myMaxSpeed;- if (blocked && speed>m_curMaxBlockedSpeed)+ if (blocked && speed>m_curMaxBlockedSpeed){- // track the ceiling instead of ratcheting down to it - see- // AIUpdate_smoothBlockedSpeed- m_bumpSpeedLimit = AIUpdate_smoothBlockedSpeed( m_bumpSpeedLimit, m_curMaxBlockedSpeed, speed );+ speed = m_curMaxBlockedSpeed;+ if (m_bumpSpeedLimit>speed) {+ m_bumpSpeedLimit = speed;+ }+ m_bumpSpeedLimit *= 0.95f;speed = m_bumpSpeedLimit;- }- else+ }+ else{blocked = FALSE;- if (m_bumpSpeedLimit<speed) {- // the same filter, now aimed at what we actually want- m_bumpSpeedLimit = AIUpdate_smoothBlockedSpeed( m_bumpSpeedLimit, speed, speed );+ if (m_bumpSpeedLimit<FAST_AS_POSSIBLE) {+ if (m_bumpSpeedLimit<speed*0.2f) {+ m_bumpSpeedLimit = speed*0.2f;+ }+ m_bumpSpeedLimit *= 1.05f;+ }+ if (speed>m_bumpSpeedLimit) {speed = m_bumpSpeedLimit;- } else {- m_bumpSpeedLimit = FAST_AS_POSSIBLE;}}@@ -2545,7 +2410,7 @@ UpdateSleepTime AIUpdateInterface::doLocomotor( void )getObject()->clearStatus( MAKE_OBJECT_STATUS_MASK( OBJECT_STATUS_AIRBORNE_TARGET ) );// before the ceiling is thrown away for the frame - it is the value the trace is about- AIUpdate_traceMove( getObject(), traceWasBlocked, m_blockedFrames, m_queueFrames,+ AIUpdate_traceMove( getObject(), traceWasBlocked, m_blockedFrames,m_desiredSpeed,m_curLocomotor->getMaxSpeedForCondition(getObject()->getBodyModule()->getDamageState()),m_curMaxBlockedSpeed, m_bumpSpeedLimit, isWaitingForPath(), getPath() != NULL,diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex 31812c602..61a7bcc53 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -6326,313 +6326,6 @@ TEST(headless_run_ends_on_a_decision_or_on_the_frame_limit)CHECK_STR( GameEngine_headlessRunResult( 3000, 2000, 3000 ), "decided" );}-extern Int Pathfinder_congestionPenalty( Int usage, Int costPerPath );--TEST(congestion_cost_is_charged_per_path_and_capped)-{- /* Another unit's live path through a cell we would step on costs us, so two units heading the- same way take parallel lanes instead of one queue. Empty ground stays free - a map with no- traffic on it has to path exactly as it always did. */- CHECK_EQ( 0, Pathfinder_congestionPenalty( 0, 5 ) );- CHECK_EQ( 0, Pathfinder_congestionPenalty( -1, 5 ) ); // usage is summed over a footprint that can leave the map-- // one path through the footprint costs one unit of the cost, two cost two- CHECK_EQ( 5, Pathfinder_congestionPenalty( 1, 5 ) );- CHECK_EQ( 10, Pathfinder_congestionPenalty( 2, 5 ) );-- /* and the cap is the point: the heuristic does not know about this cost, so an uncapped- penalty on a crowded cell inflates the search until it floods and the cell pool runs dry.- Four paths and forty pay the same as four. */- CHECK_EQ( 20, Pathfinder_congestionPenalty( 4, 5 ) );- CHECK_EQ( 20, Pathfinder_congestionPenalty( 5, 5 ) );- CHECK_EQ( 20, Pathfinder_congestionPenalty( 255, 5 ) ); // m_pathUsage is a byte: this is its ceiling-- /* The whole penalty has to stay small against the step costs it is added to (10 orthogonal,- 14 diagonal): a crowded cell may look worse than an empty one, never worse than a detour- around the map. */- CHECK( Pathfinder_congestionPenalty( 255, 5 ) <= 2*10 );-- /* The cost per path is a parameter because the cap has to move with it: whatever it is set to,- the ceiling stays four of them, which is the bound on how far a unit will go around. */- CHECK_EQ( 20, Pathfinder_congestionPenalty( 1, 20 ) );- CHECK_EQ( 80, Pathfinder_congestionPenalty( 4, 20 ) );- CHECK_EQ( 80, Pathfinder_congestionPenalty( 255, 20 ) );- CHECK( Pathfinder_congestionPenalty( 255, 20 ) <= 8*10 );-}--extern Int AIUpdate_queueFrameStep( Int queueFrames, Bool blocked );-extern Bool AIUpdate_isQueued( Int queueFrames );--TEST(a_queue_is_blocked_frames_that_decay_rather_than_reset)-{- /* The counter this replaces was zeroed by a single frame without a collision, and a unit at- the back of a column does not collide every frame - it creeps up, touches, backs its speed- off, drifts apart and touches again - so it never reached the two seconds that force a- repath and the column just stood there. This one decays. */-- /* Blocked every frame it climbs, and crosses the threshold inside a second or so. The exact- frame is a tuning constant and this test does not pin it: it pins that the threshold is- reached at all, that it takes long enough not to fire on a passing nudge, and that it comes- in under the two-second rule it exists to get in front of. */- Int q = 0;- Int framesToFire = 0;- while( !AIUpdate_isQueued( q ) && framesToFire < 1000 )- {- q = AIUpdate_queueFrameStep( q, true );- framesToFire++;- }- CHECK( AIUpdate_isQueued( q ) );- CHECK( framesToFire > 10 ); // a shove in traffic is not a queue- CHECK( framesToFire < 60 ); // 2*LOGICFRAMES_PER_SECOND: the rule this gets in front of-- // and it stops climbing, so a unit wedged for a minute carries no credit into open ground- for( Int i = 0; i < 1000; i++ )- q = AIUpdate_queueFrameStep( q, true );- CHECK_EQ( 80, q );-- // clear ground walks it back down to nothing, and no further- for( Int i = 0; i < 1000; i++ )- q = AIUpdate_queueFrameStep( q, false );- CHECK_EQ( 0, q );- CHECK( !AIUpdate_isQueued( q ) );-- /* The case that matters: touching two frames in three still gets there, where the old- reset-on-clear counter never left 1. Three frames a cycle, net +1. */- q = 0;- for( Int cycle = 0; cycle < 40; cycle++ )- {- q = AIUpdate_queueFrameStep( q, true );- q = AIUpdate_queueFrameStep( q, true );- q = AIUpdate_queueFrameStep( q, false );- }- CHECK( AIUpdate_isQueued( q ) );-- // but a unit that is merely nudged now and then - one frame in three - never fires- q = 0;- for( Int cycle = 0; cycle < 1000; cycle++ )- {- q = AIUpdate_queueFrameStep( q, true );- q = AIUpdate_queueFrameStep( q, false );- q = AIUpdate_queueFrameStep( q, false );- }- CHECK( !AIUpdate_isQueued( q ) );- CHECK_EQ( 0, q );-}--extern Real AIUpdate_followSpeed( Real leaderSpeed, Real gap, Real desiredGap );-extern Real AIUpdate_smoothBlockedSpeed( Real current, Real target, Real cap );--TEST(a_follower_keeps_a_gap_instead_of_matching_speed_exactly)-{- /* The rule this replaces gave the follower the leader's speed scaled by how much of the- leader's front it was facing, and knew nothing about the distance between them. Two units- nose to tail therefore ran at the same speed for ever: the gap that was there when they- first touched is the gap they keep, including a gap of zero. Then one touch of the brakes- at the front stopped the whole column, because a follower at zero distance has no slack to- spend. A gap law spends distance instead of stopping. */-- const Real desired = 5.0f;-- // sitting at the right distance: copy the leader and nothing else- CHECK_NEAR( 10.0f, AIUpdate_followSpeed( 10.0f, desired, desired ), 0.001f );-- // too close closes the throttle, and further in closes it further- CHECK( AIUpdate_followSpeed( 10.0f, 2.0f, desired ) < 10.0f );- CHECK( AIUpdate_followSpeed( 10.0f, 0.0f, desired )- < AIUpdate_followSpeed( 10.0f, 2.0f, desired ) );-- // too far opens it, which is what closes a gap that opened up mid-column- CHECK( AIUpdate_followSpeed( 10.0f, 10.0f, desired ) > 10.0f );-- /* Never negative. The caller uses this as a speed ceiling and a locomotor handed a negative- ceiling drives backwards. */- CHECK_NEAR( 0.0f, AIUpdate_followSpeed( 0.0f, 0.0f, 100.0f ), 0.001f );- CHECK( AIUpdate_followSpeed( 0.0f, -50.0f, 100.0f ) >= 0.0f );-- /* The property that makes it a queue rather than a concertina: start a follower stopped and- nose to tail behind a leader running at a steady speed, and it accelerates to the leader's- speed as the gap opens, without overshooting into a collision. Integrate the loop. */- Real gap = 0.0f;- Real speed = 0.0f;- const Real leader = 6.0f;- for( Int i = 0; i < 200; i++ )- {- speed = AIUpdate_followSpeed( leader, gap, desired );- gap += (leader - speed); // per frame: the leader pulls away by the speed difference- }- CHECK_NEAR( leader, speed, 0.05f ); // caught up to the leader's speed- CHECK_NEAR( desired, gap, 0.5f ); // at the distance it was asked to keep-}--TEST(the_blocked_speed_limit_relaxes_as_fast_as_it_tightens)-{- /* The limit this replaces was a ratchet: 0.95 per blocked frame down off a 20% floor, 1.05 per- clear frame up. Twenty blocked frames put a unit at 36% of its speed and forty at 13%, and- climbing back out of 13% cost about 33 clear frames - two thirds of a second of open ground- spent crawling for a jam that was over. That asymmetry is the stop-and-go the player sees.- A first order filter has the same smoothing and no memory of how long the jam lasted. */-- const Real full = 10.0f;-- // it moves toward the target rather than to it, so a one frame touch is not a one frame stop- Real limit = AIUpdate_smoothBlockedSpeed( full, 0.0f, full );- CHECK( limit < full );- CHECK( limit > 0.0f );-- // falling to a ceiling and rising back from it take the same number of frames- Real down = full;- Int framesDown = 0;- while( down > 0.5f * full && framesDown < 1000 )- {- down = AIUpdate_smoothBlockedSpeed( down, 0.0f, full );- framesDown++;- }- Real up = 0.0f;- Int framesUp = 0;- while( up < 0.5f * full && framesUp < 1000 )- {- up = AIUpdate_smoothBlockedSpeed( up, full, full );- framesUp++;- }- CHECK_EQ( framesDown, framesUp );- CHECK( framesUp < 10 ); // and recovery is frames, not the ratchet's thirty odd-- /* No memory: a unit blocked for one second and a unit blocked for ten come out of it at the- same speed, because the filter's state is where it is now, not how it got there. */- Real brief = full, forever = full;- for( Int i = 0; i < 30; i++ )- brief = AIUpdate_smoothBlockedSpeed( brief, 0.0f, full );- for( Int i = 0; i < 300; i++ )- forever = AIUpdate_smoothBlockedSpeed( forever, 0.0f, full );- for( Int i = 0; i < 30; i++ )- {- brief = AIUpdate_smoothBlockedSpeed( brief, full, full );- forever = AIUpdate_smoothBlockedSpeed( forever, full, full );- }- CHECK_NEAR( brief, forever, 0.01f );-- /* The cap is the speed the unit actually wants this frame, and the filter must never hand back- more than that - the caller assigns the result straight into the locomotor. */- CHECK( AIUpdate_smoothBlockedSpeed( 100.0f, 100.0f, full ) <= full );- CHECK( AIUpdate_smoothBlockedSpeed( full, 100.0f, full ) <= full );-- // a negative ceiling from a head-on blocker clamps to a stop, not to reverse- CHECK( AIUpdate_smoothBlockedSpeed( full, -50.0f, full ) >= 0.0f );-}--extern Bool AIState_looksLikeMoving( Real speedNow, Real maxSpeed );--TEST(the_drive_animation_asks_the_speed_and_not_the_frame_count)-{- /* EA cleared MODELCONDITION_MOVING after a quarter second of blocked frames, which is a count of- frames standing in for a speed. The case it gets wrong is the one that matters: a tank easing- round a jam is blocked most frames and still covering ground, and it was drawn parked and- sliding. This is the whole of P5, and no batch can measure it - a headless run draws nothing- - so the threshold is checked here or nowhere.-- A headless run cannot see the difference; a player can see nothing else. */- const Real top = 30.0f;-- // what the frame count got wrong: moving properly, blocked most frames, drawn parked- CHECK( AIState_looksLikeMoving( top, top ) );- CHECK( AIState_looksLikeMoving( top / 3.0f, top ) );- CHECK( AIState_looksLikeMoving( top * 0.5f, top ) );-- // and what it got right, which the speed test has to keep getting right- CHECK( !AIState_looksLikeMoving( 0.0f, top ) );- CHECK( !AIState_looksLikeMoving( top * 0.05f, top ) );-- // the threshold itself: a tenth, exclusive, so exactly a tenth is still parked- CHECK( !AIState_looksLikeMoving( top * 0.1f, top ) );- CHECK( AIState_looksLikeMoving( top * 0.1f + 0.01f, top ) );-- /* No locomotor to ask means no top speed, and then the question is only whether the thing is- moving at all - which is what the code did before the threshold went in. Something being- shoved has no drive of its own to animate away from. */- CHECK( !AIState_looksLikeMoving( 0.0f, 0.0f ) );- CHECK( AIState_looksLikeMoving( 0.5f, 0.0f ) );-- // the threshold scales with the unit, so a slow one is not held to a fast one's crawl- const Real slow = 3.0f;- CHECK( AIState_looksLikeMoving( slow * 0.5f, slow ) );- CHECK( !AIState_looksLikeMoving( slow * 0.5f, top ) );-}--extern Int Pathfinder_jamPenalty( Int jam );--TEST(a_jam_costs_only_after_it_has_lasted)-{- /* The congestion and queue costs both describe the instant the search runs, and a jam is not an- instant - a wedged doorway empties for a frame every time it shuffles, and the search that- happens to run in that frame routes another unit straight into it. The jam map remembers.- The floor is what keeps it from firing on ordinary traffic, and the cap is what keeps a cost- the A* heuristic cannot see from flooding the search. */- CHECK_EQ( 0, Pathfinder_jamPenalty( 0 ) );- CHECK_EQ( 0, Pathfinder_jamPenalty( -1 ) );-- // one unit pausing for a frame or two is traffic and costs nothing at all- CHECK_EQ( 0, Pathfinder_jamPenalty( 1 ) );- CHECK_EQ( 0, Pathfinder_jamPenalty( 3 ) );-- // past the floor it climbs per blocked unit-frame, and a step is worth three cells of ground- // (a cell of ground is COST_ORTHOGONAL, 10, which lives in AIPathfind.cpp and not in a header)- CHECK_EQ( 30, Pathfinder_jamPenalty( 4 ) );- CHECK_EQ( 60, Pathfinder_jamPenalty( 5 ) );-- /* And it stops. The stamp saturates at 10, so without a cap the worst ground on the map would- cost 21 cells of detour and the search would rather cross the map than pass a doorway. */- const Int most = Pathfinder_jamPenalty( 7 );- CHECK_EQ( most, Pathfinder_jamPenalty( 10 ) );- CHECK_EQ( most, Pathfinder_jamPenalty( 255 ) );- CHECK( most <= 120 );-}--extern Int Pathfinder_crossingPenalty( Int conflicts );--TEST(crossing_cost_is_charged_per_conflict_and_capped)-{- /* The congestion map says somebody's path runs through this cell; the reservation map says- *when* they will be in it. A cell two units want at the same moment, going different ways,- is a crossing, and it costs - a cell two units want minutes apart costs nothing. */- CHECK_EQ( 0, Pathfinder_crossingPenalty( 0 ) );- CHECK_EQ( 0, Pathfinder_crossingPenalty( -1 ) );-- // 60 per crossing: six orthogonal steps, i.e. worth going around a short way and no further- CHECK_EQ( 60, Pathfinder_crossingPenalty( 1 ) );- CHECK_EQ( 120, Pathfinder_crossingPenalty( 2 ) );-- /* Capped at three for the same reason the congestion cost is capped: the heuristic cannot see- this cost, so an uncapped one on a busy junction floods the search. A junction thirty units- want at once is a junction, not a reason to walk around the map. */- CHECK_EQ( 180, Pathfinder_crossingPenalty( 3 ) );- CHECK_EQ( 180, Pathfinder_crossingPenalty( 4 ) );- CHECK_EQ( 180, Pathfinder_crossingPenalty( 1000 ) );-}--extern Bool Pathfinder_reservationsClash( UnsignedInt frameA, Real headingAX, Real headingAY,- UnsignedInt frameB, Real headingBX, Real headingBY );--TEST(two_claims_on_a_cell_clash_only_at_the_same_moment_and_across_each_other)-{- // head-on, same frame: the crossing this whole cost exists for- CHECK( Pathfinder_reservationsClash( 100, 1.0f, 0.0f, 100, -1.0f, 0.0f ) );- // at right angles, eleven frames apart - still inside the twelve-frame window- CHECK( Pathfinder_reservationsClash( 100, 1.0f, 0.0f, 111, 0.0f, 1.0f ) );-- /* The window is how long a tank owns a ten-unit cell. Twelve frames apart is not the same- moment, in either order - and the frames are unsigned, so the older-first case must not- subtract its way into a huge positive number. */- CHECK( !Pathfinder_reservationsClash( 100, 1.0f, 0.0f, 112, 0.0f, 1.0f ) );- CHECK( !Pathfinder_reservationsClash( 112, 0.0f, 1.0f, 100, 1.0f, 0.0f ) );- CHECK( !Pathfinder_reservationsClash( 0, 1.0f, 0.0f, 5000, -1.0f, 0.0f ) );-- /* Traffic going your way is a queue, not a crossing. Charging it prices hundreds of following- pairs per order and buys nothing: the unit behind you is where you are about to not be. */- CHECK( !Pathfinder_reservationsClash( 100, 1.0f, 0.0f, 100, 1.0f, 0.0f ) );- CHECK( !Pathfinder_reservationsClash( 100, 1.0f, 0.0f, 100, 0.707107f, 0.707107f ) ); // 45 deg- CHECK( Pathfinder_reservationsClash( 100, 1.0f, 0.0f, 100, 0.0f, 1.0f ) ); // 90 deg-}-TEST(a_replay_game_is_never_itself_recorded){// what a replay is worth writing: a game a human played in real time@@ -6690,33 +6383,16 @@ TEST(an_option_read_before_the_parser_exists_is_read_on_word_boundaries)CHECK( !findCommandLineValueIn( L"-logPrefix abcdef", L"-logPrefix", tiny, 0 ) );}-TEST(the_two_group_movement_switches_are_on_until_the_command_line_says_otherwise)+TEST(the_slow_frame_bar_moves_only_for_a_positive_number){- /* Both of these were declared with a comment promising a switch and then never written, never- read and never initialised - so the field held whatever the allocator left there, and the- only way to measure either mechanism was to build a second exe. A control arm has to be in- the same binary as the thing it is controlling: two exes differ in more than the change. */+ /* -slowframe lowers the bar a logic frame has to clear before it writes its own breakdown,+ which is how a subsystem's cost gets hunted rather than a stutter. A value that is not a+ positive number leaves the default alone rather than silencing the log. */GlobalData *saved = TheWritableGlobalData;TheWritableGlobalData = NEW GlobalData;- // the default is what this fork has always done: the shared corridor, and the crossing cost- CHECK( TheGlobalData->m_useGroupPaths );- CHECK( TheGlobalData->m_useCrossingCost );-- char exe[] = "generals.exe";- char noGroupPath[] = "-nogrouppath";- char noCrossTime[] = "-NOCROSSTIME"; // the table matches case-insensitively- char *argv[] = { exe, noGroupPath, noCrossTime };- parseCommandLine( 3, argv );-- CHECK( !TheGlobalData->m_useGroupPaths );- CHECK( !TheGlobalData->m_useCrossingCost );-- /* -slowframe is the third of the same family: it lowers the bar a logic frame has to clear- before it writes its own breakdown, which is how a subsystem's cost gets hunted rather than- a stutter. A value that is not a positive number leaves the default alone rather than- silencing the log. */CHECK_NEAR( TheGlobalData->m_slowFrameMS, 20.0f, 0.001f );+ char exe[] = "generals.exe";char slowFrame[] = "-slowframe";char three[] = "3";char *argvSlow[] = { exe, slowFrame, three };diff --git a/ai-batch.ps1 b/ai-batch.ps1index 7cf599f50..8c9ce16cd 100644--- a/ai-batch.ps1+++ b/ai-batch.ps1@@ -61,7 +61,7 @@ param(# between batches - and the only way to run a batch at all while a copy of the game is open.[string] $Exe = "generals.exe",# extra arguments handed to every run, for sweeping a knob the game reads from the command line- # (e.g. -ExtraArgs "-pathcongestion",'10') without a rebuild between batches+ # (e.g. -ExtraArgs "-aislice",'4') without a rebuild between batches[string[]] $ExtraArgs = @(),# minutes before a wedged run is killed rather than waited on forever[int] $TimeoutMinutes = 20@@ -138,7 +138,7 @@ 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; QueueDetour = 0 }+ $pf = [pscustomobject]@{ FindMs = 0.0; Finds = 0; Expands = 0; NoPath = 0; OutOfCells = 0; Blocked = 0; Stuck = 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 = @{}@@ -188,7 +188,6 @@ 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] }- if ($report -match "queuedetour (\d+)") { $pf.QueueDetour = [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]@{@@ -260,10 +259,6 @@ if ($pfRows.Count -gt 0) {$totFrames = ($pfRows | Measure-Object Frames -Sum).Sum$totBlocked = ($pfRows | ForEach-Object { $_.Pf.Blocked } | Measure-Object -Sum).SumWrite-Host ("blocked unit-frames per 1000 logic frames: {0:n1}" -f (1000.0 * $totBlocked / $totFrames))- # how often a unit gave up on the line it was standing in and repathed round it. Zero here and- # a change to the queue detour cannot have done anything, good or bad.- $totDetour = ($pfRows | ForEach-Object { $_.Pf.QueueDetour } | Measure-Object -Sum).Sum- Write-Host ("queue detours per 1000 logic frames: {0:n1}" -f (1000.0 * $totDetour / $totFrames))}# Stability. A mean frame time is the statistic that hides a stutter, so this reports the tail: