Skip to content

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

feat(gameengine): pro rules 12-17 and a crowd model with no switch

Olcay Seygan04c0e1e299b9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c0709cb9b..d6ec3339c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -323,6 +323,7 @@ found and fixed — EA's own, not port damage.**
- A worker that is building something still offers you the whole build list.
- The GLA's decoy build list toggles both ways now.
- Workers go back to collecting supplies when they finish.
+- Workers and supply trucks walk to a pile up to 1400 feet away, the reach the computer opponent always had. Yours gave up at 700: when the pile beside your base ran dry they went home and stood there, with the next pile in plain sight.
- Every countdown reads real seconds and answers the game speed.
- The clock and frame-rate readout is drawn on top of everything.
- The superweapon countdowns are pictures now, not a list of names: the same strip treatment, in the top right corner, under that readout. Each one wears its own seconds and a sweeping clock, the next to land sits at the right hand end, and if you are watching more than eighteen of them the rest become a count.
@@ -491,6 +492,8 @@ found and fixed — EA's own, not port damage.**
- No foundation goes down closer to an enemy building than 300, a margin past the 225 a Patriot battery or a Stinger Site reaches on the ground. That ends walling somebody's base in with scaffolds nobody means to finish, and it ends building a tower in their yard too. The placement ghost says why it is red.
- The computer opponent is held to the same list, because it asks the same question your build buttons ask before it spends a dollar.
- With these rules on, the superweapon dropdown above decides one thing: how many Nuclear Missile silos a player may have standing.
+- No suicide bomb upgrade for the Demolition General, no Neutron Shells and no Stealth Comanche. The Carpet Bomb stays grey until its owner reaches three stars, which holds back the Air Force General, who can buy his at one.
+- Two towers per oil derrick. Your Patriot batteries, Gattling Cannons and Stinger Sites near a derrick count against it, and derricks standing together on the map share one allowance, so the pair 250 apart on Tournament Plains is one derrick for this. The third tower's placement ghost goes red and says why. Your ally's towers do not use up your two, and tunnels are not limited.
## Two windows, one machine, a real LAN game
@@ -1056,6 +1059,8 @@ found and fixed — EA's own, not port damage.**
- None of the crowd was being measured, and the numbers written here for it were another rule's. A unit steers as part of a crowd only if it was handed a line across the road, a line is handed out only by the order a player gives to a selection, and a computer opponent never gives that order: it moves its teams one vehicle at a time. So every self-play batch run to argue about the crowd was driving the two rules that live in the collision code and none of the steering. The harness now has a switch that hands every army on the map one group order every twenty seconds, to alternating corners. The match it produces is nonsense and its result says nothing, but it multiplies the time units spend standing still by fourteen, from around 300 unit-frames a match to 4,200, which is the proof it is finally creating the traffic the crowd was written for.
- With the traffic there, the crowd steering does not pay for itself. Thirty-nine battles paired map by map: time spent standing behind another unit 4,444 unit-frames a match with the rules off against 4,787 with them on, 7.7% worse, eleven maps better and twenty worse. The middle map moved by 19 unit-frames either way, so that average is four bad maps carrying thirty-five that barely noticed. What it does fix is the thing it was asked to fix. Units left properly stuck fell from 3.0 a match to 1.4, and the maps that moved are the pathological ones: 62 units wedged for good down to none, 35 down to none, 7 down to none. It creates new ones elsewhere, one map going from 5 to 34. The switch stays off, and what needs explaining now is the four maps, not the average.
- A network game now runs the shipped rules no matter what was typed to start it. Half a dozen switches exist so that the same build can be run twice and the two compared, and every one of them changes what a unit or the computer opponent decides: the crowd model, the three that put a piece of the movement back the way it shipped in 2003, how often a unit thinks, and the truce clock. Two players deciding differently is a match that comes apart on the first order rather than one that refuses the join, so online they are all off and the host's lobby settings are the only settings. Anyone who turned one on to look at it can still play with anyone who did not. A replay keeps whatever it was recorded with.
+- Then the switches themselves went, because a switch that changes what a unit decides is a way to start two copies of the game that play different matches. The crowd steering is no longer something you start the game with: every match drives with it now, the computer's armies included. The three that put a piece of 2003 movement back are gone and the movement they could turn off is always on. The group drill that measured the crowd went too, and so did the setting for how often a unit thinks, which nobody had ever measured.
+- A group no longer drops to half speed at every corner of its route. The crowd steering slowed a vehicle to as little as 55% wherever the road turned, on top of the slowing down the tank already does for a turn it cannot take, and a pathfinder route turns all the time: a quarter of the steering on a twenty-tank test sat under it, and a tank with the road to itself averaged 92% of its speed. Without it the same twenty Crusaders cross the same ramp to the enemy base in 71 seconds instead of 86, three seconds quicker than with no crowd steering at all, and the time they spend stuck behind each other fell by a third. The truce clock and the unit limit stay, since both are lobby settings the host picks for everyone.
- Since the first attempt at the band failed silently and passed every test it had, the band can now be drawn. A switch puts each moving unit's route on the ground in blue, the line it holds as a yellow mark sideways from the unit, and the offset that survived as a green mark from the route out to where the unit is actually aiming. The three failures that look identical from the camera - a line never given out, a line given out and dropped on the way, a line applied but too small to see - are three different pictures under it, and the same run writes them to the log as well.
---
diff --git a/GeneralsMD/Code/Data/Patch.str b/GeneralsMD/Code/Data/Patch.str
index e3b65ccc8..16b9148e3 100644
--- a/GeneralsMD/Code/Data/Patch.str
+++ b/GeneralsMD/Code/Data/Patch.str
@@ -834,10 +834,15 @@ GUI:ProRules
END
TOOLTIP:ProRules
-"The tournament list. No Particle Cannon or SCUD Storm, except the Superweapon General's one cannon. The Nuclear Missile silo goes up but never fires. No Aurora, no Tactical Nuke MiGs, no demo bike. A Microwave Tank cannot freeze a building still going up, and nobody builds within 300 of an enemy building."
+"The tournament list. No Particle Cannon or SCUD Storm, except the Superweapon General's one cannon. The Nuclear Missile silo goes up but never fires. No Aurora, no Tactical Nuke MiGs, no demo bike, no suicide bombs, Neutron Shells or Stealth Comanche, and no Carpet Bomb before rank 3. A Microwave Tank cannot freeze a building still going up, nobody builds within 300 of an enemy building, and nobody puts more than two Patriots, Gatling Cannons or Stinger Sites round one group of oil derricks."
END
// Pro Rules, rule 9: no foundation within reach of an enemy building
GUI:CantBuildTooCloseToEnemy
"Can't build this close to an enemy building."
END
+
+// Pro Rules, rule 16: two defenses to a group of oil derricks
+GUI:CantBuildTooManyDerrickDefenses
+"You already have two defenses round these oil derricks."
+END
diff --git a/GeneralsMD/Code/Data/Scenarios/chokeprobe.txt b/GeneralsMD/Code/Data/Scenarios/chokeprobe.txt
new file mode 100644
index 000000000..a534bb4e7
--- /dev/null
+++ b/GeneralsMD/Code/Data/Scenarios/chokeprobe.txt
@@ -0,0 +1,26 @@
+# Choke probe (ROADMAP M0.3).
+#
+# Twenty tanks, one order, one clock: how long the last of them takes to reach the other start. Win
+# rate cannot judge a pathfinding change, because a symmetric batch only says the match plays
+# differently. This says whether a column got through faster or slower.
+#
+# generals.exe -headless -quickstart -noshellmap -observer -multiInstance -noFPSLimit
+# -randommap 3 2 small -autoskirmish 2 -takeover -seed 3 -maxframes 4000
+# -scenario chokeprobe -logPrefix choke_
+#
+# then grep the log for HEADLESS ARRIVE. An A/B is two builds run with the same line; the map, the
+# seats and the army do not change between the two. Add -showlanes for the crowd model's own trail.
+#
+# Positions are start<N>, where seat N began, so the file does not care which seed built the map. A
+# generated map terraces the ground and cuts ramps between the plateaus, so the route from one start
+# to the other goes down at least one ramp and up another: those ramps are the choke.
+#
+# <frame> spawn <slot> <template> <count> <position> [spacing]
+# <frame> move <slot> <selector> <position>
+# <frame> arrive <slot> <selector> <position> [radius]
+#
+# start0:dx:dy stands dx, dy off the start, which keeps the block of tanks off the command center.
+
+30 spawn 0 AmericaTankCrusader 20 start0:0:260 40
+60 move 0 AmericaTankCrusader start1
+60 arrive 0 AmericaTankCrusader start1 250
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/BuildAssistant.h b/GeneralsMD/Code/GameEngine/Include/Common/BuildAssistant.h
index ef0e84ff5..5b5ea6198 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/BuildAssistant.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/BuildAssistant.h
@@ -97,6 +97,7 @@ enum LegalBuildCode
LBC_TOO_CLOSE_TO_SUPPLIES,
LBC_GENERIC_FAILURE,
LBC_TOO_CLOSE_TO_ENEMY, ///< Pro Rules: within PRO_RULES_ENEMY_STRUCTURE_CLEARANCE of an enemy building
+ LBC_TOO_MANY_DERRICK_DEFENSES, ///< Pro Rules: the player's own defences round this oil derrick cluster are full
};
//-------------------------------------------------------------------------------------------------
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
index 3129d483c..7ca3916fe 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
@@ -397,13 +397,7 @@ public:
Coord2D m_cameraLook; ///< where -camera pointed it
Int m_traceMoveID; ///< -tracemove [id]: log one movement line a frame for this object (0 = off, -1 = the first unit that gets blocked)
Real m_slowFrameMS; ///< -slowframe <ms>: a logic frame over this long logs its own breakdown (default 20)
- Int m_aiSliceFrames; ///< -aislice <n>: a unit's AI decides once every n logic frames, staggered by id (1 = every frame, the default)
- Bool m_noFlowPath; ///< -noflowpath: price terrain only, the way retail does - no clearance, traffic or crossing cost
- Bool m_noLanePath; ///< -nolanes: follow the centre of the route, the way retail does - no band, no lane, no passing
- Bool m_noMomentumPath; ///< -nomomentum: charge a turn retail's flat 4/8/16 instead of what this hull's own turn rate costs
Bool m_showLanes; ///< -showlanes: draw every moving unit's route, the lane it was handed and the offset it kept
- Bool m_crowdModel; ///< -crowd: the sandbox crowd model - corridor, absolute lanes, right of way, give way, fan out
- Int m_groupDrill; ///< -groupdrill <n>: every n frames, order each player's army corner to corner as one group (0 = off)
Int m_uiDrill; ///< -uidrill <n>: every n frames, minimise the command bar and re-apply its scheme, logging where it landed (0 = off)
Int m_resDrillFrame; ///< -resdrill <frame> [w] [h]: change the resolution at that logic frame, from inside a running match (0 = off)
Int m_resDrillX; ///< the width -resdrill asks for (0 = the next mode the device offers)
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Player.h b/GeneralsMD/Code/GameEngine/Include/Common/Player.h
index e5e7abb6c..7aa27ee8a 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/Player.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/Player.h
@@ -132,17 +132,37 @@ Bool UnitCapRefuses( Int unitsTowardCap, Int unitsItAdds, UnsignedInt unitCap );
// GameLogic::isProRules() says whether a match is under them; these say what they cover, by name
// or by type, so a test can ask them without a match.
enum SpecialPowerType;
+class Player;
Bool ProRulesBanThing( const AsciiString &templateName );
Bool ProRulesExemptSuperweapon( const AsciiString &templateName );
-Bool ProRulesBanUpgrade( const AsciiString &upgradeName );
-Bool ProRulesBanSpecialPower( SpecialPowerType specialPowerType );
Bool ProRulesBanRider( const AsciiString &riderTemplateName );
+// Rule 15: nobody fires a Carpet Bomb below this rank.
+enum { PRO_RULES_CARPET_BOMB_RANK = 3 };
+
+// rules 6 and 12 to 14
+Bool ProRulesBanUpgrade( const AsciiString &upgradeName );
+// rules 2 and 15, for a player of this rank
+Bool ProRulesBanSpecialPower( SpecialPowerType specialPowerType, Int rankLevel );
+// the one above asked about the match being played, and about the player's own rank
+Bool ProRulesRefuseSpecialPower( const Player *player, SpecialPowerType specialPowerType );
+
// Rule 9: no foundation this close to an enemy building, edge to edge. The same 300 world units
// the derrick cluster rules measure with, which is also more than a Patriot or a Stinger Site
// reaches on the ground, so a scaffold wall cannot be laid under an enemy's own defences.
enum { PRO_RULES_ENEMY_STRUCTURE_CLEARANCE = 300 };
+// Rule 16: a player may have this many Patriots, Gatling Cannons and Stinger Sites around one cluster
+// of oil derricks. A cluster is every derrick reachable from another in steps no longer than the
+// radius, and a structure whose centre is within the radius of any derrick in it belongs to it.
+// Rule 17 allows tunnels without a cap, so it needs no check at all.
+enum { PRO_RULES_DERRICK_CLUSTER_RADIUS = 300, PRO_RULES_DEFENSES_PER_DERRICK_CLUSTER = 2 };
+Bool ProRulesIsOilDerrick( const AsciiString &templateName );
+Bool ProRulesIsDerrickDefense( const AsciiString &templateName );
+// How many of the defenses belong to the cluster the spot belongs to, 0 when no derrick is in reach
+Int ProRulesCountDerrickClusterDefenses( const Coord2D &spot, const Coord2D *derricks, Int derrickCount,
+ const Coord2D *defenses, Int defenseCount );
+
static const Int NUM_HOTKEY_SQUADS = 10;
enum { NO_HOTKEY_SQUAD = -1 };
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/CrowdModel.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/CrowdModel.h
index 60cdf5ceb..07361af9a 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/CrowdModel.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/CrowdModel.h
@@ -18,7 +18,7 @@
// FILE: CrowdModel.h //////////////////////////////////////////////////////////////////////////
// The route as a band of measured width, and the rules a unit uses to decide where across it to
-// drive. Everything here is behind -crowd; without it none of it is built or consulted.
+// drive.
//
// The band is the part retail has no equivalent of. A route is a line, every unit handed one
// steers at the same metre of it, and a group of twenty crossing open ground therefore drives in
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h
index 16a0c5884..ad99dca9e 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h
@@ -385,7 +385,6 @@ private:
UnsignedInt m_peaceTimeEndFrame; ///< logic frame the lobby's peace time runs out on, 0 = no peace time
UnsignedInt m_unitCap; ///< units each player may have standing and queued, 0 = no limit
Bool m_proRules; ///< this match refuses what PRO-RULES.md bans
-
LoadScreen *getLoadScreen( Bool loadSaveGame );
LoadScreen *m_loadScreen;
Bool m_gamePaused;
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
index 0b2b3895b..1fc6de170 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h
@@ -502,7 +502,7 @@ public:
a rescaling of the one above: this one is a distance in world units, positive to the left of
the route, and it means the same thing wherever the unit is standing. A fraction of the
local width does not - it drags a unit into every wide bay its route happens to pass and
- swings it round the outside of corners. Only read under -crowd. */
+ swings it round the outside of corners. */
void setPendingCrowdLat( Real lat ) { m_pendingCrowdLat = lat; m_hasPendingCrowdLat = TRUE; }
/** Where this member sat across the group, as a place in a queue rather than a distance: `idx`
@@ -514,7 +514,7 @@ public:
the rest of the trip, because nothing ever asked the question again. The slot is asked every
frame against the band at the unit's own sample, so the group is as wide as the ground under
it right now: single file in the gate, six abreast on the far side, and back to single file
- at the next one. Only read under -crowd. */
+ at the next one. */
void setPendingCrowdLane( Int idx, Int of, Real spacing )
{ m_crowdLaneIdx = idx; m_crowdLaneOf = of; m_crowdLaneSpace = spacing; }
@@ -746,12 +746,6 @@ private:
/// Pick this unit's lane off its own sideways distance from the route it was just handed.
void seedLaneFraction( void );
- /** Slide across the band to get past somebody who is not moving out of the way.
- Called from the collision path, which already has the blocker in hand: no query is made
- here on purpose, because the order a query returns objects in is part of the logic CRC
- and a movement rule that depends on it desyncs every replay and every network game. */
- void tryLaneChangeAround( Object *other );
-
/** The crowd model, one frame, one unit: measure the band if it has not been measured, look at
the neighbours once, and come back with where to steer and how fast. Everything the sandbox
does per frame - separation, right of way, priority, passing, fanning out, easing through a
@@ -832,29 +826,29 @@ private:
UnsignedInt m_laneHoldFrame; ///< A lane taken to get round somebody is kept until this frame.
Real m_pendingLane; ///< Lane the ordering group picked for us, waiting for the path to arrive.
Bool m_hasPendingLane; ///< False when nobody handed us one and we have to measure our own.
- CrowdCorridor* m_corridor; ///< -crowd: the current route with the width of the ground beside it. Owned; dies with the path.
- Real m_crowdLat; ///< -crowd: how far left of the route we ride, in world units.
- Real m_pendingCrowdLat; ///< -crowd: the same, as the ordering group wanted it, waiting for the path.
- Bool m_hasPendingCrowdLat; ///< -crowd: FALSE for a unit ordered on its own, which rides where it already is.
- Int m_crowdLaneIdx; ///< -crowd: our place across the group, 0 = leftmost.
- Int m_crowdLaneOf; ///< -crowd: how many of us there were; 0 = nobody handed us a slot.
- Real m_crowdLaneSpace; ///< -crowd: how far apart the group wanted its lanes, one widest body plus air.
- Int m_crowdFit; ///< -crowd: how many lanes the band is currently held to carry; 0 = not worked out yet.
- Bool m_crowdLatValid; ///< -crowd: FALSE until the lane has been taken up against the current route.
- UnsignedInt m_crowdHoldFrame; ///< -crowd: a lane taken to pass somebody is kept until this frame.
- Int m_crowdSample; ///< -crowd: which sample of the band we were beside last frame (search hint; -1 = no band).
- Int m_crowdQueued; ///< -crowd: consecutive frames spent braking or stuck behind somebody.
- Int m_crowdSide; ///< -crowd: which side we prefer to pass on, +1 left, -1 right.
+ CrowdCorridor* m_corridor; ///< thecurrent route with the width of the ground beside it. Owned; dies with the path.
+ Real m_crowdLat; ///< howfar left of the route we ride, in world units.
+ Real m_pendingCrowdLat; ///< thesame, as the ordering group wanted it, waiting for the path.
+ Bool m_hasPendingCrowdLat; ///< FALSEfor a unit ordered on its own, which rides where it already is.
+ Int m_crowdLaneIdx; ///< ourplace across the group, 0 = leftmost.
+ Int m_crowdLaneOf; ///< howmany of us there were; 0 = nobody handed us a slot.
+ Real m_crowdLaneSpace; ///< howfar apart the group wanted its lanes, one widest body plus air.
+ Int m_crowdFit; ///< howmany lanes the band is currently held to carry; 0 = not worked out yet.
+ Bool m_crowdLatValid; ///< FALSEuntil the lane has been taken up against the current route.
+ UnsignedInt m_crowdHoldFrame; ///< a lanetaken to pass somebody is kept until this frame.
+ Int m_crowdSample; ///< whichsample of the band we were beside last frame (search hint; -1 = no band).
+ Int m_crowdQueued; ///< consecutiveframes spent braking or stuck behind somebody.
+ Int m_crowdSide; ///< whichside we prefer to pass on, +1 left, -1 right.
/* The rest of the crowd state is transient and deliberately not saved, for the same reason the
band itself is not: a filter, a stuck count and a half-finished backing-out manoeuvre are all
rebuilt within a second of the load, and a saved one restarts a jam that is over. */
- Real m_crowdSepSmooth; ///< -crowd: low-passed sideways push from the neighbours.
- Real m_crowdAim; ///< -crowd: low-passed direction the steering point is taken in, radians.
- Bool m_crowdAimValid; ///< -crowd: FALSE until the filter has something to start from.
- /* Being stuck, and getting out of it. None of this is behind -crowd: a unit that has stopped
- without a collision to show for it is not a crowd problem, it is the problem, and until this
- was pulled out of the crowd model it was only ever asked about units that happened to have
- been handed a lane by a group order. */
+ Real m_crowdSepSmooth; ///< low-passedsideways push from the neighbours.
+ Real m_crowdAim; ///< low-passeddirection the steering point is taken in, radians.
+ Bool m_crowdAimValid; ///< FALSEuntil the filter has something to start from.
+ /* Being stuck, and getting out of it. None of this is part of the crowd model: a unit that has
+ stopped without a collision to show for it is not a crowd problem, it is the problem, and
+ until this was pulled out of the crowd model it was only ever asked about units that happened
+ to have been handed a lane by a group order. */
Int m_noProgress; ///< consecutive frames wanting to move, not moving, not turning either.
Coord3D m_lastProgressPos; ///< where we were last frame, which is how the above is counted.
Real m_lastProgressAngle; ///< and which way we were pointing, because coming about is progress too.
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h
index 63a72ff9c..6c05f2bf7 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h
@@ -26,7 +26,7 @@
// ask for. A scenario file names the unit, the place, the count and the frame, so the same
// command line puts the same army on the same ground in two different builds.
//
-// Orders go out the way -groupdrill's do - an AIGroup built inside the logic frame, ordered with
+// Orders go out as an AIGroup built inside the logic frame, ordered with
// CMD_FROM_SCRIPT - and not through TheMessageStream. Two reasons. A GameMessage is stamped with
// the local player and the fake index a harness would write does not survive a network game
// (NetCommandMsg re-stamps it with the sender's). Worse for a measurement, messages propagate on
@@ -34,7 +34,7 @@
// and two builds that draw at different speeds would then be playing different scenarios. A tick
// keyed to the logic frame has neither problem.
//
-// The bill for that is the same one -groupdrill pays: these orders exist nowhere in the command
+// The bill for that: these orders exist nowhere in the command
// stream, so a run driven by a scenario cannot be replayed. Repeatability comes from the file
// plus -seed instead, which is what an A/B needs anyway.
//
@@ -51,15 +51,24 @@
// ------------------------------------------------------------------------------------------------
/** What one scenario line asks for. */
// ------------------------------------------------------------------------------------------------
+//
+// A <position> is two numbers, x and y, or one token naming a start position: start<N> is where
+// seat N began (-scenario pins seat i to start i), and start<N>:<dx>:<dy> stands that far off it.
+// The token form is what lets one file play on a generated map, whose starts move with the seed.
+//
enum ScenarioActionType
{
- SCENARIO_ACTION_SPAWN = 0, ///< spawn <slot> <template> <count> <x> <y> [spacing]
- SCENARIO_ACTION_MOVE, ///< move <slot> <selector> <x> <y>
- SCENARIO_ACTION_ATTACKMOVE, ///< attackmove <slot> <selector> <x> <y>
+ SCENARIO_ACTION_SPAWN = 0, ///< spawn <slot> <template> <count> <position> [spacing]
+ SCENARIO_ACTION_MOVE, ///< move <slot> <selector> <position>
+ SCENARIO_ACTION_ATTACKMOVE, ///< attackmove <slot> <selector> <position>
SCENARIO_ACTION_ATTACK, ///< attack <slot> <selector> <targetSlot> <targetSelector>
- SCENARIO_ACTION_STOP ///< stop <slot> <selector>
+ SCENARIO_ACTION_STOP, ///< stop <slot> <selector>
+ SCENARIO_ACTION_ARRIVE ///< arrive <slot> <selector> <position> [radius]
};
+/// ScenarioAction::atStart when the position is plain numbers
+enum { SCENARIO_NO_START = -1 };
+
// ------------------------------------------------------------------------------------------------
/** Why a line was not turned into an action. A scenario that silently drops half its orders is
worse than one that refuses to load, because the run still produces numbers. */
@@ -72,7 +81,8 @@ enum ScenarioParseResult
SCENARIO_PARSE_BAD_ACTION,
SCENARIO_PARSE_BAD_SLOT,
SCENARIO_PARSE_BAD_COUNT,
- SCENARIO_PARSE_MISSING_ARGS
+ SCENARIO_PARSE_MISSING_ARGS,
+ SCENARIO_PARSE_BAD_POSITION
};
// ------------------------------------------------------------------------------------------------
@@ -84,9 +94,11 @@ struct ScenarioAction
ScenarioActionType action;
Int slot; ///< the seat, the same number -side takes; not an index into ThePlayerList
AsciiString selector; ///< a template name, or "*" for everything that seat owns
- Coord2D at; ///< spawn, move and attackmove target
+ Coord2D at; ///< spawn, move, attackmove and arrive target, or the offset from atStart
+ Int atStart; ///< the start position at is measured from, SCENARIO_NO_START for none
Int count; ///< how many to spawn
Real spacing; ///< how far apart to spawn them, in world units
+ Real radius; ///< how close to the target counts as arrived
Int targetSlot; ///< whose units to attack
AsciiString targetSelector; ///< which of them
};
@@ -109,4 +121,9 @@ extern Bool ScenarioDrill_execute( const ScenarioAction &action );
/** One line for the end-of-run summary: how much of the file actually happened. */
extern const char *ScenarioDrill_report( void );
+/** One HEADLESS ARRIVE line per arrive action: how many of the units it watched got within its
+ radius, and how many frames after the line fired the first and the last of them did. The last
+ one's time is the choke probe's number (ROADMAP M0.3). */
+extern void ScenarioDrill_logArrivals( void );
+
#endif // __SCENARIODRILL_H_
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
index 06b8ae6d6..838c5e5ba 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
@@ -249,6 +249,12 @@ Int parseNoMilCap(char *args[], int)
return 1;
}
+#endif // _DEBUG || _INTERNAL
+
+/* The CRC switches are out of the debug block on purpose (ROADMAP M1.2). A Release build with the
+ startup log has DEBUG_CRC compiled in already, so every one of these works there; they were only
+ unreachable from the command line, which left a desync report from a tester's Release exe with
+ nothing in it to act on. */
//=============================================================================
//=============================================================================
Int parseDebugCRCFromFrame(char *args[], int argc)
@@ -361,6 +367,7 @@ Int parseReplayCRCInterval(char *args[], int argc)
return 2;
}
+#if defined(_DEBUG) || defined(_INTERNAL)
//=============================================================================
//=============================================================================
Int parseNoDraw(char *args[], int argc)
@@ -1581,72 +1588,6 @@ Int parseTraceMove(char *args[], int num)
return 1;
}
-/* -aislice <n> lets a unit's AI decide once every n logic frames instead of every one.
-
- This is the only lever left that reduces what the AI does rather than how fast it does it, and
- it is off by default because what it spends is reaction time, not milliseconds: a unit acquires
- a target and obeys an order up to n-1 frames late. Movement is not sliced - the locomotor still
- runs every frame, so units keep driving smoothly along the route they already have; it is the
- deciding that waits. The offset is the object id, so the units do not all think on the same
- frame, and an id is assigned in creation order and identical on every machine, which keeps this
- inside the CRC. */
-Int parseAISlice(char *args[], int num)
-{
- if (TheWritableGlobalData && num > 1 && args[1])
- {
- Int slice = atoi(args[1]);
- if (slice < 1)
- slice = 1;
- if (slice > 8)
- slice = 8; // past this a unit is visibly asleep, and it is a measuring tool anyway
- TheWritableGlobalData->m_aiSliceFrames = slice;
- return 2;
- }
- return 1;
-}
-
-/* -noflowpath takes the flow model back out and prices terrain only, the way retail does.
-
- It exists to be measured against. A change to how a route is costed is argued with a batch of
- matches, and a batch is only an argument if both halves of it are the same binary: two builds
- differ in the compiler's mood as well as in the change. So the clearance charge, the traffic
- charge and the crossing charge all hang off this one switch, and ai-batch.ps1 runs the same
- exe twice. The maps are still built and still maintained under it - they cost almost nothing
- to keep and turning them off as well would measure two changes at once. */
-Int parseNoFlowPath(char *args[], int num)
-{
- if (TheWritableGlobalData)
- TheWritableGlobalData->m_noFlowPath = TRUE;
- return 1;
-}
-
-/* -nolanes puts every unit back on the centre line of its route.
-
- The flow model decides where a route goes; lanes decide where across it a unit drives, which
- is a separate question and needs its own baseline. With this on, computePointOnPath steers at
- the centre the way retail always did, nothing measures the width of the ground beside the
- route, and a unit stuck behind a slower one waits instead of sliding past. Same reasoning as
- -noflowpath: one binary, run twice. */
-Int parseNoLanePath(char *args[], int num)
-{
- if (TheWritableGlobalData)
- TheWritableGlobalData->m_noLanePath = TRUE;
- return 1;
-}
-
-/* -nomomentum prices a turn the way retail does: 4, 8 or 16 whatever is turning.
-
- The search charges what the swing actually costs this hull instead - its own speed over its own
- turn rate - and charges the first step against the direction the unit is already pointing, which
- retail charged not at all. That is the difference between a route and a route a tank can drive.
- Same reasoning as the two switches above: the baseline has to be the same binary. */
-Int parseNoMomentumPath(char *args[], int num)
-{
- if (TheWritableGlobalData)
- TheWritableGlobalData->m_noMomentumPath = TRUE;
- return 1;
-}
-
/* -showlanes draws the band model on top of the world.
A movement change that measures well in a batch and cannot be seen in a game is a change nobody
@@ -1661,50 +1602,6 @@ Int parseShowLanes(char *args[], int num)
return 1;
}
-/* -crowd turns on the crowd model, in one switch, so that it can be argued with.
-
- It is not one rule but a stack of them - the corridor with its measured width, the lane handed
- out as a distance rather than a share, right of way by body size, giving way to something bigger
- closing on you, passing a unit that is actually slower rather than one whose engine is, fanning
- out only while held up, and easing off through a bend. Every one of those changes what a group
- looks like crossing a map, and shipping them one at a time means eight batches and eight
- opinions about which of them did the damage. So they land together behind one flag, off by
- default: the same exe run twice is the before and the after, and the argument is about the whole
- model rather than about any single constant inside it. */
-Int parseCrowdModel(char *args[], int num)
-{
- if (TheWritableGlobalData)
- TheWritableGlobalData->m_crowdModel = TRUE;
- return 1;
-}
-
-/* -groupdrill <n> gives every player's army a group order every n frames.
-
- A skirmish AI moves its teams one unit at a time, so a self-play batch contains no group orders
- at all and measures nothing the crowd model does. This puts them in: the same call a right-click
- makes, over the whole army, corner to corner. The match becomes meaningless - the win rate under
- this switch says nothing about anything - and the blocked unit-frames become the first honest
- measurement of group movement this fork has. 600 frames, twenty seconds, is long enough for an
- army to cross a generated map. */
-Int parseGroupDrill(char *args[], int num)
-{
- if (TheWritableGlobalData)
- {
- Int frames = 600;
- Int eaten = 1;
- if (num > 1 && args[1] && args[1][0] != '-')
- {
- frames = atoi(args[1]);
- eaten = 2;
- }
- if (frames < LOGICFRAMES_PER_SECOND)
- frames = LOGICFRAMES_PER_SECOND; // an order a frame is not a drill, it is a stutter
- TheWritableGlobalData->m_groupDrill = frames;
- return eaten;
- }
- return 1;
-}
-
/* -uidrill <n> works the command bar the way a player does, from a script.
The bar is laid out again every time its scheme is set, and a panel that was minimised at that
@@ -1836,7 +1733,7 @@ Int parseNoDevice(char *args[], int num)
something it asks for - and two runs that drew different factions were never comparable. The
file names the unit, the place, the count and the frame, so two builds play the same match.
- Like -groupdrill, the orders it gives exist nowhere in the command stream, so a run driven this
+ The orders it gives exist nowhere in the command stream, so a run driven this
way cannot be replayed. Repeatability comes from the file plus -seed instead, which is what an
A/B wanted anyway. */
Int parseScenario(char *args[], int num)
@@ -2216,6 +2113,16 @@ static CommandLineParam params[] =
{ "-latAmp", parseLatencyAmplitude },
{ "-latPeriod", parseLatencyPeriod },
{ "-latNoise", parseLatencyNoise },
+ { "-DebugCRCFromFrame", parseDebugCRCFromFrame },
+ { "-DebugCRCUntilFrame", parseDebugCRCUntilFrame },
+ { "-KeepCRCSaves", parseKeepCRCSave },
+ { "-CRCLogicModuleData", parseCRCLogicModuleData },
+ { "-CRCClientModuleData", parseCRCClientModuleData },
+ { "-ClientDeepCRC", parseClientDeepCRC },
+ { "-VerifyClientCRC", parseVerifyClientCRC },
+ { "-LogObjectCRCs", parseLogObjectCRCs },
+ { "-NetCRCInterval", parseNetCRCInterval },
+ { "-ReplayCRCInterval", parseReplayCRCInterval },
#if (defined(_DEBUG) || defined(_INTERNAL))
{ "-noaudio", parseNoAudio },
@@ -2231,17 +2138,7 @@ static CommandLineParam params[] =
{ "-localMOTD", parseLocalMOTD },
{ "-UseCSF", parseUseCSF },
{ "-NoInputDisable", parseNoInputDisable },
- { "-DebugCRCFromFrame", parseDebugCRCFromFrame },
- { "-DebugCRCUntilFrame", parseDebugCRCUntilFrame },
- { "-KeepCRCSaves", parseKeepCRCSave },
- { "-CRCLogicModuleData", parseCRCLogicModuleData },
- { "-CRCClientModuleData", parseCRCClientModuleData },
- { "-ClientDeepCRC", parseClientDeepCRC },
- { "-VerifyClientCRC", parseVerifyClientCRC },
- { "-LogObjectCRCs", parseLogObjectCRCs },
{ "-saveAllStats", parseSaveAllStats },
- { "-NetCRCInterval", parseNetCRCInterval },
- { "-ReplayCRCInterval", parseReplayCRCInterval },
{ "-noDraw", parseNoDraw },
{ "-nomilcap", parseNoMilCap },
{ "-nofade", parseNoFade },
@@ -2322,13 +2219,7 @@ static CommandLineParam params[] =
{ "-teams", parseTeams },
{ "-peacetime", parsePeaceTime },
{ "-unitlimit", parseUnitLimit },
- { "-aislice", parseAISlice },
- { "-noflowpath", parseNoFlowPath },
- { "-nolanes", parseNoLanePath },
- { "-nomomentum", parseNoMomentumPath },
{ "-showlanes", parseShowLanes },
- { "-crowd", parseCrowdModel },
- { "-groupdrill", parseGroupDrill },
{ "-uidrill", parseUIDrill },
{ "-resdrill", parseResDrill },
{ "-resdrillkeep", parseResDrillKeep },
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
index c59a8df5d..4796bf816 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
@@ -1520,7 +1520,7 @@ static void updateFixedCamera( void )
*
* The bar drifted up the screen a few pixels at a time and only under a sequence no unattended run
* performs: a panel that is away when its layout is rebuilt. Nothing the AI does touches the bar,
- * -groupdrill gives orders and never opens a menu, and the drift is small enough per rebuild that
+ * -scenario gives orders and never opens a menu, and the drift is small enough per rebuild that
* one cycle by hand looks like nothing. So the drill does the two halves on alternate ticks - a
* toggle, then a rebuild once the slide has arrived - and writes where the bar landed each time.
* A run that holds one pair of numbers for its whole life is a bar that stays put; a run whose
@@ -1855,8 +1855,6 @@ static void updateHeadlessRun( void )
Pathfinder::resetMatchProfile();
// and -tracemove with no id picks its unit out of the match, not out of the shell map
AIUpdate_resetMoveTrace();
- extern void GroupDrill_reset( void );
- GroupDrill_reset();
if (TheGlobalData->m_headless && TheGlobalData->m_videoEndFrame > 0)
DEBUG_LOG(("-video: -headless draws nothing, so there is no video to record\n"));
}
@@ -1957,22 +1955,13 @@ static void updateHeadlessRun( void )
// reduced the traffic jams it was supposed to reduce.
DEBUG_LOG(("HEADLESS PATHFIND: %s\n", Pathfinder::getMatchProfileReport()));
- /* And under -groupdrill, the question the blocked counters cannot answer: of the units that were
- marched across the map, how many were still going when the next order came, and how many had
- stopped and stayed stopped. Time spent in traffic is one thing; never getting there at all
- is the thing anybody actually complains about. */
- if (TheGlobalData->m_groupDrill > 0)
- {
- extern const char *GroupDrill_report( void );
- DEBUG_LOG(("HEADLESS DRILL: %s\n", GroupDrill_report()));
- }
-
/* And under -scenario, how much of the file actually happened. A scenario whose spawns all
failed still plays a match and still writes every number below it, so the run has to say out
loud how many orders it managed rather than leaving that to be inferred from the frame time. */
if (!TheGlobalData->m_scenarioFile.isEmpty())
{
DEBUG_LOG(("HEADLESS SCENARIO: %s\n", ScenarioDrill_report()));
+ ScenarioDrill_logArrivals();
}
/* Stability, which is a different question from speed and is answered by the tail rather than
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
index becff6378..0faf5f103 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
@@ -704,13 +704,7 @@ GlobalData::GlobalData()
m_cameraLook.x = m_cameraLook.y = 0.0f;
m_traceMoveID = 0; // no movement trace
m_slowFrameMS = 20.0f; // a frame worth a line in the log; -slowframe lowers it for a hunt
- m_aiSliceFrames = 1; // every unit thinks every frame, which is what the game has always done
- m_noFlowPath = FALSE; // the flow model is on; -noflowpath is the retail baseline to measure against
- m_noLanePath = FALSE; // lanes are on; -nolanes is the retail baseline to measure against
- m_noMomentumPath = FALSE; // a turn costs what the hull's own turn rate says; -nomomentum is retail's flat price
m_showLanes = FALSE; // the lane overlay is a diagnostic, off unless -showlanes asks for it
- m_crowdModel = FALSE; // the crowd model is the change under test; without -crowd this is the old build
- m_groupDrill = 0; // no group orders are faked; -groupdrill is a measuring tool and ruins the match it runs in
m_uiDrill = 0; // nobody presses the minimise button; -uidrill is how a script presses it
m_resDrillFrame = 0; // the resolution stays where it started unless -resdrill changes it mid-match
m_resDrillX = 0;
@@ -718,7 +712,7 @@ GlobalData::GlobalData()
m_resDrillKeep = FALSE;
m_noRenderDevice = FALSE; // -headless still takes a 100x100 device unless -nodevice says not to
m_controlPort = 0; // nothing listens; -control opens the socket
- m_scenarioFile.clear(); // nothing is scripted; -scenario is a measuring tool and, like -groupdrill, ruins the match it runs in
+ m_scenarioFile.clear(); // nothing is scripted; -scenario is a measuring tool and ruins the match it runs in
m_autoSkirmishTakeover = FALSE; // the AI plays the opponents unless -takeover empties their seats
for( Int slot = 0; slot < MAX_PLAYER_COUNT; slot++ )
m_autoSkirmishSide[ slot ].clear(); // every faction still comes out of the seed unless -side names one
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp
index b816989dc..df8da5813 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp
@@ -3006,6 +3006,17 @@ static const char theProRulesAuroraSuffix[] = "JetAurora";
static const char theProRulesNukeSiloSuffix[] = "NuclearMissileLauncher";
static const char theProRulesTacticalNukeMigUpgrade[] = "Upgrade_ChinaTacticalNukeMig";
static const char theProRulesTerroristSuffix[] = "InfantryTerrorist";
+static const char theProRulesDemoSuicideUpgrade[] = "Demo_Upgrade_SuicideBomb";
+static const char theProRulesNeutronShellsUpgrade[] = "Upgrade_ChinaNeutronShells";
+static const char theProRulesStealthComancheUpgrade[] = "AirF_Upgrade_StealthComanche";
+static const char theProRulesOilDerrick[] = "TechOilDerrick";
+// the three defences rule 16 counts, by the ending every general's copy shares
+static const char *const theProRulesDerrickDefenseSuffixes[] =
+{
+ "AmericaPatriotBattery",
+ "ChinaGattlingCannon",
+ "GLAStingerSite"
+};
// rules 4 and 5
Bool ProRulesBanThing( const AsciiString &templateName )
@@ -3020,18 +3031,103 @@ Bool ProRulesExemptSuperweapon( const AsciiString &templateName )
return templateName.endsWithNoCase( theProRulesNukeSiloSuffix );
}
-// rule 6
+// rules 6 and 12 to 14
Bool ProRulesBanUpgrade( const AsciiString &upgradeName )
{
- return upgradeName.compareNoCase( theProRulesTacticalNukeMigUpgrade ) == 0;
+ return upgradeName.compareNoCase( theProRulesTacticalNukeMigUpgrade ) == 0
+ || upgradeName.compareNoCase( theProRulesDemoSuicideUpgrade ) == 0
+ || upgradeName.compareNoCase( theProRulesNeutronShellsUpgrade ) == 0
+ || upgradeName.compareNoCase( theProRulesStealthComancheUpgrade ) == 0;
+}
+
+// Rule 2, the silo's missile, which each China general and the Superweapon General fire as a type of
+// their own, and rule 15, the Carpet Bomb below rank 3. The Air Force General buys his at rank 1 and
+// the early China copies come at rank 3, so in practice rule 15 is his.
+Bool ProRulesBanSpecialPower( SpecialPowerType specialPowerType, Int rankLevel )
+{
+ if ( specialPowerType == SPECIAL_NEUTRON_MISSILE
+ || specialPowerType == NUKE_SPECIAL_NEUTRON_MISSILE
+ || specialPowerType == SUPW_SPECIAL_NEUTRON_MISSILE )
+ return TRUE;
+
+ const Bool carpetBomb = specialPowerType == SPECIAL_CARPET_BOMB
+ || specialPowerType == SPECIAL_CHINA_CARPET_BOMB
+ || specialPowerType == EARLY_SPECIAL_CHINA_CARPET_BOMB
+ || specialPowerType == AIRF_SPECIAL_CARPET_BOMB;
+ return carpetBomb && rankLevel < PRO_RULES_CARPET_BOMB_RANK;
+}
+
+Bool ProRulesRefuseSpecialPower( const Player *player, SpecialPowerType specialPowerType )
+{
+ return TheGameLogic->isProRules() && ProRulesBanSpecialPower( specialPowerType, player->getRankLevel() );
+}
+
+// rule 16
+Bool ProRulesIsOilDerrick( const AsciiString &templateName )
+{
+ return templateName.compareNoCase( theProRulesOilDerrick ) == 0;
+}
+
+Bool ProRulesIsDerrickDefense( const AsciiString &templateName )
+{
+ for ( Int i = 0; i < ARRAY_SIZE( theProRulesDerrickDefenseSuffixes ); ++i )
+ {
+ if ( templateName.endsWithNoCase( theProRulesDerrickDefenseSuffixes[ i ] ) )
+ return TRUE;
+ }
+ return FALSE;
+}
+
+static Bool isWithinDerrickClusterRadius( const Coord2D &a, const Coord2D &b )
+{
+ const Real dx = a.x - b.x;
+ const Real dy = a.y - b.y;
+ const Real radius = (Real)PRO_RULES_DERRICK_CLUSTER_RADIUS;
+ return dx * dx + dy * dy <= radius * radius;
}
-// rule 2, the silo's missile, which each China general and the Superweapon General fire as a type of their own
-Bool ProRulesBanSpecialPower( SpecialPowerType specialPowerType )
+Int ProRulesCountDerrickClusterDefenses( const Coord2D &spot, const Coord2D *derricks, Int derrickCount,
+ const Coord2D *defenses, Int defenseCount )
{
- return specialPowerType == SPECIAL_NEUTRON_MISSILE
- || specialPowerType == NUKE_SPECIAL_NEUTRON_MISSILE
- || specialPowerType == SUPW_SPECIAL_NEUTRON_MISSILE;
+ // the derricks the spot stands beside, then every derrick one step from one already found
+ std::vector<Bool> inCluster( derrickCount, FALSE );
+ std::vector<Int> frontier;
+ for ( Int i = 0; i < derrickCount; ++i )
+ {
+ if ( isWithinDerrickClusterRadius( spot, derricks[ i ] ) )
+ {
+ inCluster[ i ] = TRUE;
+ frontier.push_back( i );
+ }
+ }
+
+ while ( !frontier.empty() )
+ {
+ const Int from = frontier.back();
+ frontier.pop_back();
+ for ( Int i = 0; i < derrickCount; ++i )
+ {
+ if ( !inCluster[ i ] && isWithinDerrickClusterRadius( derricks[ from ], derricks[ i ] ) )
+ {
+ inCluster[ i ] = TRUE;
+ frontier.push_back( i );
+ }
+ }
+ }
+
+ Int count = 0;
+ for ( Int defense = 0; defense < defenseCount; ++defense )
+ {
+ for ( Int i = 0; i < derrickCount; ++i )
+ {
+ if ( inCluster[ i ] && isWithinDerrickClusterRadius( defenses[ defense ], derricks[ i ] ) )
+ {
+ ++count;
+ break;
+ }
+ }
+ }
+ return count;
}
// rule 7, the demo bike: a combat cycle with a terrorist in the saddle
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/BuildAssistant.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/BuildAssistant.cpp
index f223773b8..35b0311b4 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/System/BuildAssistant.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/BuildAssistant.cpp
@@ -922,9 +922,54 @@ Bool BuildAssistant_shroudBlocksBuilding( CellShroudStatus status )
return status == CELLSHROUD_SHROUDED;
}
+//-------------------------------------------------------------------------------------------------
+/** Rule 16 of Pro Rules for one spot: are the owner's defences round the derrick cluster this spot
+ * belongs to already at the cap? The largest cluster measured on the game's maps is four derricks,
+ * three steps of the radius from end to end, so everything within four steps of the spot is enough
+ * to flood it, and one step more catches every defence standing round it. */
+//-------------------------------------------------------------------------------------------------
+static const Int PRO_RULES_DERRICK_SEARCH_STEPS = 5;
+
+static Bool isDerrickClusterDefenseFull( const Coord3D *worldPos, const Player *owner )
+{
+ PartitionFilterAcceptByKindOf structures( MAKE_KINDOF_MASK( KINDOF_STRUCTURE ), KINDOFMASK_NONE );
+ PartitionFilter *filters[] = { &structures, NULL };
+
+ std::vector<Coord2D> derricks;
+ std::vector<Coord2D> defenses;
+ const Real range = (Real)( PRO_RULES_DERRICK_CLUSTER_RADIUS * PRO_RULES_DERRICK_SEARCH_STEPS );
+ ObjectIterator *iter = ThePartitionManager->iterateObjectsInRange( worldPos, range, FROM_CENTER_2D, filters );
+ MemoryPoolObjectHolder hold( iter );
+ for( Object *them = iter->first(); them; them = iter->next() )
+ {
+ if( them->isEffectivelyDead() )
+ continue;
+
+ Coord2D at;
+ at.x = them->getPosition()->x;
+ at.y = them->getPosition()->y;
+
+ const AsciiString &name = them->getTemplate()->getName();
+ if( ProRulesIsOilDerrick( name ) )
+ derricks.push_back( at );
+ else if( them->getControllingPlayer() == owner && ProRulesIsDerrickDefense( name ) )
+ defenses.push_back( at );
+ }
+
+ if( derricks.empty() || defenses.empty() )
+ return FALSE;
+
+ Coord2D spot;
+ spot.x = worldPos->x;
+ spot.y = worldPos->y;
+ const Int standing = ProRulesCountDerrickClusterDefenses( spot, &derricks[ 0 ], (Int)derricks.size(),
+ &defenses[ 0 ], (Int)defenses.size() );
+ return standing >= PRO_RULES_DEFENSES_PER_DERRICK_CLUSTER;
+}
+
//-------------------------------------------------------------------------------------------------
/** Query if we can build at this location. Note that 'build' may be null and is NOT required
- * to be valid to know if a location is legal to build at. 'builderObject' is used
+ * to be valid to know if a location is legal to build at. 'builderObject' is used
* for queries that require a pathfind check and should be NULL if not required */
//-------------------------------------------------------------------------------------------------
LegalBuildCode BuildAssistant::isLocationLegalToBuild( const Coord3D *worldPos,
@@ -1108,6 +1153,14 @@ LegalBuildCode BuildAssistant::isLocationLegalToBuild( const Coord3D *worldPos,
}
}
+ //
+ // Rule 16: no more than two of the player's own Patriots, Gatling Cannons and Stinger Sites round
+ // one cluster of oil derricks. Only those three templates pay for the range query.
+ //
+ if( TheGameLogic->isProRules() && owner && ProRulesIsDerrickDefense( build->getName() )
+ && isDerrickClusterDefenseFull( worldPos, owner ) )
+ return LBC_TOO_MANY_DERRICK_DEFENSES;
+
// we passed all the checks
return LBC_OK;
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp
index 3747c71a1..90da9bb37 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp
@@ -1634,7 +1634,7 @@ CommandAvailability ControlBar::getCommandAvailability( const CommandButton *com
}
// Pro Rules: the power is there and the button stays dead
- if( TheGameLogic->isProRules() && ProRulesBanSpecialPower( command->getSpecialPowerTemplate()->getSpecialPowerType() ) )
+ if( ProRulesRefuseSpecialPower( obj->getControllingPlayer(), command->getSpecialPowerTemplate()->getSpecialPowerType() ) )
return COMMAND_RESTRICTED;
if( mod->isReady() == FALSE )
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
index 5ee56215b..3849ebf07 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
@@ -701,7 +701,7 @@ void InGameUI::addSuperweapon(Int playerIndex, const AsciiString& powerName, Obj
return;
// Pro Rules: a silo nobody may fire gets no countdown on everybody's screen and no "missile ready"
- if (TheGameLogic->isProRules() && ProRulesBanSpecialPower(powerTemplate->getSpecialPowerType()))
+ if (ProRulesRefuseSpecialPower(ThePlayerList->getNthPlayer(playerIndex), powerTemplate->getSpecialPowerType()))
return;
// srj sez: don't allow adding the same superweapon more than once. it can happen. not sure how. (srj)
@@ -5974,6 +5974,11 @@ void InGameUI::displayCantBuildMessage( LegalBuildCode lbc )
TheInGameUI->message( "GUI:CantBuildTooCloseToSupplies" );
break;
+ //---------------------------------------------------------------------------------------------
+ case LBC_TOO_MANY_DERRICK_DEFENSES:
+ TheInGameUI->message( "GUI:CantBuildTooManyDerrickDefenses" );
+ break;
+
//---------------------------------------------------------------------------------------------
case LBC_TOO_CLOSE_TO_ENEMY:
TheInGameUI->message( "GUI:CantBuildTooCloseToEnemy" );
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
index eb74d2c3c..6ae757408 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp
@@ -1644,9 +1644,9 @@ static void crowdClearLanes( std::list<Object *>& members )
The same arithmetic groupMoveToPosition does inline, extracted because the computer's armies
never go through that function: an AI team moves with groupTightenToPosition
(AIPlayer.cpp:3505), which handed nobody a lane, and a unit with no lane is a unit crowdSteer
- returns out of on its first line. So every steering rule under -crowd was reachable by the
- player and by nothing else, and the self-play harness was measuring the flag's other half - the
- collision rules in AIUpdate::blockedBy - while reporting on the crowd model. */
+ returns out of on its first line. So every steering rule in the crowd model was reachable by
+ the player and by nothing else, and the self-play harness was measuring the collision rules in
+ AIUpdate::blockedBy while reporting on the crowd model. */
static void crowdSeedLanes( std::list<Object *>& members, const Coord3D& center, const Coord3D *pos )
{
crowdClearLanes( members ); // whatever this order hands out replaces the last one entirely
@@ -1913,9 +1913,8 @@ void AIGroup::groupMoveToPosition( const Coord3D *p_posIn, Bool addWaypoint, Com
groupDir.x = pos->x - center.x;
groupDir.y = pos->y - center.y;
const Coord3D groupCenter = center;
- Bool spreadLanes = !TheGlobalData->m_noLanePath && groupDir.length() > 1.0f;
- if (TheGlobalData->m_crowdModel)
- crowdClearLanes( m_memberList ); // this order replaces the last one, spread or no spread
+ Bool spreadLanes = groupDir.length() > 1.0f;
+ crowdClearLanes( m_memberList ); // this order replaces the last one, spread or no spread
if (spreadLanes)
{
groupDir.normalize();
@@ -1951,20 +1950,9 @@ void AIGroup::groupMoveToPosition( const Coord3D *p_posIn, Bool addWaypoint, Com
{
std::sort( across.begin(), across.end(), laneSeedIsLeftOf );
- /* Under -crowd the lane count is the road's, measured here; the old model keeps the fixed
- reference it was written against, because its own offsets are scaled again downstream by
- the room found at the unit's feet and measuring the same width twice would square it. */
+ // the lane count is the road's, measured here
Real bias = 0.0f;
- Int lanes;
- if (TheGlobalData->m_crowdModel)
- {
- lanes = crowdRoadLanes( widest, groupCenter, groupDir, spacing, &bias );
- }
- else
- {
- lanes = (Int)(2.0f * Pathfinder_laneReference() / spacing);
- if (lanes < 1) lanes = 1;
- }
+ Int lanes = crowdRoadLanes( widest, groupCenter, groupDir, spacing, &bias );
if (lanes > count) lanes = count;
for (Int i = 0; i < count; i++)
@@ -1976,18 +1964,15 @@ void AIGroup::groupMoveToPosition( const Coord3D *p_posIn, Bool addWaypoint, Com
Real u = Pathfinder_groupLane( offset );
across[i].obj->getAIUpdateInterface()->setPendingLane( u );
- /* -crowd takes the offset as it stands. The old model had to turn it into a share of
- a width guessed here and re-measured somewhere else, and the two never agreed: the
- conversion is where the spacing this loop just worked out was thrown away. */
- if (TheGlobalData->m_crowdModel)
- {
- across[i].obj->getAIUpdateInterface()->setPendingCrowdLat( offset );
- /* And the slot the offset came from, which is the part that survives. The offset is
- measured here, once, on the ground the group happens to be standing on; the slot is
- re-fitted to the band every frame, so the group is as many abreast as the road under
- it carries rather than as many as its car park did. */
- across[i].obj->getAIUpdateInterface()->setPendingCrowdLane( i, count, spacing );
- }
+ /* The crowd model takes the offset as it stands. The old model had to turn it into a
+ share of a width guessed here and re-measured somewhere else, and the two never agreed:
+ the conversion is where the spacing this loop just worked out was thrown away. */
+ across[i].obj->getAIUpdateInterface()->setPendingCrowdLat( offset );
+ /* And the slot the offset came from, which is the part that survives. The offset is
+ measured here, once, on the ground the group happens to be standing on; the slot is
+ re-fitted to the band every frame, so the group is as many abreast as the road under
+ it carries rather than as many as its car park did. */
+ across[i].obj->getAIUpdateInterface()->setPendingCrowdLane( i, count, spacing );
if (TheGlobalData->m_showLanes)
{
@@ -2226,9 +2211,8 @@ void AIGroup::groupTightenToPosition( const Coord3D *pos, Bool addWaypoint, Comm
//}
}
/* The computer's armies come through here rather than groupMoveToPosition, so this is where they
- are handed their lanes. Under -crowd only: without the flag a tighten is retail's, and the
- lane is read by nothing. */
- if (TheGlobalData->m_crowdModel && !addWaypoint)
+ are handed their lanes. */
+ if (!addWaypoint)
{
Coord2D tMin, tMax;
Coord3D tCenter;
@@ -2675,8 +2659,7 @@ void AIGroup::groupAttackMoveToPosition( const Coord3D *pos, Int maxShotsToFire,
wants the crowd model and was not getting it: nothing here handed out a lane, and a unit with
no lane is one crowdSteer returns out of on its first line. So a group told to fight its way
across a map drove there in single file while the same group told to walk there spread out. */
- if (TheGlobalData->m_crowdModel)
- crowdSeedLanes( m_memberList, center, pos );
+ crowdSeedLanes( m_memberList, center, pos );
// path the members closest to the goal first; it leaves fewer of them to collide on arrival.
MemoryPoolObjectHolder iterHolder;
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
index f6eda8e78..19a6431f8 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp
@@ -1254,7 +1254,7 @@ void Path::computePointOnPath(
at the end, so the band closes onto the centre over the last few cells, and it still has
to be able to drive at whatever it is aimed at, so a lane point with something in the way
is dropped and the centre kept. */
- if (!TheGlobalData->m_noLanePath && closeNode != NULL && closeNode->getNextOptimized() != NULL)
+ if (closeNode != NULL && closeNode->getNextOptimized() != NULL)
{
const AIUpdateInterface *ai = obj ? obj->getAIUpdateInterface() : NULL;
if (ai && ai->hasLaneFraction())
@@ -4840,7 +4840,6 @@ void Pathfinder::stampClaimAt( const Coord3D *pos, UnsignedInt frame, Int dilati
void Pathfinder::claimPathTiming( const Object *obj, Path *path )
{
if (m_claims == NULL || obj == NULL || path == NULL) return;
- if (TheGlobalData->m_noFlowPath) return;
const AIUpdateInterface *ai = obj->getAIUpdateInterface();
if (ai == NULL) return;
@@ -4973,7 +4972,7 @@ void Pathfinder::beginFlowSearch( const Object *obj )
{
m_flowNow = TheGameLogic ? TheGameLogic->getFrame() : 0;
m_flowNowBucket = m_flowNow / PF_CLAIM_BUCKET_FRAMES;
- m_flowCosts = !TheGlobalData->m_noFlowPath && obj != NULL &&
+ m_flowCosts = obj != NULL &&
m_clearance != NULL && m_traffic != NULL && m_claims != NULL && m_claimTouch != NULL;
m_flowSpeed = m_flowCosts ? flowSpeedOf(obj) : 0;
// and the estimate is raised to match what the charge adds, or the search stops steering
@@ -4986,7 +4985,7 @@ void Pathfinder::beginFlowSearch( const Object *obj )
and charges nothing. */
thePathTurnChassis = 0;
thePathStartDirValid = FALSE;
- if (obj != NULL && !TheGlobalData->m_noMomentumPath)
+ if (obj != NULL)
{
const AIUpdateInterface *ai = obj->getAIUpdateInterface();
const Locomotor *loco = ai ? ai->getCurLocomotor() : NULL;
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SpecialPower/SpecialPowerModule.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SpecialPower/SpecialPowerModule.cpp
index 63717fdf1..6edd41fcb 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SpecialPower/SpecialPowerModule.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SpecialPower/SpecialPowerModule.cpp
@@ -62,11 +62,12 @@
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
-/** Rule 2 of Pro Rules: the silo stands and charges, and firing it is refused. Every route to
- * firing - the button, a hotkey, a script, a computer player - ends in one of the four do calls. */
-static Bool proRulesRefuse( const SpecialPowerTemplate *specialPowerTemplate )
+/** Rules 2 and 15 of Pro Rules: the silo stands and charges and firing it is refused, and so is a
+ * Carpet Bomb below rank 3. Every route to firing - the button, a hotkey, a script, a computer
+ * player - ends in one of the four do calls. */
+static Bool proRulesRefuse( const Object *object, const SpecialPowerTemplate *specialPowerTemplate )
{
- return TheGameLogic->isProRules() && ProRulesBanSpecialPower( specialPowerTemplate->getSpecialPowerType() );
+ return ProRulesRefuseSpecialPower( object->getControllingPlayer(), specialPowerTemplate->getSpecialPowerType() );
}
//-------------------------------------------------------------------------------------------------
@@ -699,7 +700,7 @@ void SpecialPowerModule::aboutToDoSpecialPower( const Coord3D *location )
//-------------------------------------------------------------------------------------------------
void SpecialPowerModule::doSpecialPower( UnsignedInt commandOptions )
{
- if (m_pausedCount > 0 || getObject()->isDisabled() || proRulesRefuse( getSpecialPowerTemplate() )) {
+ if (m_pausedCount > 0 || getObject()->isDisabled() || proRulesRefuse( getObject(), getSpecialPowerTemplate() )) {
return;
}
@@ -721,7 +722,7 @@ void SpecialPowerModule::doSpecialPower( UnsignedInt commandOptions )
//-------------------------------------------------------------------------------------------------
void SpecialPowerModule::doSpecialPowerAtObject( Object *obj, UnsignedInt commandOptions )
{
- if (m_pausedCount > 0 || getObject()->isDisabled() || proRulesRefuse( getSpecialPowerTemplate() )) {
+ if (m_pausedCount > 0 || getObject()->isDisabled() || proRulesRefuse( getObject(), getSpecialPowerTemplate() )) {
return;
}
@@ -743,7 +744,7 @@ void SpecialPowerModule::doSpecialPowerAtObject( Object *obj, UnsignedInt comman
//-------------------------------------------------------------------------------------------------
void SpecialPowerModule::doSpecialPowerAtLocation( const Coord3D *loc, Real angle, UnsignedInt commandOptions )
{
- if (m_pausedCount > 0 || getObject()->isDisabled() || proRulesRefuse( getSpecialPowerTemplate() )) {
+ if (m_pausedCount > 0 || getObject()->isDisabled() || proRulesRefuse( getObject(), getSpecialPowerTemplate() )) {
return;
}
@@ -765,7 +766,7 @@ void SpecialPowerModule::doSpecialPowerAtLocation( const Coord3D *loc, Real angl
//-------------------------------------------------------------------------------------------------
void SpecialPowerModule::doSpecialPowerUsingWaypoints( const Waypoint *way, UnsignedInt commandOptions )
{
- if (m_pausedCount > 0 || getObject()->isDisabled() || proRulesRefuse( getSpecialPowerTemplate() )) {
+ if (m_pausedCount > 0 || getObject()->isDisabled() || proRulesRefuse( getObject(), getSpecialPowerTemplate() )) {
return;
}
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
index f4470b849..35bde5988 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp
@@ -1135,19 +1135,7 @@ UpdateSleepTime AIUpdateInterface::update( void )
// assume we can sleep forever, unless the state machine (or turret, etc) demand otherwise
UpdateSleepTime subMachineSleep = UPDATE_SLEEP_FOREVER;
- /* -aislice: think every n-th frame, drive every frame.
-
- The state machine below is where a unit decides - what to attack, where the next waypoint is,
- whether to give up and repath - and it is the expensive half of the object walk. The
- locomotor at the bottom of this function is what actually moves it, and that is not skipped,
- so a sliced-out frame is a frame the unit keeps driving along the route it already has
- without asking any new questions. The stagger is the object id: creation order, identical on
- every machine, so this stays inside the CRC. Off by default (n = 1). */
- const Int aiSlice = TheGlobalData ? TheGlobalData->m_aiSliceFrames : 1;
- const Bool thinkThisFrame = (aiSlice <= 1) ||
- (((TheGameLogic->getFrame() + (UnsignedInt)getObject()->getID()) % (UnsignedInt)aiSlice) == 0);
-
- StateReturnType stRet = thinkThisFrame ? getStateMachine()->updateStateMachine() : STATE_CONTINUE;
+ StateReturnType stRet = getStateMachine()->updateStateMachine();
// A unit that was just built walks a short exit path out of its producer and then, if the player
// set a rally point, attack moves to it - so it stops and fights whatever it runs into on the way
@@ -1247,8 +1235,7 @@ UpdateSleepTime AIUpdateInterface::update( void )
! obj->isDisabledByType( DISABLED_HACKED ) )
{
// If we are dead, don't let the turrets do anything anymore, or else they will keep attacking
- // (a turret is deciding too, so it waits with the rest of the unit's thinking under -aislice)
- for (int i = 0; thinkThisFrame && i < MAX_TURRETS; ++i)
+ for (int i = 0; i < MAX_TURRETS; ++i)
{
if (m_turretAI[i])
{
@@ -1583,7 +1570,7 @@ Bool AIUpdateInterface::needToRotate(void)
//-------------------------------------------------------------------------------------------------
-// -crowd: the constants the steering stack is made of, all in world units (a pathfind cell is 10).
+// the crowd model: the constants the steering stack is made of, all in world units (a pathfind cell is 10).
//-------------------------------------------------------------------------------------------------
static const Real CROWD_AIR = 4.0f; ///< air a body wants round it, on top of both radii
static const Real CROWD_SEP_STEP = 1.5f; ///< most one frame of separation may move a lane
@@ -1600,7 +1587,7 @@ static const Real CROWD_AIM_URGENT = 0.67f; ///< and while manoeuvring (~20/sec)
static const Real CROWD_AIM_DEAD = 0.035f; ///< two degrees: hold the wheel still rather than chase the noise
//-------------------------------------------------------------------------------------------------
/* Being stuck. These are not crowd constants: every unit trying to drive somewhere is measured
- against them, with or without -crowd. The rungs of the ladder are spaced by continued lack of
+ against them, whether or not the crowd model steers it. The rungs of the ladder are spaced by continued lack of
progress rather than by wall clock, so a unit that starts moving again drops off it at once. */
//-------------------------------------------------------------------------------------------------
static const Real STUCK_TURN_EPSILON = 0.004f; ///< a quarter of a degree a frame: below this the hull is not turning
@@ -1664,11 +1651,8 @@ Bool AIUpdateInterface::processCollision(PhysicsBehavior *physics, Object *other
m_curMaxBlockedSpeed = maxSpeed;
}
- // before settling in behind him, see whether the route is wide enough to go round.
- // under -crowd the same decision is made every frame in crowdSteer, off the band and the
- // whole neighbourhood rather than off this one collision, so the old rule stands down
- if (!TheGlobalData->m_crowdModel)
- tryLaneChangeAround(other);
+ // whether the route is wide enough to go round is decided every frame in crowdSteer, off the
+ // band and the whole neighbourhood rather than off this one collision
if (!aiOther->isMovingAwayFrom(getObject())) {
@@ -1710,14 +1694,13 @@ Bool AIUpdateInterface::processCollision(PhysicsBehavior *physics, Object *other
// at a group's destination every arriving unit shoved the parked ones, which
// shoved others - the group milled about and repathed without end)
//
- /* -crowd asks again, under the three conditions that revert was missing. We have
+ /* The crowd model asks again, under the three conditions that revert was missing. We have
to have been held up for a while, so an arrival that clears on its own is left
alone; we have to still have somewhere to be, which is what stops the whole thing
at a destination where nobody does; and the parked unit has to be the smaller of
the two, so a mob of infantry cannot pass a tank around by taking turns to shove
it. */
- if (TheGlobalData->m_crowdModel
- && m_crowdQueued > CROWD_FAN_FRAMES * 2
+ if (m_crowdQueued > CROWD_FAN_FRAMES * 2
&& Crowd_remaining(getObject()) > PATHFIND_CELL_SIZE_F * 3.0f
&& !crowdOutranksMe(other)
&& !aiOther->isMovingAwayFrom(getObject())
@@ -1739,13 +1722,9 @@ Bool AIUpdateInterface::processCollision(PhysicsBehavior *physics, Object *other
{
if (!aiOther->needToRotate())
{
- // Deadlocked. -crowd settles it by size and by who is nearer the end of his
- // route, which is the same order the steering used all the way here; retail
- // settles it by who is carrying the more urgent kind of order
- const Bool yield = TheGlobalData->m_crowdModel
- ? crowdOutranksMe(other)
- : !hasHigherPathPriority(aiOther);
- if (yield)
+ // Deadlocked: settled by size and by who is nearer the end of his route, which is
+ // the same order the steering used all the way here
+ if (crowdOutranksMe(other))
{
// get out of his way.
aiMoveAwayFromUnit(aiOther->getObject(), CMD_FROM_AI);
@@ -2329,9 +2308,6 @@ void AIUpdateInterface::seedLaneFraction( void )
m_laneHoldFrame = 0;
m_hasPendingLane = FALSE;
- if (TheGlobalData->m_noLanePath)
- m_laneFraction = 0.5f;
-
// the other end of the SHOWLANES trail: a lane handed out at order time is worth nothing if the
// path arrives after something else has already seeded this unit at the centre.
if (TheGlobalData->m_showLanes)
@@ -2341,86 +2317,6 @@ void AIUpdateInterface::seedLaneFraction( void )
}
}
-//-------------------------------------------------------------------------------------------------
-/**
- * Take a different lane to get past a unit that is in the way and not going anywhere.
- *
- * The alternative retail offers is to wait, count blocked frames, and eventually spend a search on
- * a route that starts from the middle of the queue - which is how a column of tanks turns into a
- * column of stopped tanks. Sliding across the band costs no search at all: the route is unchanged,
- * only the point on it the unit steers at moves. The lane is held for a while so it does not flap
- * between the two sides of a blocker who is himself drifting, and it is paid for in a little speed.
- */
-//-------------------------------------------------------------------------------------------------
-void AIUpdateInterface::tryLaneChangeAround( Object *other )
-{
- if (TheGlobalData->m_noLanePath)
- return;
- if (!m_laneFractionValid || getPath() == NULL)
- return;
- if (TheGameLogic->getFrame() < m_laneHoldFrame)
- return;
- if (m_curLocomotor == NULL)
- return;
-
- // only worth going round somebody slower than us; anybody keeping up will clear on his own
- Real mySpeed = m_curLocomotor->getMaxSpeedForCondition(getObject()->getBodyModule()->getDamageState());
- if (mySpeed < 0.05f)
- return;
- /* How fast the blocker is actually going, not how fast his engine could. Comparing top speeds
- means a column of identical tanks never passes anything: every one of them reports full
- speed while crawling nose to tail behind the same jam, so the one mechanism that could
- break the queue up refused to fire in exactly the case it was written for. */
- AIUpdateInterface *aiOther = other->getAI();
- Real hisSpeed = 0.0f;
- if (aiOther != NULL && aiOther->isMoving() && other->getPhysics() != NULL)
- hisSpeed = other->getPhysics()->getVelocityMagnitude();
- if (hisSpeed > mySpeed * 0.8f)
- return;
-
- Coord3D onPath;
- Coord2D dir;
- if (!getPath()->closestPointAndDir(*getObject()->getPosition(), &onPath, &dir))
- return;
-
- Coord2D left, right;
- left.x = -dir.y; left.y = dir.x;
- right.x = dir.y; right.y = -dir.x;
-
- Pathfinder *pf = TheAI->pathfinder();
- PathfindLayerEnum layer = getObject()->getLayer();
- Real leftRoom = pf->laneExtent(getObject(), m_locomotorSet, layer, &onPath, &left);
- Real rightRoom = pf->laneExtent(getObject(), m_locomotorSet, layer, &onPath, &right);
- Real width = leftRoom + rightRoom;
- if (width < 1.0f)
- return; // a doorway has no room to pass in, and pretending otherwise just wedges both units
-
- // where the blocker sits across the same band, and how far past him we have to be to clear
- Real hisLateral = (other->getPosition()->x - onPath.x) * left.x
- + (other->getPosition()->y - onPath.y) * left.y;
- Real hisFraction = Pathfinder_laneFraction(hisLateral, leftRoom, rightRoom);
- Real gap = (getObject()->getGeometryInfo().getBoundingCircleRadius()
- + other->getGeometryInfo().getBoundingCircleRadius()) / width;
-
- // prefer the side we are already on, and take the other one if that side has no room
- Real want = (m_laneFraction >= hisFraction) ? (hisFraction + gap) : (hisFraction - gap);
- if (want > 0.95f || want < 0.05f)
- want = (m_laneFraction >= hisFraction) ? (hisFraction - gap) : (hisFraction + gap);
- if (want > 0.95f || want < 0.05f)
- return;
- if (fabs(want - m_laneFraction) < 0.02f)
- return;
-
- m_laneFraction = want;
- m_laneHoldFrame = TheGameLogic->getFrame() + PF_LANE_HOLD_FRAMES;
- getPath()->invalidateCachedPointOnPath(); // or we steer at the old lane for another twenty frames
-
- // a unit crabbing sideways is not driving forwards at full speed
- Real cap = mySpeed * 0.85f;
- if (cap < m_curMaxBlockedSpeed)
- m_curMaxBlockedSpeed = cap;
-}
-
//-------------------------------------------------------------------------------------------------
/**
* Right of way between two units, decided the same way by both of them.
@@ -2460,7 +2356,7 @@ Bool AIUpdateInterface::crowdOutranksMe( Object *other ) const
/**
* Where across the route to drive this frame, and how fast.
*
- * This is the whole -crowd model, and it is one function on purpose: every rule in it reads the
+ * This is the whole crowd model, and it is one function on purpose: every rule in it reads the
* same neighbour scan and writes the same two numbers, and the only two numbers the engine's
* steering will accept are the point to aim at and the speed to aim at it with. Retail has one
* reactive rule (a collision, once it has already happened, caps the speed) and consequently a
@@ -3500,14 +3396,12 @@ void AIUpdateInterface::crowdSteer( Coord3D& goalPos, Real& speed )
cap = ease;
}
- // ease off through a bend, or the outside of the group is asked for a speed it cannot turn at
- const Real bend = (Real)fabs( m_corridor->curvature( i ) );
- if (bend > 0.15f)
- {
- Real f = 1.0f - bend * 0.5f;
- if (f < 0.55f) f = 0.55f;
- cap *= f;
- }
+ /* No easing off for a bend. There was a rule here that cut the speed to as little as 55% wherever
+ the route turned within four samples, and the corners of a pathfinder route are everywhere: a
+ quarter of all crowd frames on the choke probe were under it, at an average of two thirds of
+ full speed, and a unit with the road to itself ran at 0.92. The locomotor already slows for a
+ turn it cannot make. Taking the rule out brought the last of 20 Crusaders in after 2136 frames
+ instead of 2581, with blocked unit-frames 3965 against 5815 and wedged 2439 against 3890. */
//--- and finally, the two numbers the locomotor takes ------------------------------------------
/* How far ahead to steer. The distance is the old one, two cells and a body; what changed is
@@ -3607,9 +3501,10 @@ void AIUpdateInterface::crowdSteer( Coord3D& goalPos, Real& speed )
{
const char *mode = pressing ? "press" : (giveWay ? "yield" : (merged ? "merge"
: (queued ? "brake" : (blocker != NULL ? "pass" : "free"))));
- DEBUG_LOG(("SHOWLANES crowd: unit %d %s sample %d lat %.1f band %.1f/%.1f lane %d/%d of %d queued %d stuck %d rank %d speed %.2f\n",
+ DEBUG_LOG(("SHOWLANES crowd: unit %d %s sample %d lat %.1f band %.1f/%.1f lane %d/%d of %d queued %d stuck %d rank %d speed %.2f cross %d vel %.2f\n",
self->getID(), mode, i, m_crowdLat, here.left, here.right, laneMine, laneFit, m_crowdLaneOf,
- m_crowdQueued, m_noProgress, rank, speed));
+ m_crowdQueued, m_noProgress, rank, speed, crossing ? 1 : 0,
+ myPhys != NULL ? myPhys->getVelocityMagnitude() : 0.0f));
}
}
@@ -3727,13 +3622,10 @@ UpdateSleepTime AIUpdateInterface::doLocomotor( void )
arrived. The cell it is standing in gets more expensive for about a second, which is
long enough for whoever repaths next to be handed a way round the line instead of a
place in it. */
- if (!TheGlobalData->m_noFlowPath)
- {
- Int trafficRadius = 0;
- Bool trafficCenter = true;
- TheAI->pathfinder()->getRadiusAndCenter(getObject(), trafficRadius, trafficCenter);
- TheAI->pathfinder()->noteTraffic(getObject()->getPosition(), trafficRadius);
- }
+ Int trafficRadius = 0;
+ Bool trafficCenter = true;
+ TheAI->pathfinder()->getRadiusAndCenter(getObject(), trafficRadius, trafficCenter);
+ TheAI->pathfinder()->noteTraffic(getObject()->getPosition(), trafficRadius);
}
else
{
@@ -3744,7 +3636,7 @@ UpdateSleepTime AIUpdateInterface::doLocomotor( void )
its own id so the whole army does not do it on one frame. Always from where the unit
actually is - a claim made a second ago against a plan that has since been held up is
exactly the claim that would send somebody else round a crossing that is no longer there. */
- if (!TheGlobalData->m_noFlowPath && getPath() != NULL)
+ if (getPath() != NULL)
{
UnsignedInt stagger = TheGameLogic->getFrame() + (UnsignedInt)getObject()->getID();
if ((stagger % PF_CLAIM_REFRESH_FRAMES) == 0)
@@ -3871,11 +3763,11 @@ UpdateSleepTime AIUpdateInterface::doLocomotor( void )
inside the crowd model because being wedged is not a crowd problem. */
if (!rescueSteer(goalPos))
{
- /* -crowd hangs here, on the two numbers about to be handed to the locomotor. The
- point on the route has already been worked out; the crowd model moves it sideways
- across the width of the road and takes speed off for whatever is in the way.
- Ground movement only - an aircraft has no road and no traffic. */
- if (TheGlobalData->m_crowdModel && isDoingGroundMovement())
+ /* The crowd model hangs here, on the two numbers about to be handed to the
+ locomotor. The point on the route has already been worked out; the crowd model
+ moves it sideways across the width of the road and takes speed off for whatever is
+ in the way. Ground movement only - an aircraft has no road and no traffic. */
+ if (isDoingGroundMovement())
crowdSteer(goalPos, speed);
}
@@ -7142,7 +7034,7 @@ void AIUpdateInterface::xfer( Xfer *xfer )
if (version >= 9)
{
- /* -crowd's lane, which is a distance and not a share, plus how long the unit has been held
+ /* The crowd model's lane, which is a distance and not a share, plus how long the unit has been held
up - a save made in the middle of a jam that came back with everybody patient again would
restart the jam from the beginning. The band itself is not saved: it is derived from the
route and is rebuilt the first frame after the load. */
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
index d3926c3e3..a005db6d1 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
@@ -1160,21 +1160,16 @@ void GameLogic::startNewGame( Bool loadingSaveGame )
TheWritableGlobalData->m_loadScreenRender = TRUE; ///< mark it so only a few select things are rendered during load
TheWritableGlobalData->m_TiVOFastMode = FALSE; //always disable the TIVO fast-forward mode at the start of a new game.
- /* Every switch below changes what a unit or the AI decides, and a decision that differs between
- two machines is a desync. None of them is in the INI checksum, so a player who types one joins
- a lobby like anyone else and the match comes apart on the first order instead of being refused
- at the door. They are measurement tools - the point of each is to run the same exe twice and
- compare - so a network game runs the shipped rules whatever the command line said. Replays are
- left alone: a replay recorded with a flag needs that flag to play back. Anything new that
- reaches GameLogic from the command line belongs in this list on the day it is written. */
+ /* Every switch below puts something into the match that the other machines never hear about, and
+ none of them is in the INI checksum, so a player who types one joins a lobby like anyone else
+ and the match comes apart on the first order instead of being refused at the door. They set up
+ an unattended measurement, so a network game runs the host's options whatever the command line
+ said. No switch changes how a unit decides: the movement A/B switches that used to sit in this
+ list were taken out of the game, and a new rule goes in on for everybody or not at all.
+ Anything new that reaches GameLogic from the command line belongs in this list on the day it
+ is written. */
if (isInMultiplayerGame())
{
- TheWritableGlobalData->m_crowdModel = FALSE; // -crowd
- TheWritableGlobalData->m_noFlowPath = FALSE; // -noflowpath
- TheWritableGlobalData->m_noLanePath = FALSE; // -nolanes
- TheWritableGlobalData->m_noMomentumPath = FALSE; // -nomomentum
- TheWritableGlobalData->m_aiSliceFrames = 1; // -aislice
- TheWritableGlobalData->m_groupDrill = 0; // -groupdrill
TheWritableGlobalData->m_scenarioFile.clear(); // -scenario
TheWritableGlobalData->m_peaceTime = 0; // -peacetime, and the host's options string is read below
TheWritableGlobalData->m_unitLimit = FALSE; // -unitlimit, the same
@@ -3948,166 +3943,6 @@ static const char *getModuleProfileReport( void )
}
#endif
-//-------------------------------------------------------------------------------------------------
-/** -groupdrill: play the part of a player giving group orders.
-
- The self-play harness never exercised the crowd model, and it took a SHOWLANES log to notice.
- The computer's armies do not move as groups: a skirmish AI team hands each of its units its own
- aiMoveToPosition, and a unit that was never handed a lane is one crowdSteer returns out of on
- its first line. Every steering rule under -crowd was therefore reachable by a human with a
- mouse and by nothing else, while ai-batch.ps1 reported on the flag's other half - the collision
- rules in AIUpdate::blockedBy - and called it the crowd model.
-
- This selects each player's ground army every n frames and gives it one order, through the same
- AIGroup::groupMoveToPosition a right-click goes through. The match it produces is nonsense:
- two armies marching corner to corner past each other, nobody defending anything, and the win
- rate means nothing at all. The blocked unit-frames underneath it are the point, and they are
- the first numbers this fork has ever had for the steering itself. */
-//-------------------------------------------------------------------------------------------------
-/* What the drill is for, in the end: were the units that were sent somewhere still trying to get
- there when the next order arrived, or had they stopped. Blocked unit-frames say how much time
- was spent in traffic; this says whether the traffic was ever cleared. One entry per unit per
- order, scored at the next tick and thrown away.
-
- "Stalled" is deliberately not "did not arrive". Forty units sent to one point cannot all stand
- on it, and a unit that spent the whole window fighting has not failed to move for want of a
- route. It is "covered less than a tenth of the distance it was given", which is a unit that
- never got going at all. */
-struct DrillOrder
-{
- ObjectID id;
- Coord3D dest;
- Real startDist;
-};
-static std::vector<DrillOrder> theDrillOrders;
-static Int theDrillScored = 0;
-static Int theDrillArrived = 0;
-static Int theDrillStalled = 0;
-
-/* And why the stalled ones stalled. "1.2% never got going" is a number to be held to; it is not
- an answer, and without this the only way to find out was to watch a match. Every unit that
- scores as stalled is asked the six questions that can be asked from outside it, in the order
- that makes the answer unambiguous: the first one that fits is the reason. */
-enum
-{
- DRILL_WHY_DISABLED = 0, ///< held, EMP'd, sold, whatever: not a movement answer
- DRILL_WHY_NOSTATE, ///< not in a move state any more, so something else took the unit over
- DRILL_WHY_NOPATH, ///< in a move state, no path and not waiting for one: the search failed
- DRILL_WHY_WAITING, ///< still waiting for the pathfinder
- DRILL_WHY_BLOCKED, ///< has a path and is being collided with
- DRILL_WHY_SILENT, ///< has a path, nothing is touching it, and it is not moving
- DRILL_WHY_COUNT
-};
-static const char *theDrillWhyName[ DRILL_WHY_COUNT ] =
- { "disabled", "nostate", "nopath", "waiting", "blocked", "silent" };
-static Int theDrillWhy[ DRILL_WHY_COUNT ];
-static char theDrillReport[ 256 ];
-
-const char *GroupDrill_report( void )
-{
- Int len = sprintf( theDrillReport, "orders %d arrived %d stalled %d",
- theDrillScored, theDrillArrived, theDrillStalled );
- for( Int w = 0; w < DRILL_WHY_COUNT; w++ )
- len += sprintf( theDrillReport + len, " %s %d", theDrillWhyName[ w ], theDrillWhy[ w ] );
- return theDrillReport;
-}
-
-void GroupDrill_reset( void )
-{
- theDrillOrders.clear();
- theDrillScored = 0;
- theDrillArrived = 0;
- theDrillStalled = 0;
- for( Int w = 0; w < DRILL_WHY_COUNT; w++ )
- theDrillWhy[ w ] = 0;
-}
-
-/** Why is this unit, which was sent somewhere twenty seconds ago and has not moved, not moving. */
-static Int groupDrillWhyStalled( Object *obj )
-{
- AIUpdateInterface *ai = obj->getAIUpdateInterface();
- if (ai == NULL || obj->isDisabled())
- return DRILL_WHY_DISABLED;
-
- const AIStateType state = ai->getAIStateType();
- if (state != AI_MOVE_TO && state != AI_ATTACK_MOVE_TO && state != AI_MOVE_AND_TIGHTEN
- && state != AI_FOLLOW_PATH && state != AI_MOVE_OUT_OF_THE_WAY)
- return DRILL_WHY_NOSTATE;
-
- if (ai->isWaitingForPath())
- return DRILL_WHY_WAITING;
- if (ai->getPath() == NULL)
- return DRILL_WHY_NOPATH;
- if (ai->getNumFramesBlocked() > 0)
- return DRILL_WHY_BLOCKED;
- return DRILL_WHY_SILENT;
-}
-
-static void groupDrillScorePrevious( void )
-{
- const Real arriveDist = PATHFIND_CELL_SIZE_F * 12.0f;
-
- for (std::vector<DrillOrder>::iterator it = theDrillOrders.begin(); it != theDrillOrders.end(); ++it)
- {
- Object *obj = TheGameLogic->findObjectByID( it->id );
- if (obj == NULL || obj->isEffectivelyDead())
- continue; // died on the way: not a movement answer either way
-
- /* Only units that were actually given a journey. Forty units sent to a point they are
- already standing on shuffle a body length while the group re-forms, and against a starting
- distance of eight world units that shuffle reads as "went nowhere": four of the first
- seven stalls this ever reported were that. */
- if (it->startDist < arriveDist * 2.0f)
- continue;
-
- const Coord3D *pos = obj->getPosition();
- const Real dx = it->dest.x - pos->x;
- const Real dy = it->dest.y - pos->y;
- const Real now = (Real)sqrt( dx * dx + dy * dy );
-
- AIUpdateInterface *ai = obj->getAIUpdateInterface();
- const Bool doneWithIt = (ai == NULL) || (ai->getPath() == NULL && !ai->isWaitingForPath());
-
- /* Arrived, and the second half of that is not pedantry either. Forty units cannot stand on
- one point, so the ones that packed in around it are further from the middle than the
- radius allows while being exactly where they meant to stop. A unit that has stopped
- trying and is inside a quarter of the distance it was given has arrived. */
- if (now < arriveDist || (doneWithIt && now < it->startDist * 0.25f))
- {
- ++theDrillScored;
- ++theDrillArrived;
- continue;
- }
-
- /* Still ours? The computer player goes on giving its teams orders of its own between drill
- ticks, and a unit sent somewhere else is not a unit that failed to get here. Without this
- the stalled figure was two fifths of every order given, and most of that was the AI
- changing its mind rather than anything being stuck. */
- Coord3D goal;
- if (!TheAI->pathfinder()->goalPosition( obj, &goal ))
- continue;
- const Real gdx = goal.x - it->dest.x;
- const Real gdy = goal.y - it->dest.y;
- if ((Real)sqrt( gdx * gdx + gdy * gdy ) > PATHFIND_CELL_SIZE_F * 20.0f)
- continue;
-
- ++theDrillScored;
- if (now > it->startDist * 0.9f)
- {
- ++theDrillStalled;
- const Int why = groupDrillWhyStalled( obj );
- ++theDrillWhy[ why ];
- DEBUG_LOG(("DRILLSTALL frame %d unit %d %s: %s, %.0f of %.0f left at %.0f,%.0f layer %d, blocked %d noprogress %d state %d\n",
- TheGameLogic->getFrame(), (Int)it->id, obj->getTemplate()->getName().str(),
- theDrillWhyName[ why ], now, it->startDist, pos->x, pos->y, (Int)obj->getLayer(),
- ai ? ai->getNumFramesBlocked() : -1,
- ai ? ai->getNoProgressFrames() : -1,
- ai ? (Int)ai->getAIStateType() : -1));
- }
- }
- theDrillOrders.clear();
-}
-
/* Both peace time gates - the one in Object::getAbleToAttackSpecificObject that stops a weapon
being aimed, and the one in ActiveBody::attemptDamage that stops damage arriving by any other
route - ask this. The truce is between the players who are in the lobby: civilians, the map's
@@ -4194,80 +4029,6 @@ static void peaceTimeTick( void )
}
}
-static void groupDrillTick( void )
-{
- groupDrillScorePrevious();
-
- Region3D extent;
- TheTerrainLogic->getExtent( &extent );
- const Real inset = PATHFIND_CELL_SIZE_F * 8.0f;
-
- // which corner this tick sends them to; alternating it marches the army back and forth over the
- // same ground rather than parking it once and measuring an empty map
- const Int tick = (Int)(TheGameLogic->getFrame() / (UnsignedInt)TheGlobalData->m_groupDrill);
-
- for( Int p = 0; p < ThePlayerList->getPlayerCount(); p++ )
- {
- Player *player = ThePlayerList->getNthPlayer( p );
- if (player == NULL)
- continue;
-
- AIGroup *group = TheAI->createGroup();
- Int taken = 0;
- for( Object *obj = TheGameLogic->getFirstObject(); obj; obj = obj->getNextObject() )
- {
- if (obj->getControllingPlayer() != player || obj->isEffectivelyDead())
- continue;
- if (obj->getAIUpdateInterface() == NULL)
- continue;
- // the army, and only the army: a base that stops building has no traffic to measure
- if (obj->isKindOf( KINDOF_STRUCTURE ) || obj->isKindOf( KINDOF_IMMOBILE )
- || obj->isKindOf( KINDOF_AIRCRAFT ) || obj->isKindOf( KINDOF_DOZER )
- || obj->isKindOf( KINDOF_HARVESTER ))
- continue;
-
- group->add( obj );
- if (++taken >= 40)
- break;
- }
-
- if (taken < 2)
- {
- TheAI->destroyGroup( group );
- continue;
- }
-
- Coord3D dest;
- const Bool farCorner = ((tick + p) & 1) != 0;
- dest.x = farCorner ? extent.hi.x - inset : extent.lo.x + inset;
- dest.y = farCorner ? extent.hi.y - inset : extent.lo.y + inset;
- dest.z = TheTerrainLogic->getGroundHeight( dest.x, dest.y );
-
- group->groupMoveToPosition( &dest, false, CMD_FROM_AI );
-
- // and remember who was sent where, so the next tick can ask whether they got there
- for( Object *member = TheGameLogic->getFirstObject(); member; member = member->getNextObject() )
- {
- if (!group->isMember( member ))
- continue;
- // the order itself skips these, so counting them as sent somewhere is counting a
- // passenger in a transport as a unit that failed to drive there
- if (member->isDisabledByType( DISABLED_HELD ) || member->isKindOf( KINDOF_IMMOBILE ))
- continue;
- const Coord3D *pos = member->getPosition();
- const Real dx = dest.x - pos->x;
- const Real dy = dest.y - pos->y;
- DrillOrder order;
- order.id = member->getID();
- order.dest = dest;
- order.startDist = (Real)sqrt( dx * dx + dy * dy );
- theDrillOrders.push_back( order );
- }
-
- TheAI->destroyGroup( group );
- }
-}
-
void GameLogic::update( void )
{
USE_PERF_TIMER(GameLogic_update)
@@ -4344,12 +4105,7 @@ void GameLogic::update( void )
// the lobby's peace time, if the host set one
peaceTimeTick();
- // the measurement harness for group movement; the first tick waits for there to be an army
- if (TheGlobalData->m_groupDrill > 0 && now > (UnsignedInt)(LOGICFRAMES_PER_SECOND * 60)
- && (now % (UnsignedInt)TheGlobalData->m_groupDrill) == 0)
- groupDrillTick();
-
- /* And the scripted one. Keyed to the logic frame rather than to the render pass, so the same
+ /* The scripted measurement harness. Keyed to the logic frame rather than to the render pass, so the same
scenario file plays out on the same frames however fast the machine draws - which is the whole
point of measuring two builds against it. */
ScenarioDrill_tick();
@@ -5557,7 +5313,7 @@ void GameLogic::prepareLogicForObjectLoad( void )
// ------------------------------------------------------------------------------------------------
void GameLogic::xfer( Xfer *xfer )
{
-
+
// version
const XferVersion currentVersion = 14;
XferVersion version = currentVersion;
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp
index 7bb2a28e3..3df9053e0 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp
@@ -60,12 +60,24 @@ static const Real SCENARIO_DEFAULT_SPACING = 30.0f;
/// "keep shooting until told otherwise" - the same count the mob's own self-tasking passes
static const Int SCENARIO_ATTACK_SHOTS = 999;
-// token counts, including the frame and the action name
+/// how close to its target a unit has to get before arrive counts it, when the line does not say
+static const Real SCENARIO_DEFAULT_ARRIVE_RADIUS = 200.0f;
+
+/// the one-token position, and what separates its offset
+static const char *SCENARIO_START_PREFIX = "start";
+static const char SCENARIO_START_OFFSET_SEPARATOR = ':';
+
+// the fewest tokens each action can be written in, including the frame and the action name, with a
+// position written as its one-token start<N> form
static const Int SCENARIO_TOKENS_STOP = 4;
-static const Int SCENARIO_TOKENS_MOVE = 6;
+static const Int SCENARIO_TOKENS_MOVE = 5;
static const Int SCENARIO_TOKENS_ATTACK = 6;
-static const Int SCENARIO_TOKENS_SPAWN = 7;
-static const Int SCENARIO_TOKENS_SPAWN_WITH_SPACING = 8;
+static const Int SCENARIO_TOKENS_SPAWN = 6;
+static const Int SCENARIO_TOKENS_ARRIVE = 5;
+
+// where the position starts in each line that has one
+static const Int SCENARIO_SPAWN_POSITION_TOKEN = 5;
+static const Int SCENARIO_ORDER_POSITION_TOKEN = 4;
static const char *SCENARIO_DIRECTORY = "Scenarios\\";
static const char *SCENARIO_EXTENSION = ".txt";
@@ -148,12 +160,75 @@ static Bool parseActionType( const AsciiString &token, ScenarioActionType *actio
*action = SCENARIO_ACTION_ATTACK;
else if (token == "stop")
*action = SCENARIO_ACTION_STOP;
+ else if (token == "arrive")
+ *action = SCENARIO_ACTION_ARRIVE;
else
return FALSE;
return TRUE;
}
+/** A position at tokens[*index]: two numbers, or start<N>, or start<N>:<dx>:<dy>. Moves *index past
+ whatever it used. The start number is spelt out digit by digit for parseWholeNumber's reason, and
+ an offset that is not two numbers is refused rather than read as zero. */
+static ScenarioParseResult parseScenarioPosition( const AsciiString *tokens, Int count, Int *index,
+ ScenarioAction *action )
+{
+ if (*index >= count)
+ return SCENARIO_PARSE_MISSING_ARGS;
+
+ const char *word = tokens[ *index ].str();
+ const Int prefixLength = (Int)strlen( SCENARIO_START_PREFIX );
+ if (strncmp( word, SCENARIO_START_PREFIX, prefixLength ) != 0)
+ {
+ if (*index + 1 >= count)
+ return SCENARIO_PARSE_MISSING_ARGS;
+
+ action->atStart = SCENARIO_NO_START;
+ action->at.x = (Real)atof( word );
+ action->at.y = (Real)atof( tokens[ *index + 1 ].str() );
+ *index += 2;
+ return SCENARIO_PARSE_OK;
+ }
+
+ const char *at = word + prefixLength;
+ Int start = 0;
+ Int digits = 0;
+ while (*at >= '0' && *at <= '9')
+ {
+ start = start * 10 + (*at - '0');
+ ++at;
+ ++digits;
+ }
+ if (digits == 0)
+ return SCENARIO_PARSE_BAD_POSITION;
+
+ action->atStart = start;
+ action->at.x = 0.0f;
+ action->at.y = 0.0f;
+
+ if (*at == SCENARIO_START_OFFSET_SEPARATOR)
+ {
+ const char *xText = at + 1;
+ char *end = NULL;
+ action->at.x = (Real)strtod( xText, &end );
+ if (end == xText || *end != SCENARIO_START_OFFSET_SEPARATOR)
+ return SCENARIO_PARSE_BAD_POSITION;
+
+ const char *yText = end + 1;
+ action->at.y = (Real)strtod( yText, &end );
+ if (end == yText || *end != 0)
+ return SCENARIO_PARSE_BAD_POSITION;
+ }
+ else if (*at != 0)
+ {
+ return SCENARIO_PARSE_BAD_POSITION;
+ }
+
+ *index += 1;
+ return SCENARIO_PARSE_OK;
+}
+
static Int tokensNeededFor( ScenarioActionType action )
{
switch (action)
@@ -163,6 +238,7 @@ static Int tokensNeededFor( ScenarioActionType action )
case SCENARIO_ACTION_ATTACKMOVE: return SCENARIO_TOKENS_MOVE;
case SCENARIO_ACTION_ATTACK: return SCENARIO_TOKENS_ATTACK;
case SCENARIO_ACTION_STOP: return SCENARIO_TOKENS_STOP;
+ case SCENARIO_ACTION_ARRIVE: return SCENARIO_TOKENS_ARRIVE;
}
return SCENARIO_TOKENS_STOP;
}
@@ -199,8 +275,10 @@ ScenarioParseResult ScenarioDrill_parseLine( const char *line, ScenarioAction *a
action->selector = tokens[ 3 ];
action->at.x = 0.0f;
action->at.y = 0.0f;
+ action->atStart = SCENARIO_NO_START;
action->count = 1;
action->spacing = SCENARIO_DEFAULT_SPACING;
+ action->radius = SCENARIO_DEFAULT_ARRIVE_RADIUS;
action->targetSlot = 0;
action->targetSelector.clear();
@@ -210,18 +288,25 @@ ScenarioParseResult ScenarioDrill_parseLine( const char *line, ScenarioAction *a
{
if (!parseWholeNumber( tokens[ 4 ], &action->count ) || action->count < 1)
return SCENARIO_PARSE_BAD_COUNT;
- action->at.x = (Real)atof( tokens[ 5 ].str() );
- action->at.y = (Real)atof( tokens[ 6 ].str() );
- if (count >= SCENARIO_TOKENS_SPAWN_WITH_SPACING)
- action->spacing = (Real)atof( tokens[ 7 ].str() );
+ Int next = SCENARIO_SPAWN_POSITION_TOKEN;
+ const ScenarioParseResult position = parseScenarioPosition( tokens, count, &next, action );
+ if (position != SCENARIO_PARSE_OK)
+ return position;
+ if (count > next)
+ action->spacing = (Real)atof( tokens[ next ].str() );
break;
}
case SCENARIO_ACTION_MOVE:
case SCENARIO_ACTION_ATTACKMOVE:
+ case SCENARIO_ACTION_ARRIVE:
{
- action->at.x = (Real)atof( tokens[ 4 ].str() );
- action->at.y = (Real)atof( tokens[ 5 ].str() );
+ Int next = SCENARIO_ORDER_POSITION_TOKEN;
+ const ScenarioParseResult position = parseScenarioPosition( tokens, count, &next, action );
+ if (position != SCENARIO_PARSE_OK)
+ return position;
+ if (actionType == SCENARIO_ACTION_ARRIVE && count > next)
+ action->radius = (Real)atof( tokens[ next ].str() );
break;
}
@@ -251,6 +336,7 @@ const char *ScenarioDrill_parseResultName( ScenarioParseResult result )
case SCENARIO_PARSE_BAD_SLOT: return "slot is not a whole number";
case SCENARIO_PARSE_BAD_COUNT: return "count is not a whole number above zero";
case SCENARIO_PARSE_MISSING_ARGS: return "not enough arguments for this action";
+ case SCENARIO_PARSE_BAD_POSITION: return "position is not x y, start<N> or start<N>:<dx>:<dy>";
}
return "unknown";
}
@@ -268,8 +354,27 @@ static Int theScenarioUnitsSpawned = 0;
static UnsignedInt theScenarioLastFrame = 0;
static char theScenarioReport[ SCENARIO_REPORT_LENGTH ];
+static const UnsignedInt SCENARIO_NOT_ARRIVED = 0xffffffff;
+
+/** One arrive line: the units that matched when it fired, and the frame each first stood within the
+ radius of the target. The units are fixed when the line fires, so one that is built afterwards
+ cannot finish the run for a unit still stuck in the choke. */
+struct ScenarioArrival
+{
+ Int slot;
+ AsciiString selector;
+ Coord3D goal;
+ Real radius;
+ UnsignedInt fromFrame;
+ std::vector<ObjectID> ids;
+ std::vector<UnsignedInt> arrivedOn;
+};
+
+static std::vector<ScenarioArrival> theScenarioArrivals;
+
static void resetScenario( void )
{
+ theScenarioArrivals.clear();
theScenarioActions.clear();
theScenarioCursor = 0;
theScenarioLoaded = FALSE;
@@ -383,17 +488,20 @@ static Bool selectorMatches( const AsciiString &selector, const Object *obj )
return tmpl->getName() == selector;
}
+/** Whether this player owns the object, it matches the selector and it can be given an order at all. */
+static Bool isOrderableMatch( const Player *player, const AsciiString &selector, Object *obj )
+{
+ return obj->getControllingPlayer() == player && !obj->isEffectivelyDead()
+ && obj->getAIUpdateInterface() != NULL && selectorMatches( selector, obj );
+}
+
/** Everything this player owns that matches the selector and can be given an order at all. */
static Int gatherIntoGroup( Player *player, const AsciiString &selector, AIGroup *group )
{
Int taken = 0;
for( Object *obj = TheGameLogic->getFirstObject(); obj; obj = obj->getNextObject() )
{
- if (obj->getControllingPlayer() != player || obj->isEffectivelyDead())
- continue;
- if (obj->getAIUpdateInterface() == NULL)
- continue;
- if (!selectorMatches( selector, obj ))
+ if (!isOrderableMatch( player, selector, obj ))
continue;
group->add( obj );
@@ -402,6 +510,31 @@ static Int gatherIntoGroup( Player *player, const AsciiString &selector, AIGroup
return taken;
}
+/** Where the action's position is on this map: its own numbers, or a start position plus the offset
+ it gave. -scenario pins seat i to start i, and start waypoints are numbered from 1. */
+static Bool resolveScenarioPosition( const ScenarioAction &action, Coord3D *pos )
+{
+ pos->x = action.at.x;
+ pos->y = action.at.y;
+
+ if (action.atStart != SCENARIO_NO_START)
+ {
+ AsciiString waypointName;
+ waypointName.format( "Player_%d_Start", action.atStart + 1 );
+ const Waypoint *start = TheTerrainLogic->getWaypointByName( waypointName );
+ if (start == NULL)
+ {
+ DEBUG_LOG(("SCENARIO: frame %d: this map has no %s\n", action.frame, waypointName.str()));
+ return FALSE;
+ }
+ pos->x += start->getLocation()->x;
+ pos->y += start->getLocation()->y;
+ }
+
+ pos->z = TheTerrainLogic->getGroundHeight( pos->x, pos->y );
+ return TRUE;
+}
+
static Object *findFirstMatching( Player *player, const AsciiString &selector )
{
for( Object *obj = TheGameLogic->getFirstObject(); obj; obj = obj->getNextObject() )
@@ -439,7 +572,7 @@ static Bool spawnOne( const ThingTemplate *tmpl, Team *team, const Coord3D *pos
return TRUE;
}
-static Bool executeSpawn( const ScenarioAction &action, Player *player )
+static Bool executeSpawn( const ScenarioAction &action, Player *player, const Coord3D &centre )
{
const ThingTemplate *tmpl = TheThingFactory->findTemplate( action.selector, FALSE );
if (tmpl == NULL)
@@ -464,8 +597,8 @@ static Bool executeSpawn( const ScenarioAction &action, Player *player )
for( Int i = 0; i < action.count; ++i )
{
Coord3D pos;
- pos.x = action.at.x + (i % columns) * action.spacing - halfWidth;
- pos.y = action.at.y + (i / columns) * action.spacing - halfHeight;
+ pos.x = centre.x + (i % columns) * action.spacing - halfWidth;
+ pos.y = centre.y + (i / columns) * action.spacing - halfHeight;
pos.z = TheTerrainLogic->getGroundHeight( pos.x, pos.y );
if (spawnOne( tmpl, team, &pos ))
@@ -475,12 +608,109 @@ static Bool executeSpawn( const ScenarioAction &action, Player *player )
theScenarioUnitsSpawned += made;
DEBUG_LOG(("SCENARIO: frame %d spawn slot %d '%s' %d of %d at (%.0f,%.0f)\n",
action.frame, action.slot, action.selector.str(),
- made, action.count, action.at.x, action.at.y));
+ made, action.count, centre.x, centre.y));
return made > 0;
}
-static Bool executeOrder( const ScenarioAction &action, Player *player )
+/** Watch every unit of this seat that matches the selector as they stand now, and note the frame
+ each one first comes within the radius of the target. The watch starts on the line's own frame,
+ so a file puts it on the frame of the order it is timing. */
+static Bool executeArrive( const ScenarioAction &action, Player *player, const Coord3D &goal )
+{
+ ScenarioArrival arrival;
+ arrival.slot = action.slot;
+ arrival.selector = action.selector;
+ arrival.goal = goal;
+ arrival.radius = action.radius;
+ arrival.fromFrame = TheGameLogic->getFrame();
+
+ for( Object *obj = TheGameLogic->getFirstObject(); obj; obj = obj->getNextObject() )
+ {
+ if (!isOrderableMatch( player, action.selector, obj ))
+ continue;
+
+ arrival.ids.push_back( obj->getID() );
+ arrival.arrivedOn.push_back( SCENARIO_NOT_ARRIVED );
+ }
+
+ DEBUG_LOG(("SCENARIO: frame %d arrive slot %d '%s' x%d within %.0f of (%.0f,%.0f)\n",
+ action.frame, action.slot, action.selector.str(), (Int)arrival.ids.size(),
+ action.radius, goal.x, goal.y));
+
+ if (arrival.ids.empty())
+ return FALSE;
+
+ theScenarioArrivals.push_back( arrival );
+ return TRUE;
+}
+
+static void updateArrivals( UnsignedInt now )
+{
+ for( std::vector<ScenarioArrival>::iterator it = theScenarioArrivals.begin();
+ it != theScenarioArrivals.end(); ++it )
+ {
+ const Real radiusSquared = it->radius * it->radius;
+ for( size_t i = 0; i < it->ids.size(); ++i )
+ {
+ if (it->arrivedOn[ i ] != SCENARIO_NOT_ARRIVED)
+ continue;
+
+ Object *obj = TheGameLogic->findObjectByID( it->ids[ i ] );
+ if (obj == NULL || obj->isEffectivelyDead())
+ continue;
+
+ const Real dx = obj->getPosition()->x - it->goal.x;
+ const Real dy = obj->getPosition()->y - it->goal.y;
+ if (dx * dx + dy * dy <= radiusSquared)
+ it->arrivedOn[ i ] = now;
+ }
+ }
+}
+
+void ScenarioDrill_logArrivals( void )
+{
+ for( std::vector<ScenarioArrival>::const_iterator it = theScenarioArrivals.begin();
+ it != theScenarioArrivals.end(); ++it )
+ {
+ Int arrived = 0;
+ Int lost = 0;
+ UnsignedInt first = SCENARIO_NOT_ARRIVED;
+ UnsignedInt last = 0;
+ for( size_t i = 0; i < it->ids.size(); ++i )
+ {
+ const UnsignedInt on = it->arrivedOn[ i ];
+ if (on != SCENARIO_NOT_ARRIVED)
+ {
+ ++arrived;
+ first = (on < first) ? on : first;
+ last = (on > last) ? on : last;
+ continue;
+ }
+
+ Object *obj = TheGameLogic->findObjectByID( it->ids[ i ] );
+ if (obj == NULL || obj->isEffectivelyDead())
+ ++lost;
+ }
+
+ const Int total = (Int)it->ids.size();
+ const Int stillOut = total - arrived - lost;
+ if (arrived == 0)
+ {
+ DEBUG_LOG(("HEADLESS ARRIVE: slot %d '%s' from frame %d: none of %d within %.0f of (%.0f,%.0f), %d lost, %d still out\n",
+ it->slot, it->selector.str(), it->fromFrame, total, it->radius, it->goal.x, it->goal.y,
+ lost, stillOut));
+ continue;
+ }
+
+ DEBUG_LOG(("HEADLESS ARRIVE: slot %d '%s' from frame %d: %d of %d within %.0f of (%.0f,%.0f), first after %d frames, last after %d frames (%.1f s), %d lost, %d still out\n",
+ it->slot, it->selector.str(), it->fromFrame, arrived, total, it->radius, it->goal.x, it->goal.y,
+ first - it->fromFrame, last - it->fromFrame,
+ (Real)(last - it->fromFrame) / (Real)LOGICFRAMES_PER_SECOND, lost, stillOut));
+ }
+}
+
+static Bool executeOrder( const ScenarioAction &action, Player *player, const Coord3D &dest )
{
AIGroup *group = TheAI->createGroup();
const Int taken = gatherIntoGroup( player, action.selector, group );
@@ -498,11 +728,6 @@ static Bool executeOrder( const ScenarioAction &action, Player *player )
case SCENARIO_ACTION_MOVE:
case SCENARIO_ACTION_ATTACKMOVE:
{
- Coord3D dest;
- dest.x = action.at.x;
- dest.y = action.at.y;
- dest.z = TheTerrainLogic->getGroundHeight( dest.x, dest.y );
-
if (action.action == SCENARIO_ACTION_MOVE)
group->groupMoveToPosition( &dest, FALSE, CMD_FROM_SCRIPT );
else
@@ -545,6 +770,7 @@ static Bool executeOrder( const ScenarioAction &action, Player *player )
}
case SCENARIO_ACTION_SPAWN:
+ case SCENARIO_ACTION_ARRIVE:
ordered = FALSE; // handled before the group is built
break;
}
@@ -562,10 +788,17 @@ Bool ScenarioDrill_execute( const ScenarioAction &action )
return FALSE;
}
+ Coord3D position;
+ if (!resolveScenarioPosition( action, &position ))
+ return FALSE;
+
if (action.action == SCENARIO_ACTION_SPAWN)
- return executeSpawn( action, player );
+ return executeSpawn( action, player, position );
- return executeOrder( action, player );
+ if (action.action == SCENARIO_ACTION_ARRIVE)
+ return executeArrive( action, player, position );
+
+ return executeOrder( action, player, position );
}
// ------------------------------------------------------------------------------------------------
@@ -574,9 +807,6 @@ Bool ScenarioDrill_execute( const ScenarioAction &action )
void ScenarioDrill_tick( void )
{
- if (TheGlobalData->m_scenarioFile.isEmpty())
- return;
-
// the shell map is a running game too, and an army spawned onto the main menu is not the match
// anybody asked to measure
if (TheGameLogic->isInShellGame())
@@ -589,6 +819,12 @@ void ScenarioDrill_tick( void )
resetScenario();
theScenarioLastFrame = now;
+ // before the file test, because an arrive typed down the control socket has no file behind it
+ updateArrivals( now );
+
+ if (TheGlobalData->m_scenarioFile.isEmpty())
+ return;
+
if (!theScenarioLoaded)
loadScenario();
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 399fe8c8a..8628ef323 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -10805,7 +10805,7 @@ TEST(a_turn_costs_what_the_hull_takes_to_swing_it)
CHECK_EQ( Pathfinder_turnCost( 3.14159f, 40, 60 ), 60 );
CHECK_EQ( Pathfinder_turnCost( 3.14159f, 40, 28 ), 28 );
- // a hull that turns on the spot pays nothing, and so does the switch being off
+ // a hull that turns on the spot pays nothing, and neither does a search with no hull behind it
CHECK_EQ( Pathfinder_turnCost( 3.14159f, 0, 60 ), 0 );
CHECK_EQ( Pathfinder_turnCost( 0.0f, 40, 60 ), 0 );
@@ -11387,12 +11387,12 @@ TEST(pro_rules_ban_the_listed_things_and_nothing_beside_them)
CHECK( !ProRulesBanUpgrade( AsciiString( "Nuke_Upgrade_ChinaWGUraniumShells" ) ) );
// rule 2: the missile, for each general that fires one, and not the other superweapons' powers
- CHECK( ProRulesBanSpecialPower( SPECIAL_NEUTRON_MISSILE ) );
- CHECK( ProRulesBanSpecialPower( NUKE_SPECIAL_NEUTRON_MISSILE ) );
- CHECK( ProRulesBanSpecialPower( SUPW_SPECIAL_NEUTRON_MISSILE ) );
- CHECK( !ProRulesBanSpecialPower( SPECIAL_SCUD_STORM ) );
- CHECK( !ProRulesBanSpecialPower( SPECIAL_PARTICLE_UPLINK_CANNON ) );
- CHECK( !ProRulesBanSpecialPower( SPECIAL_CLUSTER_MINES ) );
+ CHECK( ProRulesBanSpecialPower( SPECIAL_NEUTRON_MISSILE, 5 ) );
+ CHECK( ProRulesBanSpecialPower( NUKE_SPECIAL_NEUTRON_MISSILE, 5 ) );
+ CHECK( ProRulesBanSpecialPower( SUPW_SPECIAL_NEUTRON_MISSILE, 5 ) );
+ CHECK( !ProRulesBanSpecialPower( SPECIAL_SCUD_STORM, 1 ) );
+ CHECK( !ProRulesBanSpecialPower( SPECIAL_PARTICLE_UPLINK_CANNON, 1 ) );
+ CHECK( !ProRulesBanSpecialPower( SPECIAL_CLUSTER_MINES, 1 ) );
// rule 7: a terrorist on a combat cycle, and every other rider still rides
CHECK( ProRulesBanRider( AsciiString( "GLAInfantryTerrorist" ) ) );
@@ -11407,6 +11407,62 @@ TEST(pro_rules_ban_the_listed_things_and_nothing_beside_them)
CHECK( (Int)PRO_RULES_ENEMY_STRUCTURE_CLEARANCE > 225 );
}
+/* Rules 12 to 15 ride on the one Pro Rules box like every other rule: three upgrades by name, and
+ the Carpet Bomb until rank 3. */
+TEST(pro_rules_ban_rules_12_to_15)
+{
+ CHECK( ProRulesBanUpgrade( AsciiString( "Demo_Upgrade_SuicideBomb" ) ) );
+ CHECK( ProRulesBanUpgrade( AsciiString( "Upgrade_ChinaNeutronShells" ) ) );
+ CHECK( ProRulesBanUpgrade( AsciiString( "AirF_Upgrade_StealthComanche" ) ) );
+
+ // the Comanche's rocket pods and the other two shells stay buildable
+ CHECK( !ProRulesBanUpgrade( AsciiString( "Upgrade_ComancheRocketPods" ) ) );
+ CHECK( !ProRulesBanUpgrade( AsciiString( "Upgrade_ChinaUraniumShells" ) ) );
+ CHECK( !ProRulesBanUpgrade( AsciiString( "Upgrade_GLAToxinShells" ) ) );
+
+ // rule 15: rank 3 is where the carpet bomb opens
+ CHECK( ProRulesBanSpecialPower( AIRF_SPECIAL_CARPET_BOMB, 2 ) );
+ CHECK( !ProRulesBanSpecialPower( AIRF_SPECIAL_CARPET_BOMB, PRO_RULES_CARPET_BOMB_RANK ) );
+ CHECK( ProRulesBanSpecialPower( SPECIAL_CARPET_BOMB, 1 ) );
+ CHECK( ProRulesBanSpecialPower( SPECIAL_CHINA_CARPET_BOMB, 2 ) );
+ CHECK( ProRulesBanSpecialPower( EARLY_SPECIAL_CHINA_CARPET_BOMB, 2 ) );
+ CHECK( !ProRulesBanSpecialPower( SPECIAL_CLUSTER_MINES, 1 ) );
+}
+
+/* Rule 16: two of a player's own defences per oil derrick cluster. A cluster is every derrick
+ chained to the next within the radius, so a pair 250 apart is one cluster and a derrick 600 away
+ is another. */
+TEST(pro_rules_count_the_defenses_of_one_derrick_cluster)
+{
+ CHECK( ProRulesIsOilDerrick( AsciiString( "TechOilDerrick" ) ) );
+ CHECK( !ProRulesIsOilDerrick( AsciiString( "TechOilDerrickHulk" ) ) );
+ CHECK( ProRulesIsDerrickDefense( AsciiString( "AmericaPatriotBattery" ) ) );
+ CHECK( ProRulesIsDerrickDefense( AsciiString( "AirF_AmericaPatriotBattery" ) ) );
+ CHECK( ProRulesIsDerrickDefense( AsciiString( "Tank_ChinaGattlingCannon" ) ) );
+ CHECK( ProRulesIsDerrickDefense( AsciiString( "Demo_GLAStingerSite" ) ) );
+ CHECK( !ProRulesIsDerrickDefense( AsciiString( "ChinaHelixGattlingCannon" ) ) );
+ CHECK( !ProRulesIsDerrickDefense( AsciiString( "AmericaFireBase" ) ) );
+ CHECK( !ProRulesIsDerrickDefense( AsciiString( "GLATunnelNetwork" ) ) );
+
+ const Coord2D derricks[] = { { 0.0f, 0.0f }, { 250.0f, 0.0f }, { 850.0f, 0.0f } };
+ const Coord2D defenses[] = { { -100.0f, 50.0f }, { 400.0f, 0.0f }, { 850.0f, 200.0f } };
+ const Int derrickCount = ARRAY_SIZE( derricks );
+ const Int defenseCount = ARRAY_SIZE( defenses );
+
+ const Coord2D besideTheFirst = { 0.0f, 150.0f };
+ CHECK_EQ( ProRulesCountDerrickClusterDefenses( besideTheFirst, derricks, derrickCount, defenses, defenseCount ), 2 );
+
+ // the far end of the pair reaches the same two
+ const Coord2D besideTheSecond = { 300.0f, -100.0f };
+ CHECK_EQ( ProRulesCountDerrickClusterDefenses( besideTheSecond, derricks, derrickCount, defenses, defenseCount ), 2 );
+
+ const Coord2D besideTheLoneDerrick = { 850.0f, -100.0f };
+ CHECK_EQ( ProRulesCountDerrickClusterDefenses( besideTheLoneDerrick, derricks, derrickCount, defenses, defenseCount ), 1 );
+
+ const Coord2D inTheOpen = { 0.0f, 2000.0f };
+ CHECK_EQ( ProRulesCountDerrickClusterDefenses( inTheOpen, derricks, derrickCount, defenses, defenseCount ), 0 );
+}
+
/* -scenario's line parser.
*
* A scenario file that gets half-read still plays a match and still writes a frame time table, so
@@ -11508,6 +11564,54 @@ TEST(scenario_refuses_a_line_it_cannot_read)
CHECK_STR( ScenarioDrill_parseResultName( SCENARIO_PARSE_BAD_FRAME ), "frame is not a whole number" );
}
+/* A position can name a start instead of two numbers, which is what lets one file play on a
+ generated map whose starts move with the seed. The number is spelt out for the atoi reason, and
+ an offset that is not two numbers is refused rather than read as zero. */
+TEST(scenario_positions_can_name_a_start)
+{
+ ScenarioAction action;
+
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "30 spawn 0 AmericaTankCrusader 20 start0", &action ), (Int)SCENARIO_PARSE_OK );
+ CHECK_EQ( action.atStart, 0 );
+ CHECK_NEAR( action.at.x, 0.0f, 0.01f );
+ CHECK_NEAR( action.at.y, 0.0f, 0.01f );
+ CHECK_NEAR( action.spacing, 30.0f, 0.01f );
+
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "30 spawn 0 AmericaTankCrusader 20 start1:-250.5:80 40", &action ),
+ (Int)SCENARIO_PARSE_OK );
+ CHECK_EQ( action.atStart, 1 );
+ CHECK_NEAR( action.at.x, -250.5f, 0.01f );
+ CHECK_NEAR( action.at.y, 80.0f, 0.01f );
+ CHECK_NEAR( action.spacing, 40.0f, 0.01f );
+
+ // plain numbers still mean a position, and say so
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "60 move 0 * 800 600", &action ), (Int)SCENARIO_PARSE_OK );
+ CHECK_EQ( action.atStart, (Int)SCENARIO_NO_START );
+
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "60 move 0 * start", &action ), (Int)SCENARIO_PARSE_BAD_POSITION );
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "60 move 0 * start1x", &action ), (Int)SCENARIO_PARSE_BAD_POSITION );
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "60 move 0 * start1:100", &action ), (Int)SCENARIO_PARSE_BAD_POSITION );
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "60 move 0 * start1:100:y", &action ), (Int)SCENARIO_PARSE_BAD_POSITION );
+}
+
+/* arrive is the choke probe's clock: it takes a position like move and an optional radius. */
+TEST(scenario_parses_an_arrive_line)
+{
+ ScenarioAction action;
+
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "60 arrive 0 AmericaTankCrusader start1", &action ), (Int)SCENARIO_PARSE_OK );
+ CHECK_EQ( (Int)action.action, (Int)SCENARIO_ACTION_ARRIVE );
+ CHECK_EQ( action.atStart, 1 );
+ CHECK( action.radius > 0.0f );
+
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "60 arrive 0 * 1200 900 150", &action ), (Int)SCENARIO_PARSE_OK );
+ CHECK_NEAR( action.at.x, 1200.0f, 0.01f );
+ CHECK_NEAR( action.radius, 150.0f, 0.01f );
+
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "60 arrive 0 *", &action ), (Int)SCENARIO_PARSE_MISSING_ARGS );
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "60 arrive 0 * 1200", &action ), (Int)SCENARIO_PARSE_MISSING_ARGS );
+}
+
/* -control's WebSocket handshake.
*
* The reply to a client key is SHA-1 of the key and the protocol's GUID, base64'd. Nothing in
diff --git a/ai-batch.ps1 b/ai-batch.ps1
index be24ee68f..b353f4be1 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 "-aislice",'4') without a rebuild between batches
+ # (e.g. -ExtraArgs "-unitlimit") without a rebuild between batches
[string[]] $ExtraArgs = @(),
# minutes before a wedged run is killed rather than waited on forever
[int] $TimeoutMinutes = 20
@@ -179,12 +179,6 @@ for ($i = 0; $i -lt $Runs; $i++) {
$why = $Matches[1]
$frames = [int]$Matches[2]
}
- elseif ($line -match "HEADLESS DRILL: orders (\d+) arrived (\d+) stalled (\d+)") {
- # -groupdrill only: did the units that were marched across the map get there
- $pf.Orders = [int]$Matches[1]
- $pf.Arrived = [int]$Matches[2]
- $pf.Stalled = [int]$Matches[3]
- }
elseif ($line -match "HEADLESS PATHFIND: (.*)") {
$report = $Matches[1]
# "queue 6000x/47 find 2313x/0 ... expand 11414x | nopath 0 outofcells 0 blocked 17 stuck 0"
@@ -202,7 +196,7 @@ for ($i = 0; $i -lt $Runs; $i++) {
if ($report -match "outofcells (\d+)") { $pf.OutOfCells = [int]$Matches[1] }
if ($report -match "blocked (\d+)") { $pf.Blocked = [int]$Matches[1] }
if ($report -match "stuck (\d+)") { $pf.Stuck = [int]$Matches[1] }
- # the crowd model's own three: a unit stopped with nothing to blame it on, the backing-out
+ # the rescue ladder's own counts: a unit stopped with nothing to blame it on, the backing-out
# manoeuvres that answers, and the routes given up on entirely
if ($report -match "wedge (\d+)") { $pf.Wedge = [int]$Matches[1] }
if ($report -match "worst (\d+)") { $pf.WedgeWorst = [int]$Matches[1] }
@@ -306,7 +300,7 @@ if ($pfRows.Count -gt 0) {
Write-Host ("blocked unit-frames per 1000 logic frames: {0:n1}" -f (1000.0 * $totBlocked / $totFrames))
# and the half of it a collision never sees: stopped with nothing to blame, and what was done
- # about it. Only the crowd model counts these, so a run without -crowd reports zeroes.
+ # about it.
$totWedge = ($pfRows | ForEach-Object { $_.Pf.Wedge } | Measure-Object -Sum).Sum
# the worst is the one that matters: the rescue ladder promises nothing is left wanting to move
# and not moving for longer than its own cycle, and this is the number that holds it to it
@@ -317,16 +311,6 @@ if ($pfRows.Count -gt 0) {
(& $avg { param($p) $p.Escapes }),
(& $avg { param($p) $p.Repaths }),
(& $avg { param($p) $p.Dithers }))
-
- # -groupdrill only: the plainest question there is. Of every unit sent across the map, how many
- # were still going when the next order came, and how many had stopped and stayed stopped.
- $totOrders = ($pfRows | ForEach-Object { $_.Pf.Orders } | Measure-Object -Sum).Sum
- if ($totOrders -gt 0) {
- $totArrived = ($pfRows | ForEach-Object { $_.Pf.Arrived } | Measure-Object -Sum).Sum
- $totStalled = ($pfRows | ForEach-Object { $_.Pf.Stalled } | Measure-Object -Sum).Sum
- Write-Host ("group orders: {0:n0} scored, {1:n1}% reached the destination, {2:n1}% never got going" -f
- $totOrders, (100.0 * $totArrived / $totOrders), (100.0 * $totStalled / $totOrders))
- }
}
# Stability. A mean frame time is the statistic that hides a stutter, so this reports the tail:
diff --git a/replay-check.ps1 b/replay-check.ps1
index 83228ef5f..34c61393c 100644
--- a/replay-check.ps1
+++ b/replay-check.ps1
@@ -17,7 +17,7 @@
A mismatch names the frame it was taken at, not the frame it started at, so it says a divergence
happened rather than where. That is still the whole difference between shipping a desync and
- not: -DebugCRCFromFrame in an _INTERNAL build is what narrows it down afterwards.
+ not: -DebugCRCFromFrame, which Release parses too, is what narrows it down afterwards.
.EXAMPLE
.\replay-check.ps1
@@ -39,9 +39,9 @@ param(
# where the game is
[string] $RunDir = "$PSScriptRoot\GeneralsMD\Run",
[string] $Exe = "generals.exe",
- # switches to add to both halves of every seed. A movement flag has to be on for the recording
- # and the playback alike: turning it on for one of them is a divergence the script would report
- # as a broken build. -ExtraArgs -crowd is the crowd model's determinism check
+ # switches to add to both halves of every seed. A switch that reaches the match has to be on for
+ # the recording and the playback alike: turning it on for one of them is a divergence the script
+ # would report as a broken build. -ExtraArgs -unitlimit is the unit limit's determinism check
[string[]] $ExtraArgs = @()
)