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): drive a match from a scenario file

Olcay Seygan93204a5ef763
diff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txt
index 1fb19f6b5..6d12dde4d 100644
--- a/GeneralsMD/Code/CMakeLists.txt
+++ b/GeneralsMD/Code/CMakeLists.txt
@@ -530,7 +530,14 @@ add_custom_command(TARGET generals POST_BUILD
# join.
COMMAND ${CMAKE_COMMAND} -E copy_directory
${CMAKE_CURRENT_SOURCE_DIR}/Data/Window
- ${CMAKE_CURRENT_SOURCE_DIR}/../Run/Window)
+ ${CMAKE_CURRENT_SOURCE_DIR}/../Run/Window
+ # -scenario reads these. They are a measuring tool rather than game data: outside Data/ so they
+ # cannot collide with an archive path, and outside the multiplayer INI checksum because nothing
+ # loads them with &xferCRC. They are not in package.bat for the same reason - a player has no use
+ # for one, and a scenario run cannot be replayed anyway.
+ COMMAND ${CMAKE_COMMAND} -E copy_directory
+ ${CMAKE_CURRENT_SOURCE_DIR}/Data/Scenarios
+ ${CMAKE_CURRENT_SOURCE_DIR}/../Run/Scenarios)
add_dependencies(generals d3d8to9)
# ===========================================================================
diff --git a/GeneralsMD/Code/Data/Scenarios/mobstress.txt b/GeneralsMD/Code/Data/Scenarios/mobstress.txt
new file mode 100644
index 000000000..8cfed9e92
--- /dev/null
+++ b/GeneralsMD/Code/Data/Scenarios/mobstress.txt
@@ -0,0 +1,33 @@
+# Angry Mob stress test.
+#
+# Put a known number of mobs on the field, march them across it, and let the frame time say what
+# they cost. Without this the count is whatever the seed happened to draw, and two runs that drew
+# different factions were never comparable in the first place.
+#
+# generals.exe -headless -quickstart -noshellmap -observer -multiInstance -noFPSLimit
+# -map "Maps\Alpine Assault\Alpine Assault.map" -autoskirmish 2 -takeover
+# -side 0 FactionGLA -side 1 FactionAmerica -seed 1 -maxframes 3000
+# -scenario mobstress -logPrefix mob_
+#
+# One action a line, in this shape:
+#
+# <frame> spawn <slot> <template> <count> <x> <y> [spacing]
+# <frame> move <slot> <selector> <x> <y>
+# <frame> attackmove <slot> <selector> <x> <y>
+# <frame> attack <slot> <selector> <targetSlot> <targetSelector>
+# <frame> stop <slot> <selector>
+#
+# A selector is a template name, or * for everything that seat owns. The number after the action is
+# a seat, the same one -side takes, so slot 0 here and -side 0 mean the same player. It is not an
+# index into the engine's player list: that one opens with a neutral player and a civilian one, so
+# slot 0 was player 2 in the first two-player run, and the mapping the game recorded at startup is
+# what resolves it.
+#
+# Coordinates are world positions, the same ones -camera takes, so UI-MAP.md's verified camera
+# positions are the cheapest place to find ground that exists.
+#
+# Each nexus brings ten members with it, so eight of these is 88 objects.
+
+30 spawn 0 GLAInfantryAngryMobNexus 8 760 920 60
+600 attackmove 0 GLAInfantryAngryMobNexus 1400 1400
+1800 move 0 GLAInfantryAngryMobNexus 760 920
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
index d4f19d1d3..0187635a3 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
@@ -401,6 +401,9 @@ public:
Int m_resDrillX; ///< the width -resdrill asks for (0 = the next mode the device offers)
Int m_resDrillY; ///< the height -resdrill asks for
Bool m_resDrillKeep; ///< -resdrillkeep: answer the confirmation with Ok and stay on the new mode
+ AsciiString m_scenarioFile; ///< -scenario <name>: play Run/Scenarios/<name>.txt instead of leaving the match to a person or an AI (empty = off)
+ Bool m_autoSkirmishTakeover; ///< -takeover: give every -autoskirmish slot a driverless human seat, so nothing thinks unless a scenario says so
+ AsciiString m_autoSkirmishSide[ MAX_PLAYER_COUNT ]; ///< -side <slot> <faction>: name that slot's faction instead of drawing it from the seed
AsciiString m_netGameHosts; ///< -netgame <ip>[,<ip>...]: the slot list of a LAN game started from the command line (empty = off)
Int m_netGameLocalSlot; ///< -netslot <n>: which of those addresses this copy of the game is
AsciiString m_lanPlayerName; ///< -lanname <name>: the name this copy takes in the LAN lobby (empty = the one in the preferences)
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h
new file mode 100644
index 000000000..e304cdbf4
--- /dev/null
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h
@@ -0,0 +1,107 @@
+/*
+** Command & Conquer Generals Zero Hour(tm)
+** Copyright 2025 Electronic Arts Inc.
+**
+** This program is free software: you can redistribute it and/or modify
+** it under the terms of the GNU General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** This program is distributed in the hope that it will be useful,
+** but WITHOUT ANY WARRANTY; without even the implied warranty of
+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+** GNU General Public License for more details.
+**
+** You should have received a copy of the GNU General Public License
+** along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+// FILE: ScenarioDrill.h /////////////////////////////////////////////////////////////////////////
+//
+// -scenario <name>: play a match out of a text file instead of out of a person or an AI.
+//
+// A measurement needs the same units doing the same thing twice, and -autoskirmish cannot give
+// that: it hands every slot PLAYERTEMPLATE_RANDOM and the faction falls out of the seed, so
+// "enough angry mobs to see them cost anything" is a thing you wait for rather than a thing you
+// 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
+// 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
+// the render pass, so which logic frame an order lands on depends on how fast the machine drew -
+// 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
+// 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.
+//
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+#pragma once
+
+#ifndef __SCENARIODRILL_H_
+#define __SCENARIODRILL_H_
+
+#include "Lib/BaseType.h"
+#include "Common/AsciiString.h"
+
+// ------------------------------------------------------------------------------------------------
+/** What one scenario line asks for. */
+// ------------------------------------------------------------------------------------------------
+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_ATTACK, ///< attack <slot> <selector> <targetSlot> <targetSelector>
+ SCENARIO_ACTION_STOP ///< stop <slot> <selector>
+};
+
+// ------------------------------------------------------------------------------------------------
+/** 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. */
+// ------------------------------------------------------------------------------------------------
+enum ScenarioParseResult
+{
+ SCENARIO_PARSE_OK = 0,
+ SCENARIO_PARSE_BLANK, ///< a comment or an empty line: nothing to do, not an error
+ SCENARIO_PARSE_BAD_FRAME,
+ SCENARIO_PARSE_BAD_ACTION,
+ SCENARIO_PARSE_BAD_SLOT,
+ SCENARIO_PARSE_BAD_COUNT,
+ SCENARIO_PARSE_MISSING_ARGS
+};
+
+// ------------------------------------------------------------------------------------------------
+/** One parsed line. Which fields carry anything depends on the action - see the enum above. */
+// ------------------------------------------------------------------------------------------------
+struct ScenarioAction
+{
+ UnsignedInt frame; ///< the logic frame this fires on
+ 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
+ Int count; ///< how many to spawn
+ Real spacing; ///< how far apart to spawn them, in world units
+ Int targetSlot; ///< whose units to attack
+ AsciiString targetSelector; ///< which of them
+};
+
+/** Turn one line of a scenario file into an action. Pure: no engine state is read, which is what
+ lets the parser be tested without booting a game. */
+extern ScenarioParseResult ScenarioDrill_parseLine( const char *line, ScenarioAction *action );
+
+/** The name of a parse result, for the log. */
+extern const char *ScenarioDrill_parseResultName( ScenarioParseResult result );
+
+/** Run whatever the file asks for on this logic frame. Called from GameLogic::update. */
+extern void ScenarioDrill_tick( void );
+
+/** One line for the end-of-run summary: how much of the file actually happened. */
+extern const char *ScenarioDrill_report( void );
+
+#endif // __SCENARIODRILL_H_
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
index 1819c664f..61b24ecbb 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
@@ -1600,6 +1600,66 @@ Int parseResDrillKeep(char *args[], int)
return 1;
}
+/* -scenario <name> plays Run/Scenarios/<name>.txt: spawn this unit here, send it there, on that
+ frame.
+
+ A measurement needs the same army doing the same thing twice, and -autoskirmish cannot give it.
+ Every slot goes in as PLAYERTEMPLATE_RANDOM and the faction falls out of the seed, so "enough
+ angry mobs on the field to see what they cost" is something a batch waits for rather than
+ 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
+ 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)
+{
+ if (TheWritableGlobalData && num > 1 && args[1])
+ {
+ TheWritableGlobalData->m_scenarioFile = args[1];
+ return 2;
+ }
+ return 1;
+}
+
+/* -side <slot> <faction> nails one -autoskirmish slot to a faction instead of letting the seed
+ pick it.
+
+ populateRandomSideAndColor only draws for a slot that still reads PLAYERTEMPLATE_RANDOM, so a
+ real template index written into the slot survives untouched and nothing downstream changes.
+ The name is resolved late, in startAutoSkirmish, because PlayerTemplateStore is an INI subsystem
+ and none of it exists yet while the command line is being read. The names are the templates'
+ own: FactionGLA, FactionAmerica, FactionChina and the generals. */
+Int parseSide(char *args[], int num)
+{
+ if (TheWritableGlobalData && num > 2 && args[1] && args[2])
+ {
+ const Int slot = atoi(args[1]);
+ if (slot >= 0 && slot < MAX_SLOTS)
+ TheWritableGlobalData->m_autoSkirmishSide[slot] = args[2];
+ else
+ DEBUG_LOG(("-side: slot %d is outside 0..%d\n", slot, MAX_SLOTS - 1));
+ return 3;
+ }
+ return 1;
+}
+
+/* -takeover empties every -autoskirmish seat instead of filling it with an AI.
+
+ SLOT_TAKEOVER is an occupied seat with nothing behind it: startNewGame writes playerIsHuman for
+ it, so Player::setPlayerType never news an AIPlayer and that player sits waiting to be told what
+ to do. For a measurement that is exactly the point. An AI that builds, expands and attacks costs
+ more of the frame than whatever is under test, and it costs a different amount every run; with
+ the seats empty, nothing happens at all unless -scenario says it does. */
+Int parseTakeover(char *args[], int num)
+{
+ if (TheWritableGlobalData)
+ {
+ TheWritableGlobalData->m_autoSkirmishTakeover = TRUE;
+ }
+ return 1;
+}
+
/* -teams <n> splits an -autoskirmish lobby into n allied teams instead of a free-for-all.
Free-for-all and 4v4 are not the same load and not the same game. Eight players each fighting
@@ -2000,6 +2060,9 @@ static CommandLineParam params[] =
{ "-uidrill", parseUIDrill },
{ "-resdrill", parseResDrill },
{ "-resdrillkeep", parseResDrillKeep },
+ { "-scenario", parseScenario },
+ { "-side", parseSide },
+ { "-takeover", parseTakeover },
{ "-replay", parseReplay },
{ "-loadsave", parseLoadSave },
{ "-netgame", parseNetGame },
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
index 45a432e09..75ea27b4c 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
@@ -86,6 +86,7 @@
#include "GameLogic/GameLogic.h"
#include "GameLogic/Locomotor.h"
#include "GameLogic/RankInfo.h"
+#include "GameLogic/ScenarioDrill.h" // -scenario says at the end how much of the file ran
#include "GameLogic/ScriptEngine.h"
#include "GameLogic/SidesList.h"
@@ -383,6 +384,41 @@ static void startAutoSkirmish( void )
list with nothing but AI in it leaves that observer holding the camera, exactly the way a
replay does. Spending a slot on the observer instead would cost a bot, because MAX_SLOTS is
8 and that is also the most start positions a map has. */
+ /* -side names a faction for a slot instead of letting populateRandomSideAndColor draw one.
+ Resolve every name before a slot list is built, and refuse the whole run on one nobody
+ recognises: falling back to a random draw would still produce a match, still produce numbers,
+ and quietly answer a different question than the one that was asked. */
+ Int sideTemplate[ MAX_SLOTS ];
+ for( Int s = 0; s < MAX_SLOTS; s++ )
+ {
+ sideTemplate[ s ] = PLAYERTEMPLATE_RANDOM;
+ const AsciiString &sideName = TheGlobalData->m_autoSkirmishSide[ s ];
+ if (sideName.isEmpty())
+ continue;
+
+ const Int templateIndex = ThePlayerTemplateStore->getTemplateNumByName( sideName );
+ if (templateIndex < 0)
+ {
+ DEBUG_LOG(("-side: slot %d asks for '%s', which is not a player template\n",
+ s, sideName.str()));
+ return;
+ }
+ sideTemplate[ s ] = templateIndex;
+ }
+
+ /* -takeover leaves the opponents' seats occupied but driverless. SLOT_TAKEOVER is written into
+ the slot list as an opponent, but startNewGame marks it playerIsHuman, so setPlayerType never
+ news an AIPlayer and nothing on that side thinks. A measurement wants that: an AI building and
+ attacking costs more of the frame than whatever is under test, and a different amount every
+ run. */
+ const Bool takeover = TheGlobalData->m_autoSkirmishTakeover;
+
+ /* A scenario names map coordinates, so it needs to know which corner each slot starts in.
+ populateRandomStartPosition leaves alone any slot that already has a position in range; the
+ draw stays random without -scenario so that every existing batch plays exactly what it
+ played before. */
+ const Bool fixedStartPositions = !TheGlobalData->m_scenarioFile.isEmpty();
+
const Bool observing = TheGlobalData->m_autoSkirmishObserver;
UnicodeString localName;
localName.translate( AsciiString( "Player" ) );
@@ -393,7 +429,10 @@ static void startAutoSkirmish( void )
{
slot.setState( SLOT_PLAYER, localName );
slot.setName( localName );
- slot.setPlayerTemplate( PLAYERTEMPLATE_RANDOM );
+ }
+ else if (takeover)
+ {
+ slot.setState( SLOT_TAKEOVER );
}
else
{
@@ -402,10 +441,10 @@ static void startAutoSkirmish( void )
if ((i & 1) && TheGlobalData->m_autoSkirmishAIStateOdd != 0)
state = TheGlobalData->m_autoSkirmishAIStateOdd;
slot.setState( (SlotState)state );
- slot.setPlayerTemplate( PLAYERTEMPLATE_RANDOM );
}
+ slot.setPlayerTemplate( sideTemplate[ i ] );
slot.setColor( -1 ); // -1 is "random" to populateRandomSideAndColor
- slot.setStartPos( -1 ); // and to populateRandomStartPosition
+ slot.setStartPos( fixedStartPositions ? i : -1 ); // and -1 to populateRandomStartPosition
/* -teams splits the lobby into allied blocks: with eight players and two teams the first
four are team 0 and the rest team 1, the way the lobby numbers them. GameLogic's own
alliance pass reads the slot's team number and does the rest. Without it every slot is
@@ -452,9 +491,11 @@ static void startAutoSkirmish( void )
msg->appendIntegerArgument( 0 );
msg->appendIntegerArgument( maxFPS );
- DEBUG_LOG(("-autoskirmish: %d slots on '%s', seed %d, up to %d fps, %s\n",
+ DEBUG_LOG(("-autoskirmish: %d slots on '%s', seed %d, up to %d fps, %s%s%s\n",
numPlayers, mapName.str(), seed, maxFPS,
- observing ? "every slot AI, watching from the free camera" : "slot 0 is the local player"));
+ observing ? "every slot AI, watching from the free camera" : "slot 0 is the local player",
+ takeover ? ", seats driverless" : "",
+ fixedStartPositions ? ", start positions fixed to slot order" : ""));
}
/** -----------------------------------------------------------------------------------------------
@@ -1840,6 +1881,14 @@ static void updateHeadlessRun( 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()));
+ }
+
/* Stability, which is a different question from speed and is answered by the tail rather than
by the average. These two lines are the ones a stutter complaint is argued with. */
reportFrameTimeStats();
@@ -1879,7 +1928,12 @@ static void updateHeadlessRun( void )
written rather than left half-flushed by the process going away. */
if (TheRecorder->getMode() == RECORDERMODETYPE_RECORD)
TheRecorder->stopRecording();
- TheGameLogic->clearGameData();
+ /* And without the score screen. Nobody is sitting in front of an unattended run to read one,
+ and building it crashes the teardown: clearGameData pushes Menus/ScoreScreen.wnd, whose init
+ walks the players and calls TheGameInfo->isSandbox(), and TheGameInfo is gone by then. The
+ crash lands after every HEADLESS line is written, so the numbers of a run were never wrong -
+ the process just died on its way out and handed a script exit code 1 either way. */
+ TheGameLogic->clearGameData( FALSE );
TheGameEngine->setQuitting( TRUE );
}
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
index 7b1b1875e..aecf82de9 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
@@ -708,6 +708,10 @@ GlobalData::GlobalData()
m_resDrillX = 0;
m_resDrillY = 0;
m_resDrillKeep = FALSE;
+ m_scenarioFile.clear(); // nothing is scripted; -scenario is a measuring tool and, like -groupdrill, 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
m_netGameHosts.clear(); // no network game from the command line
m_netGameLocalSlot = 0;
m_lanPlayerName.clear(); // the lobby name comes out of the preferences unless -lanname says otherwise
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
index c29456d2c..79e031239 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
@@ -94,6 +94,7 @@
#include "GameLogic/Module/OpenContain.h"
#include "GameLogic/PartitionManager.h"
#include "GameLogic/PolygonTrigger.h"
+#include "GameLogic/ScenarioDrill.h"
#include "GameLogic/ScriptActions.h"
#include "GameLogic/ScriptConditions.h"
#include "GameLogic/ScriptEngine.h"
@@ -1166,6 +1167,7 @@ void GameLogic::startNewGame( Bool loadingSaveGame )
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
}
@@ -4261,6 +4263,11 @@ void GameLogic::update( void )
&& (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
+ 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();
+
QueryPerformanceCounter( (LARGE_INTEGER *)&tScripts );
Bool freezeTime = TheTacticalView->isTimeFrozen() && !TheTacticalView->isCameraMovementFinished();
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp
new file mode 100644
index 000000000..68693d50c
--- /dev/null
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp
@@ -0,0 +1,612 @@
+/*
+** Command & Conquer Generals Zero Hour(tm)
+** Copyright 2025 Electronic Arts Inc.
+**
+** This program is free software: you can redistribute it and/or modify
+** it under the terms of the GNU General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** This program is distributed in the hope that it will be useful,
+** but WITHOUT ANY WARRANTY; without even the implied warranty of
+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+** GNU General Public License for more details.
+**
+** You should have received a copy of the GNU General Public License
+** along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+// FILE: ScenarioDrill.cpp ///////////////////////////////////////////////////////////////////////
+//
+// -scenario <name>: play a match out of Run/Scenarios/<name>.txt. See ScenarioDrill.h for why the
+// orders go out through an AIGroup inside the logic frame rather than through the message stream.
+//
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine
+
+#include "Common/file.h"
+#include "Common/FileSystem.h"
+#include "Common/GlobalData.h"
+#include "Common/Player.h"
+#include "Common/PlayerList.h"
+#include "Common/Team.h"
+#include "Common/ThingFactory.h"
+#include "Common/ThingTemplate.h"
+#include "GameLogic/AI.h"
+#include "GameLogic/AIPathfind.h"
+#include "GameLogic/GameLogic.h"
+#include "GameLogic/Module/AIUpdate.h"
+#include "GameLogic/Module/BehaviorModule.h"
+#include "GameLogic/Module/CreateModule.h"
+#include "GameLogic/Object.h"
+#include "GameLogic/ScenarioDrill.h"
+#include "GameLogic/TerrainLogic.h"
+
+#include <algorithm>
+#include <vector>
+
+// ------------------------------------------------------------------------------------------------
+// the shape of a scenario line
+// ------------------------------------------------------------------------------------------------
+
+static const Int SCENARIO_MAX_TOKENS = 10;
+static const char SCENARIO_COMMENT_CHAR = '#';
+static const char *SCENARIO_SELECTOR_ALL = "*";
+
+/// how far apart spawned units stand, when the line does not say
+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
+static const Int SCENARIO_TOKENS_STOP = 4;
+static const Int SCENARIO_TOKENS_MOVE = 6;
+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 char *SCENARIO_DIRECTORY = "Scenarios\\";
+static const char *SCENARIO_EXTENSION = ".txt";
+
+static const Int SCENARIO_REPORT_LENGTH = 192;
+
+// ------------------------------------------------------------------------------------------------
+// parsing
+// ------------------------------------------------------------------------------------------------
+
+static Bool isScenarioSpace( char c )
+{
+ return c == ' ' || c == '\t' || c == '\r' || c == '\n';
+}
+
+/** Split a line into whitespace-separated tokens, stopping at a comment. Returns how many it
+ found, which may be more than maxTokens - the caller checks the count it wanted. */
+static Int tokenizeScenarioLine( const char *line, AsciiString *tokens, Int maxTokens )
+{
+ Int found = 0;
+ const char *at = line;
+
+ while (*at != 0)
+ {
+ while (*at != 0 && isScenarioSpace( *at ))
+ ++at;
+
+ if (*at == 0 || *at == SCENARIO_COMMENT_CHAR)
+ break;
+
+ const char *start = at;
+ while (*at != 0 && !isScenarioSpace( *at ) && *at != SCENARIO_COMMENT_CHAR)
+ ++at;
+
+ if (found < maxTokens)
+ {
+ const Int length = (Int)(at - start);
+ char word[ 128 ];
+ const Int copied = (length < (Int)sizeof( word ) - 1) ? length : (Int)sizeof( word ) - 1;
+ memcpy( word, start, copied );
+ word[ copied ] = 0;
+ tokens[ found ].set( word );
+ }
+ ++found;
+ }
+
+ return found;
+}
+
+/** atoi cannot tell "0" from "banana", and a scenario that quietly reads a typo as frame 0 fires
+ its whole file on the first frame. So spell the digits out. */
+static Bool parseWholeNumber( const AsciiString &token, Int *value )
+{
+ const char *at = token.str();
+ if (at == NULL || *at == 0)
+ return FALSE;
+
+ Int accumulated = 0;
+ while (*at != 0)
+ {
+ if (*at < '0' || *at > '9')
+ return FALSE;
+ accumulated = accumulated * 10 + (*at - '0');
+ ++at;
+ }
+
+ *value = accumulated;
+ return TRUE;
+}
+
+static Bool parseActionType( const AsciiString &token, ScenarioActionType *action )
+{
+ if (token == "spawn")
+ *action = SCENARIO_ACTION_SPAWN;
+ else if (token == "move")
+ *action = SCENARIO_ACTION_MOVE;
+ else if (token == "attackmove")
+ *action = SCENARIO_ACTION_ATTACKMOVE;
+ else if (token == "attack")
+ *action = SCENARIO_ACTION_ATTACK;
+ else if (token == "stop")
+ *action = SCENARIO_ACTION_STOP;
+ else
+ return FALSE;
+
+ return TRUE;
+}
+
+static Int tokensNeededFor( ScenarioActionType action )
+{
+ switch (action)
+ {
+ case SCENARIO_ACTION_SPAWN: return SCENARIO_TOKENS_SPAWN;
+ case SCENARIO_ACTION_MOVE: return SCENARIO_TOKENS_MOVE;
+ case SCENARIO_ACTION_ATTACKMOVE: return SCENARIO_TOKENS_MOVE;
+ case SCENARIO_ACTION_ATTACK: return SCENARIO_TOKENS_ATTACK;
+ case SCENARIO_ACTION_STOP: return SCENARIO_TOKENS_STOP;
+ }
+ return SCENARIO_TOKENS_STOP;
+}
+
+ScenarioParseResult ScenarioDrill_parseLine( const char *line, ScenarioAction *action )
+{
+ AsciiString tokens[ SCENARIO_MAX_TOKENS ];
+ const Int count = tokenizeScenarioLine( line, tokens, SCENARIO_MAX_TOKENS );
+ if (count == 0)
+ return SCENARIO_PARSE_BLANK;
+
+ // a bare frame number with nothing after it is a line somebody started and did not finish
+ if (count < SCENARIO_TOKENS_STOP)
+ return SCENARIO_PARSE_MISSING_ARGS;
+
+ Int frame = 0;
+ if (!parseWholeNumber( tokens[ 0 ], &frame ))
+ return SCENARIO_PARSE_BAD_FRAME;
+
+ ScenarioActionType actionType;
+ if (!parseActionType( tokens[ 1 ], &actionType ))
+ return SCENARIO_PARSE_BAD_ACTION;
+
+ Int slot = 0;
+ if (!parseWholeNumber( tokens[ 2 ], &slot ))
+ return SCENARIO_PARSE_BAD_SLOT;
+
+ if (count < tokensNeededFor( actionType ))
+ return SCENARIO_PARSE_MISSING_ARGS;
+
+ action->frame = (UnsignedInt)frame;
+ action->action = actionType;
+ action->slot = slot;
+ action->selector = tokens[ 3 ];
+ action->at.x = 0.0f;
+ action->at.y = 0.0f;
+ action->count = 1;
+ action->spacing = SCENARIO_DEFAULT_SPACING;
+ action->targetSlot = 0;
+ action->targetSelector.clear();
+
+ switch (actionType)
+ {
+ case SCENARIO_ACTION_SPAWN:
+ {
+ 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() );
+ break;
+ }
+
+ case SCENARIO_ACTION_MOVE:
+ case SCENARIO_ACTION_ATTACKMOVE:
+ {
+ action->at.x = (Real)atof( tokens[ 4 ].str() );
+ action->at.y = (Real)atof( tokens[ 5 ].str() );
+ break;
+ }
+
+ case SCENARIO_ACTION_ATTACK:
+ {
+ if (!parseWholeNumber( tokens[ 4 ], &action->targetSlot ))
+ return SCENARIO_PARSE_BAD_SLOT;
+ action->targetSelector = tokens[ 5 ];
+ break;
+ }
+
+ case SCENARIO_ACTION_STOP:
+ break;
+ }
+
+ return SCENARIO_PARSE_OK;
+}
+
+const char *ScenarioDrill_parseResultName( ScenarioParseResult result )
+{
+ switch (result)
+ {
+ case SCENARIO_PARSE_OK: return "ok";
+ case SCENARIO_PARSE_BLANK: return "blank";
+ case SCENARIO_PARSE_BAD_FRAME: return "frame is not a whole number";
+ case SCENARIO_PARSE_BAD_ACTION: return "no such action";
+ 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";
+ }
+ return "unknown";
+}
+
+// ------------------------------------------------------------------------------------------------
+// the loaded file, and what happened to it
+// ------------------------------------------------------------------------------------------------
+
+static std::vector<ScenarioAction> theScenarioActions;
+static Int theScenarioCursor = 0;
+static Bool theScenarioLoaded = FALSE;
+static Int theScenarioActionsRun = 0;
+static Int theScenarioActionsFailed = 0;
+static Int theScenarioUnitsSpawned = 0;
+static UnsignedInt theScenarioLastFrame = 0;
+static char theScenarioReport[ SCENARIO_REPORT_LENGTH ];
+
+static void resetScenario( void )
+{
+ theScenarioActions.clear();
+ theScenarioCursor = 0;
+ theScenarioLoaded = FALSE;
+ theScenarioActionsRun = 0;
+ theScenarioActionsFailed = 0;
+ theScenarioUnitsSpawned = 0;
+}
+
+/** Sorted by frame, and stable so two actions on the same frame keep the order the file wrote
+ them in. An unstable sort would make the run depend on the standard library's mood, which is
+ the one thing a repeatable measurement cannot have. */
+static Bool scenarioActionIsEarlier( const ScenarioAction &left, const ScenarioAction &right )
+{
+ return left.frame < right.frame;
+}
+
+static void loadScenario( void )
+{
+ theScenarioLoaded = TRUE;
+
+ AsciiString path;
+ path.set( SCENARIO_DIRECTORY );
+ path.concat( TheGlobalData->m_scenarioFile );
+ path.concat( SCENARIO_EXTENSION );
+
+ /* Read it as bytes, not as text. readEntireAndClose sizes its buffer from size() and then reads
+ that many bytes; in text mode the CRLF translation hands back fewer than it asked for and the
+ tail of the buffer is whatever was in the heap. So take the file as it lies and let the
+ tokenizer treat a carriage return as the whitespace it is. */
+ File *file = TheFileSystem->openFile( path.str(), File::READ );
+ if (file == NULL)
+ {
+ DEBUG_LOG(("SCENARIO: cannot open '%s'\n", path.str()));
+ return;
+ }
+
+ const Int fileSize = file->size();
+ char *contents = file->readEntireAndClose(); // this also closes and frees the File
+ if (contents == NULL)
+ {
+ DEBUG_LOG(("SCENARIO: '%s' read as nothing\n", path.str()));
+ return;
+ }
+
+ Int lineNumber = 0;
+ Int at = 0;
+ while (at < fileSize)
+ {
+ Int end = at;
+ while (end < fileSize && contents[ end ] != '\n')
+ ++end;
+
+ const Int length = end - at;
+ char line[ 512 ];
+ const Int copied = (length < (Int)sizeof( line ) - 1) ? length : (Int)sizeof( line ) - 1;
+ memcpy( line, contents + at, copied );
+ line[ copied ] = 0;
+ ++lineNumber;
+
+ ScenarioAction action;
+ const ScenarioParseResult result = ScenarioDrill_parseLine( line, &action );
+ if (result == SCENARIO_PARSE_OK)
+ {
+ theScenarioActions.push_back( action );
+ }
+ else if (result != SCENARIO_PARSE_BLANK)
+ {
+ DEBUG_LOG(("SCENARIO: %s line %d: %s\n",
+ path.str(), lineNumber, ScenarioDrill_parseResultName( result )));
+ ++theScenarioActionsFailed;
+ }
+
+ at = end + 1;
+ }
+
+ delete [] contents;
+
+ std::stable_sort( theScenarioActions.begin(), theScenarioActions.end(), scenarioActionIsEarlier );
+
+ DEBUG_LOG(("SCENARIO: loaded '%s', %d actions, %d lines refused\n",
+ path.str(), (Int)theScenarioActions.size(), theScenarioActionsFailed));
+}
+
+// ------------------------------------------------------------------------------------------------
+// doing what the file asked for
+// ------------------------------------------------------------------------------------------------
+
+/** The file names a seat, the same number -side takes. ThePlayerList is not that list: it opens
+ with a neutral player and a civilian one, so slot 0 was player 2 in the first two-player run and
+ would be something else in another shape of game. assignSlotIndices recorded the real mapping
+ when the game started, so ask it rather than carrying an offset around. */
+static Player *findPlayerForSlot( Int slot )
+{
+ for( Int i = 0; i < ThePlayerList->getPlayerCount(); ++i )
+ {
+ if (ThePlayerList->getSlotIndex( i ) == slot)
+ return ThePlayerList->getNthPlayer( i );
+ }
+ return NULL;
+}
+
+static Bool selectorMatches( const AsciiString &selector, const Object *obj )
+{
+ if (selector == SCENARIO_SELECTOR_ALL)
+ return TRUE;
+
+ const ThingTemplate *tmpl = obj->getTemplate();
+ if (tmpl == NULL)
+ return FALSE;
+
+ return tmpl->getName() == selector;
+}
+
+/** 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 ))
+ continue;
+
+ group->add( obj );
+ ++taken;
+ }
+ return taken;
+}
+
+static Object *findFirstMatching( Player *player, const AsciiString &selector )
+{
+ for( Object *obj = TheGameLogic->getFirstObject(); obj; obj = obj->getNextObject() )
+ {
+ if (obj->getControllingPlayer() != player || obj->isEffectivelyDead())
+ continue;
+ if (selectorMatches( selector, obj ))
+ return obj;
+ }
+ return NULL;
+}
+
+/** The recipe the debug spawn path uses (GameLogic.cpp's unitTimings): a template's onCreate ran in
+ the constructor, but a unit that was never built still has to be told it is finished, or half
+ its modules never start. The team has to be activated too, or it counts as an empty team. */
+static Bool spawnOne( const ThingTemplate *tmpl, Team *team, const Coord3D *pos )
+{
+ Object *obj = TheThingFactory->newObject( tmpl, team );
+ if (obj == NULL)
+ return FALSE;
+
+ obj->setOrientation( 0 );
+ obj->setPosition( pos );
+
+ for( BehaviorModule **m = obj->getBehaviorModules(); *m; ++m )
+ {
+ CreateModuleInterface *create = (*m)->getCreate();
+ if (create == NULL)
+ continue;
+ create->onBuildComplete();
+ }
+
+ team->setActive();
+ TheAI->pathfinder()->addObjectToPathfindMap( obj );
+ return TRUE;
+}
+
+static Bool executeSpawn( const ScenarioAction &action, Player *player )
+{
+ const ThingTemplate *tmpl = TheThingFactory->findTemplate( action.selector, FALSE );
+ if (tmpl == NULL)
+ {
+ DEBUG_LOG(("SCENARIO: frame %d spawn: no template named '%s'\n",
+ action.frame, action.selector.str()));
+ return FALSE;
+ }
+
+ Team *team = player->getDefaultTeam();
+
+ // a square-ish block centred on the point the file named, so the author names where the army is
+ // rather than where its top left corner is
+ Int columns = 1;
+ while (columns * columns < action.count)
+ ++columns;
+ const Int rows = (action.count + columns - 1) / columns;
+ const Real halfWidth = (columns - 1) * action.spacing * 0.5f;
+ const Real halfHeight = (rows - 1) * action.spacing * 0.5f;
+
+ Int made = 0;
+ 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.z = TheTerrainLogic->getGroundHeight( pos.x, pos.y );
+
+ if (spawnOne( tmpl, team, &pos ))
+ ++made;
+ }
+
+ 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));
+
+ return made > 0;
+}
+
+static Bool executeOrder( const ScenarioAction &action, Player *player )
+{
+ AIGroup *group = TheAI->createGroup();
+ const Int taken = gatherIntoGroup( player, action.selector, group );
+ if (taken == 0)
+ {
+ TheAI->destroyGroup( group );
+ DEBUG_LOG(("SCENARIO: frame %d: slot %d owns nothing matching '%s'\n",
+ action.frame, action.slot, action.selector.str()));
+ return FALSE;
+ }
+
+ Bool ordered = TRUE;
+ switch (action.action)
+ {
+ 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
+ group->groupAttackMoveToPosition( &dest, SCENARIO_ATTACK_SHOTS, CMD_FROM_SCRIPT );
+
+ DEBUG_LOG(("SCENARIO: frame %d %s slot %d '%s' x%d to (%.0f,%.0f)\n",
+ action.frame,
+ (action.action == SCENARIO_ACTION_MOVE) ? "move" : "attackmove",
+ action.slot, action.selector.str(), taken, dest.x, dest.y));
+ break;
+ }
+
+ case SCENARIO_ACTION_ATTACK:
+ {
+ Player *targetPlayer = findPlayerForSlot( action.targetSlot );
+ Object *victim = (targetPlayer != NULL)
+ ? findFirstMatching( targetPlayer, action.targetSelector )
+ : NULL;
+ if (victim == NULL)
+ {
+ DEBUG_LOG(("SCENARIO: frame %d attack: slot %d owns nothing matching '%s'\n",
+ action.frame, action.targetSlot, action.targetSelector.str()));
+ ordered = FALSE;
+ break;
+ }
+
+ group->groupAttackObject( victim, SCENARIO_ATTACK_SHOTS, CMD_FROM_SCRIPT );
+ DEBUG_LOG(("SCENARIO: frame %d attack slot %d '%s' x%d -> slot %d '%s'\n",
+ action.frame, action.slot, action.selector.str(), taken,
+ action.targetSlot, action.targetSelector.str()));
+ break;
+ }
+
+ case SCENARIO_ACTION_STOP:
+ {
+ group->groupIdle( CMD_FROM_SCRIPT );
+ DEBUG_LOG(("SCENARIO: frame %d stop slot %d '%s' x%d\n",
+ action.frame, action.slot, action.selector.str(), taken));
+ break;
+ }
+
+ case SCENARIO_ACTION_SPAWN:
+ ordered = FALSE; // handled before the group is built
+ break;
+ }
+
+ TheAI->destroyGroup( group );
+ return ordered;
+}
+
+static Bool executeAction( const ScenarioAction &action )
+{
+ Player *player = findPlayerForSlot( action.slot );
+ if (player == NULL)
+ {
+ DEBUG_LOG(("SCENARIO: frame %d: nobody is sitting in slot %d\n", action.frame, action.slot));
+ return FALSE;
+ }
+
+ if (action.action == SCENARIO_ACTION_SPAWN)
+ return executeSpawn( action, player );
+
+ return executeOrder( action, player );
+}
+
+// ------------------------------------------------------------------------------------------------
+// the tick
+// ------------------------------------------------------------------------------------------------
+
+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())
+ return;
+
+ const UnsignedInt now = TheGameLogic->getFrame();
+
+ // a restart runs the clock back, and the file should play again rather than sit finished
+ if (now < theScenarioLastFrame)
+ resetScenario();
+ theScenarioLastFrame = now;
+
+ if (!theScenarioLoaded)
+ loadScenario();
+
+ while (theScenarioCursor < (Int)theScenarioActions.size()
+ && theScenarioActions[ theScenarioCursor ].frame <= now)
+ {
+ if (executeAction( theScenarioActions[ theScenarioCursor ] ))
+ ++theScenarioActionsRun;
+ else
+ ++theScenarioActionsFailed;
+ ++theScenarioCursor;
+ }
+}
+
+const char *ScenarioDrill_report( void )
+{
+ sprintf( theScenarioReport, "%d actions, %d ran, %d refused, %d units spawned",
+ (Int)theScenarioActions.size(), theScenarioActionsRun,
+ theScenarioActionsFailed, theScenarioUnitsSpawned );
+ return theScenarioReport;
+}
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index f6db75bc4..208f2a64f 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -42,6 +42,7 @@
#include "GameNetwork/LinkSimulation.h"
#include "Common/Energy.h"
#include "Common/RandomValue.h"
+#include "GameLogic/ScenarioDrill.h"
#include "GameLogic/LogicRandomValue.h"
#include "GameClient/ClientRandomValue.h"
#include "Common/ThingTemplate.h"
@@ -10145,3 +10146,104 @@ TEST(the_superweapon_rule_is_a_mode_with_one_exception)
delete TheWritableGlobalData;
TheWritableGlobalData = saved;
}
+
+/* -scenario's line parser.
+ *
+ * A scenario file that gets half-read still plays a match and still writes a frame time table, so
+ * the run produces numbers that answer a different question than the one asked. Every way a line
+ * can be wrong therefore has to come back named. atoi is the specific trap the parser exists to
+ * avoid: it reads "banana" as 0, 0 is a real frame number, and a typo in one field would put the
+ * whole file on the first frame.
+ */
+TEST(scenario_parses_a_spawn_line)
+{
+ ScenarioAction action;
+
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "0 spawn 2 GLAInfantryAngryMobNexus 8 1200 900", &action ),
+ (Int)SCENARIO_PARSE_OK );
+ CHECK_EQ( (Int)action.frame, 0 );
+ CHECK_EQ( (Int)action.action, (Int)SCENARIO_ACTION_SPAWN );
+ CHECK_EQ( action.slot, 2 );
+ CHECK_STR( action.selector.str(), "GLAInfantryAngryMobNexus" );
+ CHECK_EQ( action.count, 8 );
+ CHECK_NEAR( action.at.x, 1200.0f, 0.01f );
+ CHECK_NEAR( action.at.y, 900.0f, 0.01f );
+
+ // spacing is optional, and the default has to be a real gap rather than zero
+ CHECK( action.spacing > 0.0f );
+
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "30 spawn 1 AmericaVehicleHumvee 4 100 200 55", &action ),
+ (Int)SCENARIO_PARSE_OK );
+ CHECK_EQ( (Int)action.frame, 30 );
+ CHECK_NEAR( action.spacing, 55.0f, 0.01f );
+}
+
+TEST(scenario_parses_the_order_lines)
+{
+ ScenarioAction action;
+
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "120 move 2 * 800 600", &action ), (Int)SCENARIO_PARSE_OK );
+ CHECK_EQ( (Int)action.action, (Int)SCENARIO_ACTION_MOVE );
+ CHECK_STR( action.selector.str(), "*" );
+ CHECK_NEAR( action.at.x, 800.0f, 0.01f );
+ CHECK_NEAR( action.at.y, 600.0f, 0.01f );
+
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "240 attackmove 2 GLAInfantryAngryMobNexus 2400 1500", &action ),
+ (Int)SCENARIO_PARSE_OK );
+ CHECK_EQ( (Int)action.action, (Int)SCENARIO_ACTION_ATTACKMOVE );
+ CHECK_NEAR( action.at.x, 2400.0f, 0.01f );
+
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "300 attack 2 * 1 AmericaCommandCenter", &action ),
+ (Int)SCENARIO_PARSE_OK );
+ CHECK_EQ( (Int)action.action, (Int)SCENARIO_ACTION_ATTACK );
+ CHECK_EQ( action.targetSlot, 1 );
+ CHECK_STR( action.targetSelector.str(), "AmericaCommandCenter" );
+
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "900 stop 2 *", &action ), (Int)SCENARIO_PARSE_OK );
+ CHECK_EQ( (Int)action.action, (Int)SCENARIO_ACTION_STOP );
+}
+
+TEST(scenario_ignores_comments_and_blank_lines)
+{
+ ScenarioAction action;
+
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "", &action ), (Int)SCENARIO_PARSE_BLANK );
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( " \t ", &action ), (Int)SCENARIO_PARSE_BLANK );
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "# eight mobs on the ridge", &action ), (Int)SCENARIO_PARSE_BLANK );
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( " # indented comment", &action ), (Int)SCENARIO_PARSE_BLANK );
+
+ // a text-mode read still leaves the carriage return on a CRLF file
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "900 stop 2 *\r", &action ), (Int)SCENARIO_PARSE_OK );
+
+ // and a comment after a real action does not eat the action
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "900 stop 2 * # everybody halt", &action ),
+ (Int)SCENARIO_PARSE_OK );
+ CHECK_EQ( (Int)action.action, (Int)SCENARIO_ACTION_STOP );
+ CHECK_STR( action.selector.str(), "*" );
+}
+
+TEST(scenario_refuses_a_line_it_cannot_read)
+{
+ ScenarioAction action;
+
+ // the atoi trap: none of these may come back as frame 0
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "banana spawn 2 X 1 0 0", &action ), (Int)SCENARIO_PARSE_BAD_FRAME );
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "12x spawn 2 X 1 0 0", &action ), (Int)SCENARIO_PARSE_BAD_FRAME );
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "-5 stop 2 *", &action ), (Int)SCENARIO_PARSE_BAD_FRAME );
+
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "0 teleport 2 *", &action ), (Int)SCENARIO_PARSE_BAD_ACTION );
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "0 stop two *", &action ), (Int)SCENARIO_PARSE_BAD_SLOT );
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "0 attack 2 * nobody Thing", &action ), (Int)SCENARIO_PARSE_BAD_SLOT );
+
+ // a count of zero spawns nothing, which is a typo rather than an instruction
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "0 spawn 2 X 0 100 100", &action ), (Int)SCENARIO_PARSE_BAD_COUNT );
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "0 spawn 2 X lots 100 100", &action ), (Int)SCENARIO_PARSE_BAD_COUNT );
+
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "0 stop", &action ), (Int)SCENARIO_PARSE_MISSING_ARGS );
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "0 move 2 *", &action ), (Int)SCENARIO_PARSE_MISSING_ARGS );
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "0 move 2 * 100", &action ), (Int)SCENARIO_PARSE_MISSING_ARGS );
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "0 spawn 2 X 4 100", &action ), (Int)SCENARIO_PARSE_MISSING_ARGS );
+
+ // and every refusal has something to say for itself in the log
+ CHECK_STR( ScenarioDrill_parseResultName( SCENARIO_PARSE_BAD_FRAME ), "frame is not a whole number" );
+}