Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
feat(gameengine): balance file over ea's data, defences earn their price
Olcay Seygan073c5ad58970
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b68cfcd4a..166223c64 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -357,6 +357,14 @@ found and fixed — EA's own, not port damage.**fires five rockets a reload, one after another. Rifles keep their own turns and never wait behind therockets.+## A defence earns its price++- A tower used to be cheaper to kill than to build. We put every stock defence against 22 kinds of attacker, 528 fights a round, and in Zero Hour as shipped two Battlemasters took a Gattling Cannon and lost nothing, and tanks paid 89 cents in wrecks for every dollar of Patriot they destroyed. Tank shells now do half damage to the Patriot, the Gattling Cannon, the Stinger Site and the Fire Base. Taking one with tanks now costs you more than the tower cost them: a Patriot $1.23 in tanks per dollar, a Stinger Site $1.09, a Fire Base $1.26.+- The Gattling Cannon costs 1000, the same as a Patriot. It is still the tower for infantry and aircraft, and it makes a rifle rush pay $1.72 for every dollar of it.+- Bunkers and Tunnel Networks stand half as long again, 1500 instead of 1000. One of them in a game saved before this change comes back at full health when you load it.+- Artillery is untouched. A Tomahawk, an Inferno Cannon, a Nuke Cannon, a Scud Launcher or a Rocket Buggy outranges every tower in the game and still takes one without losing a thing. Bring them when a player digs in.+- Replays recorded before this change play out differently.+## Weapons and units that were quietly wrong- A bunker buster shot down on the way in no longer clears out the building it was aimed at. It emptied the bunker from wherever it happened to be destroyed - a Point Defence Laser did not save you, it just moved the explosion.diff --git a/GeneralsMD/Code/Data/INI/BalanceReforged.ini b/GeneralsMD/Code/Data/INI/BalanceReforged.ininew file mode 100644index 000000000..6812ba8b7--- /dev/null+++ b/GeneralsMD/Code/Data/INI/BalanceReforged.ini@@ -0,0 +1,218 @@+; Zero Hour Reforged balance, loaded after every Object, Weapon and Armor file.+;+; An Object or Weapon block here edits the template EA's files built: the fields it names are+; written over, the rest stay as EA wrote them. A module is changed with ReplaceModule and a new tag.+; An Armor block replaces that armor whole, so it carries every line.+;+; This file lands in the multiplayer INI checksum.+;+; Defender's advantage, 2026-09-24. Measured with 528 staged sieges a round, every stock defence+; against 22 attackers at one and two times its price from two directions (Tools/Balance/siege.py).+; EA's numbers let a main battle tank take a defence for less than the defence cost:+; tanks lost 0.27 of a Gattling Cannon's price killing it, 0.75 of a Stinger Site's, 0.89 of a+; Patriot's. Tank shells now do half damage to the three defence armors, which puts every one of+; them at 1.1 to 1.3 against tanks. Artillery is untouched and still takes any defence for nothing.++; ---- tank shells do half damage to base defences ------------------------------------------------++Armor BaseDefenseArmor+ Armor = DEFAULT 100%+ Armor = Surrender 0%+ Armor = SMALL_ARMS 50%+ Armor = GATTLING 25%+ Armor = COMANCHE_VULCAN 50%+ Armor = RADIATION 0%+ Armor = MICROWAVE 0%+ Armor = SNIPER 0%+ Armor = POISON 1%+ Armor = MELEE 0%+ Armor = LASER 0%+ Armor = HAZARD_CLEANUP 0%+ Armor = INFANTRY_MISSILE 25%+ Armor = PARTICLE_BEAM 200%+ Armor = KILL_PILOT 0%+ Armor = SURRENDER 0%+ Armor = AURORA_BOMB 200%+ Armor = STEALTHJET_MISSILES 250%+ Armor = JET_MISSILES 25%+ Armor = LAND_MINE 0%+ Armor = FLAME 50%+ Armor = SUBDUAL_MISSILE 0%+ Armor = SUBDUAL_VEHICLE 0%+ Armor = SUBDUAL_BUILDING 100%+ Armor = ARMOR_PIERCING 50% ; EA: 100%+End++Armor StingerSiteArmor+ Armor = DEFAULT 100%+ Armor = SMALL_ARMS 50%+ Armor = GATTLING 30%+ Armor = COMANCHE_VULCAN 50%+ Armor = RADIATION 0%+ Armor = MICROWAVE 1%+ Armor = SNIPER 100% ; must stay above zero or snipers cannot reach the soldiers+ Armor = POISON 100% ; the same for the toxin tractor+ Armor = SURRENDER 0%+ Armor = MELEE 0%+ Armor = LASER 0%+ Armor = HAZARD_CLEANUP 0%+ Armor = INFANTRY_MISSILE 25%+ Armor = PARTICLE_BEAM 200%+ Armor = KILL_PILOT 0%+ Armor = AURORA_BOMB 200%+ Armor = STEALTHJET_MISSILES 250%+ Armor = JET_MISSILES 40%+ Armor = LAND_MINE 0%+ Armor = FLAME 50%+ Armor = SUBDUAL_MISSILE 0%+ Armor = SUBDUAL_VEHICLE 0%+ Armor = SUBDUAL_BUILDING 100%+ Armor = ARMOR_PIERCING 50% ; EA: 100%+End++Armor FireBaseArmor+ Armor = DEFAULT 100%+ Armor = SMALL_ARMS 50%+ Armor = GATTLING 30%+ Armor = COMANCHE_VULCAN 50%+ Armor = RADIATION 0%+ Armor = MICROWAVE 0%+ Armor = SNIPER 100%+ Armor = POISON 0%+ Armor = SURRENDER 0%+ Armor = MELEE 0%+ Armor = LASER 0%+ Armor = HAZARD_CLEANUP 0%+ Armor = INFANTRY_MISSILE 25%+ Armor = PARTICLE_BEAM 200%+ Armor = KILL_PILOT 0%+ Armor = AURORA_BOMB 200%+ Armor = STEALTHJET_MISSILES 250%+ Armor = JET_MISSILES 40%+ Armor = LAND_MINE 0%+ Armor = FLAME 50%+ Armor = SUBDUAL_MISSILE 0%+ Armor = SUBDUAL_VEHICLE 0%+ Armor = SUBDUAL_BUILDING 100%+ Armor = ARMOR_PIERCING 50% ; EA: 100%+End++; ---- the Gattling Cannon costs what a Patriot costs ------------------------------------------------+; It is China's anti-infantry and anti-air tower and stays that: at 1000 it still loses to tanks+; (0.61 of its price), and wins against infantry at 1.72.++Object ChinaGattlingCannon+ BuildCost = 1000 ; EA: 1200+End++Object Infa_ChinaGattlingCannon+ BuildCost = 1000+End++Object Nuke_ChinaGattlingCannon+ BuildCost = 1000+End++Object Tank_ChinaGattlingCannon+ BuildCost = 1000+End++; ---- the Bunker and the Tunnel Network stand half as long again ------------------------------------+; Both wear StructureArmor, which every building shares, so they get health rather than armor.+; Tunnel against tanks went from 1.09 to 1.27, the Bunker against light vehicles from 0.64 to 0.91.++Object ChinaBunker+ ReplaceModule ModuleTag_05+ Body = StructureBody ModuleTag_05_Reforged+ MaxHealth = 1500.0 ; EA: 1000+ InitialHealth = 1500.0+ SubdualDamageCap = 1800+ SubdualDamageHealRate = 500+ SubdualDamageHealAmount = 100+ End+ End+End++Object Infa_ChinaBunker+ ReplaceModule ModuleTag_05+ Body = StructureBody ModuleTag_05_Reforged+ MaxHealth = 1500.0+ InitialHealth = 1500.0+ SubdualDamageCap = 1800+ SubdualDamageHealRate = 500+ SubdualDamageHealAmount = 100+ End+ End+End++Object Nuke_ChinaBunker+ ReplaceModule ModuleTag_05+ Body = StructureBody ModuleTag_05_Reforged+ MaxHealth = 1500.0+ InitialHealth = 1500.0+ SubdualDamageCap = 1800+ SubdualDamageHealRate = 500+ SubdualDamageHealAmount = 100+ End+ End+End++Object Tank_ChinaBunker+ ReplaceModule ModuleTag_05+ Body = StructureBody ModuleTag_05_Reforged+ MaxHealth = 1500.0+ InitialHealth = 1500.0+ SubdualDamageCap = 1800+ SubdualDamageHealRate = 500+ SubdualDamageHealAmount = 100+ End+ End+End++Object GLATunnelNetwork+ ReplaceModule ModuleTag_04+ Body = StructureBody ModuleTag_04_Reforged+ MaxHealth = 1500.0 ; EA: 1000+ InitialHealth = 1500.0+ SubdualDamageCap = 1800+ SubdualDamageHealRate = 500+ SubdualDamageHealAmount = 100+ End+ End+End++Object Chem_GLATunnelNetwork+ ReplaceModule ModuleTag_04+ Body = StructureBody ModuleTag_04_Reforged+ MaxHealth = 1500.0+ InitialHealth = 1500.0+ SubdualDamageCap = 1800+ SubdualDamageHealRate = 500+ SubdualDamageHealAmount = 100+ End+ End+End++Object Demo_GLATunnelNetwork+ ReplaceModule ModuleTag_04+ Body = StructureBody ModuleTag_04_Reforged+ MaxHealth = 1500.0+ InitialHealth = 1500.0+ SubdualDamageCap = 1800+ SubdualDamageHealRate = 500+ SubdualDamageHealAmount = 100+ End+ End+End++Object Slth_GLATunnelNetwork+ ReplaceModule ModuleTag_04+ Body = StructureBody ModuleTag_04_Reforged+ MaxHealth = 1500.0+ InitialHealth = 1500.0+ SubdualDamageCap = 1800+ SubdualDamageHealRate = 500+ SubdualDamageHealAmount = 100+ End+ End+Enddiff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.hindex 08701d262..2092ce293 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h@@ -69,7 +69,8 @@ enum ScenarioActionTypeSCENARIO_ACTION_PLAYERMOVE, ///< playermove <slot> <selector> <position>; a right click, not a script orderSCENARIO_ACTION_POWER, ///< power <slot> <building> <position> [powerName]; fire its special powers (or the one named) there now, charged or notSCENARIO_ACTION_PLAYERATTACKMOVE, ///< playerattackmove <slot> <selector> <position>; the player's attack move, not a script's- SCENARIO_ACTION_PRODUCE ///< produce <slot> <building> <template> <count>; queue that many in its first matching building+ SCENARIO_ACTION_PRODUCE, ///< produce <slot> <building> <template> <count>; queue that many in its first matching building+ SCENARIO_ACTION_TALLY ///< tally <slot> <selector>; log how many are alive, their health and what they cost};/// ScenarioAction::atStart when the position is plain numbersdiff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cppindex 044703926..452bf1178 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp@@ -935,6 +935,11 @@ void GameEngine::init( int argc, char *argv[] )initSubsystem(TheThingFactory,"TheThingFactory", createThingFactory(), &xferCRC, "Data\\INI\\Default\\Object.ini", NULL, "Data\\INI\\Object");+ /* The fork's balance, written over EA's numbers after every object, weapon and armor exists.+ MULTIFILE edits a template in place and leaves every field the file does not name as EA+ wrote it, so the file holds the changes and nothing else; an Armor block still replaces+ that armor whole. It is in the INI CRC like the files it edits. */+ ini.load( AsciiString( "Data\\INI\\BalanceReforged.ini" ), INI_LOAD_MULTIFILE, &xferCRC );#ifdef DUMP_PERF_STATS///////////////////////////////////////////////////////////////////////////GetPrecisionTimer(&endTime64);//////////////////////////////////////////////////////////////////diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingFactory.cppindex d6fc455aa..bb867e4b8 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingFactory.cpp@@ -388,7 +388,14 @@ AsciiString TheThingTemplateBeingParsedName;// find existing item if presentThingTemplate *thingTemplate = TheThingFactory->findTemplateInternal( name, FALSE );- if( !thingTemplate )+ if( !thingTemplate && ini->getLoadType() == INI_LOAD_MULTIFILE )+ {+ // a patch names an object EA's files built; a name that finds nothing is a typo, and a new+ // template made from it would change no unit and still land in the INI CRC+ DEBUG_CRASH(( "[LINE: %d in '%s'] %s patches an object that does not exist", ini->getLineNum(), ini->getFilename().str(), name.str() ));+ throw INI_INVALID_DATA;+ }+ else if( !thingTemplate ){// no item is present, create a new onethingTemplate = TheThingFactory->newTemplate( name );@@ -399,6 +406,11 @@ AsciiString TheThingTemplateBeingParsedName;thingTemplate->markAsOverride();}}+ else if( ini->getLoadType() == INI_LOAD_MULTIFILE )+ {+ // BalanceReforged.ini: the fields it names are written over the template EA's file built, and+ // everything it does not name stays as it was+ }else if( ini->getLoadType() != INI_LOAD_CREATE_OVERRIDES ){//Holy crap, this sucks to debug!!!diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Armor.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Armor.cppindex e038fca95..c7df6d0b5 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Armor.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Armor.cpp@@ -140,6 +140,12 @@ const ArmorTemplate* ArmorStore::findArmorTemplate(AsciiString name) constconst char *c = ini->getNextToken();NameKeyType key = TheNameKeyGenerator->nameToKey(c);+ if (ini->getLoadType() == INI_LOAD_MULTIFILE && TheArmorStore->m_armorTemplates.find(key) == TheArmorStore->m_armorTemplates.end())+ {+ // BalanceReforged.ini rewrites armors objects already wear; a new name would reach nothing+ DEBUG_CRASH(("Armor '%s' is patched but was never defined", c));+ throw INI_INVALID_DATA;+ }ArmorTemplate& armorTmpl = TheArmorStore->m_armorTemplates[key];armorTmpl.clear();ini->initFromINI(&armorTmpl, myFieldParse);diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cppindex 77c5b5e07..1885a7b26 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp@@ -1805,18 +1805,27 @@ void WeaponStore::postProcessLoad(){if (ini->getLoadType() == INI_LOAD_CREATE_OVERRIDES)weapon = TheWeaponStore->newOverride(weapon);- else+ else if (ini->getLoadType() == INI_LOAD_MULTIFILE)+ {+ // BalanceReforged.ini: edit the weapon in place, the fields it does not name stay as they were+ }+ else{DEBUG_CRASH(("Weapon '%s' already exists, but OVERRIDE not specified", c));return;}}+ else if (ini->getLoadType() == INI_LOAD_MULTIFILE)+ {+ DEBUG_CRASH(("Weapon '%s' is patched but was never defined", c));+ throw INI_INVALID_DATA;+ }else{// no item is present, create a new oneweapon = TheWeaponStore->newWeaponTemplate(name);- }+ }// parse the ini weapon definitionini->initFromINI(weapon, weapon->getFieldParse());diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cppindex fb200d07a..d8e26db39 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp@@ -179,6 +179,8 @@ static Bool parseActionType( const AsciiString &token, ScenarioActionType *actio*action = SCENARIO_ACTION_POWER;else if (token == "produce")*action = SCENARIO_ACTION_PRODUCE;+ else if (token == "tally")+ *action = SCENARIO_ACTION_TALLY;elsereturn FALSE;@@ -261,6 +263,7 @@ static Int tokensNeededFor( ScenarioActionType action )case SCENARIO_ACTION_ENTER: return SCENARIO_TOKENS_ATTACK;case SCENARIO_ACTION_PRODUCE: return SCENARIO_TOKENS_ATTACK;case SCENARIO_ACTION_STOP: return SCENARIO_TOKENS_STOP;+ case SCENARIO_ACTION_TALLY: return SCENARIO_TOKENS_STOP;case SCENARIO_ACTION_ARRIVE: return SCENARIO_TOKENS_ARRIVE;}return SCENARIO_TOKENS_STOP;@@ -357,6 +360,7 @@ ScenarioParseResult ScenarioDrill_parseLine( const char *line, ScenarioAction *a}case SCENARIO_ACTION_STOP:+ case SCENARIO_ACTION_TALLY:break;}@@ -544,6 +548,11 @@ static Bool selectorMatches( const AsciiString &selector, const Object *obj )if (tmpl == NULL)return FALSE;+ // "GLAVehicleTechnical*": a Technical spawns as one of its chassis templates, never under its own name+ const Int length = selector.getLength();+ if (length > 1 && selector.getCharAt( length - 1 ) == '*')+ return strncmp( tmpl->getName().str(), selector.str(), length - 1 ) == 0;+return tmpl->getName() == selector;}@@ -957,6 +966,34 @@ static Bool executeProduce( const ScenarioAction &action, Player *player )return queued > 0;}+/** How much of this seat's matching stock is still standing: the count, the health left against the+ health they started with, and what the living ones cost. Structures count too, so a fight between+ an army and a defence reads as money lost on each side. */+static Bool executeTally( const ScenarioAction &action, Player *player )+{+ Int alive = 0;+ Int inside = 0;+ Real health = 0.0f;+ Real maxHealth = 0.0f;+ Int worth = 0;+ for( Object *obj = TheGameLogic->getFirstObject(); obj; obj = obj->getNextObject() )+ {+ if (obj->getControllingPlayer() != player || obj->isEffectivelyDead() || !selectorMatches( action.selector, obj ))+ continue;++ ++alive;+ if (obj->getContainedBy() != NULL)+ ++inside;+ health += obj->getBodyModule()->getHealth();+ maxHealth += obj->getBodyModule()->getMaxHealth();+ worth += obj->getTemplate()->friend_getBuildCost();+ }++ DEBUG_LOG(("HEADLESS TALLY: frame %d slot %d '%s': %d alive, health %.0f of %.0f, worth %d, %d inside\n",+ action.frame, action.slot, action.selector.str(), alive, health, maxHealth, worth, inside));+ return TRUE;+}+static Bool executeOrder( const ScenarioAction &action, Player *player, const Coord3D &dest ){AIGroup *group = TheAI->createGroup();@@ -1037,6 +1074,7 @@ static Bool executeOrder( const ScenarioAction &action, Player *player, const Cocase SCENARIO_ACTION_PARTICLES:case SCENARIO_ACTION_POWER:case SCENARIO_ACTION_PRODUCE:+ case SCENARIO_ACTION_TALLY:ordered = FALSE; // handled before the group is builtbreak;}@@ -1073,6 +1111,9 @@ Bool ScenarioDrill_execute( const ScenarioAction &action )if (action.action == SCENARIO_ACTION_PRODUCE)return executeProduce( action, player );+ if (action.action == SCENARIO_ACTION_TALLY)+ return executeTally( action, player );+return executeOrder( action, player, position );}diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex b1a058000..eab3583d7 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -523,6 +523,58 @@ TEST(ini_unknown_field_is_skipped_only_when_asked)remove( TEST_INI );}+/* Data\INI\BalanceReforged.ini is loaded INI_LOAD_MULTIFILE after Weapon.ini: a Weapon block in it+ edits EA's weapon in place. Before this load type was honoured, a second definition of a weapon+ was refused and returned early, so the whole balance file would have loaded and changed nothing. */+TEST(balance_patch_edits_a_weapon_in_place)+{+ CHECK( bootOnce() );++ if( TheWeaponStore == NULL )+ TheWeaponStore = NEW WeaponStore;++ writeFile( TEST_INI,+ "Weapon BalancePatchProbeGun\r\n"+ " PrimaryDamage = 60.0\r\n"+ " AttackRange = 150.0\r\n"+ " DelayBetweenShots = 2000\r\n"+ "End\r\n" );+ CHECK( loadIni( TEST_INI ) );++ writeFile( TEST_INI,+ "Weapon BalancePatchProbeGun\r\n"+ " PrimaryDamage = 45.0\r\n"+ "End\r\n" );+ INI ini;+ ini.load( AsciiString( TEST_INI ), INI_LOAD_MULTIFILE, NULL );++ const WeaponTemplate *gun = TheWeaponStore->findWeaponTemplate( "BalancePatchProbeGun" );+ CHECK( gun != NULL );+ WeaponBonus noBonus;+ CHECK_NEAR( gun->getPrimaryDamage( noBonus ), 45.0f, 0.01f );+ CHECK_NEAR( gun->getUnmodifiedAttackRange(), 150.0f, 0.01f );++ /* a patch that names a weapon nobody defined is a typo, and has to stop the load */+ writeFile( TEST_INI,+ "Weapon BalancePatchProbeGunTypo\r\n"+ " PrimaryDamage = 45.0\r\n"+ "End\r\n" );+ Bool threw = FALSE;+ try+ {+ INI typo;+ typo.load( AsciiString( TEST_INI ), INI_LOAD_MULTIFILE, NULL );+ }+ catch( ... )+ {+ threw = TRUE;+ }+ CHECK( threw );+ CHECK( TheWeaponStore->findWeaponTemplate( "BalancePatchProbeGunTypo" ) == NULL );++ remove( TEST_INI );+}+/* Data\INI\FXListReforged.ini is the fork's own explosion light: 89 of EA's FXLists, each repeatedwhole with one LightPulse added. Whole, because FXListStore::parseFXListDefinition clears anentry before re-reading it - a half-copied block does not add a light, it deletes an explosion.@@ -13151,6 +13203,11 @@ TEST(scenario_parses_the_order_lines)CHECK_EQ( (Int)ScenarioDrill_parseLine( "900 stop 2 *", &action ), (Int)SCENARIO_PARSE_OK );CHECK_EQ( (Int)action.action, (Int)SCENARIO_ACTION_STOP );+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "1800 tally 1 ChinaGattlingCannon", &action ), (Int)SCENARIO_PARSE_OK );+ CHECK_EQ( (Int)action.action, (Int)SCENARIO_ACTION_TALLY );+ CHECK_STR( action.selector.str(), "ChinaGattlingCannon" );+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "1800 tally 1", &action ), (Int)SCENARIO_PARSE_MISSING_ARGS );+CHECK_EQ( (Int)ScenarioDrill_parseLine( "700 power 1 GLAScudStorm start0:0:300", &action ),(Int)SCENARIO_PARSE_OK );CHECK_EQ( (Int)action.action, (Int)SCENARIO_ACTION_POWER );diff --git a/Tools/Balance/compare.py b/Tools/Balance/compare.pynew file mode 100644index 000000000..b8d93a3ab--- /dev/null+++ b/Tools/Balance/compare.py@@ -0,0 +1,59 @@+"""Side by side: what attacking a defence cost in two siege runs.++ python compare.py <before tag> <after tag>++Per defence and attacker class, over both budgets: how often the defence stood, and the attacker's+money lost for each dollar of defence (the defence's own price in that run, garrison included).+"""++import json+import sys+from collections import defaultdict++from siege import OUT_DIR+CLASSES = {+ "tank": ("AmericaTankCrusader", "AmericaTankPaladin", "ChinaTankBattleMaster", "ChinaTankOverlord",+ "ChinaTankDragon", "GLATankScorpion", "GLATankMarauder"),+ "light vehicle": ("AmericaVehicleHumvee", "ChinaTankGattling", "GLAVehicleTechnical", "GLAVehicleQuadCannon",+ "GLAVehicleRocketBuggy"),+ "infantry": ("AmericaInfantryRanger", "AmericaInfantryMissileDefender", "ChinaInfantryRedguard",+ "ChinaInfantryTankHunter", "GLAInfantryRebel", "GLAInfantryTunnelDefender"),+ "artillery": ("AmericaVehicleTomahawk", "ChinaVehicleInfernoCannon", "ChinaVehicleNukeLauncher",+ "GLAVehicleScudLauncher"),+}+CLASS_OF = {unit: name for name, units in CLASSES.items() for unit in units}+++def load(tag: str) -> list[dict]:+ return [row for row in json.loads((OUT_DIR / (tag + ".json")).read_text()) if "error" not in row]+++def price(row: dict) -> int:+ garrison = row["defencePrice"] - {"ChinaBunker": 400, "AmericaFireBase": 1000}.get(row["defence"], row["defencePrice"])+ return row.get("defenceWorth", row["defencePrice"]) + garrison+++def summarise(rows: list[dict]) -> dict:+ cells = defaultdict(lambda: {"runs": 0, "stood": 0, "lost": 0, "price": 0})+ for row in rows:+ for key in ((row["defence"], CLASS_OF[row["attacker"]]), (row["defence"], "all")):+ cell = cells[key]+ cell["runs"] += 1+ cell["stood"] += 1 if row["defenceStanding"] else 0+ cell["lost"] += row["attackerLost"]+ cell["price"] += price(row)+ return cells+++def main() -> int:+ before, after = summarise(load(sys.argv[1])), summarise(load(sys.argv[2]))+ print("%-22s %-14s %16s %16s" % ("defence", "attackers", sys.argv[1] + " stood $/$", sys.argv[2] + " stood $/$"))+ for key in sorted(before):+ b, a = before[key], after.get(key)+ cell = lambda c: "%2d/%-2d %5.2f" % (c["stood"], c["runs"], c["lost"] / c["price"]) if c else "-"+ print("%-22s %-14s %16s %16s" % (key[0], key[1], cell(b), cell(a)))+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/Tools/Balance/duel.py b/Tools/Balance/duel.pynew file mode 100644index 000000000..3d8dad7c9--- /dev/null+++ b/Tools/Balance/duel.py@@ -0,0 +1,98 @@+"""Equal-money armies of two unit types meet on open ground; the money each side has left is the answer.++Every cross-faction pair fights twice with the two starting points swapped: on generated map 1 the+side starting at 1000,1150 won 118 of 183 decided fights, so one orientation measures the ground.+duel_report.py averages the two.++ python duel.py <exe name in Run> <tag> [budget] [pair filter]+"""++import concurrent.futures+import itertools+import json+import re+import subprocess+import sys++import siege++BUDGET = 4800+MAX_FRAMES = 3000+TALLY_FRAME = 2950+SPAWN_FRAME = 30+ATTACK_FRAME = 60+LEFT_AT = (760, 800)+RIGHT_AT = (1000, 1150)+MEET_AT = (880, 975)++# the direct-fire ground core each side builds most of+UNITS = {+ "AmericaTankCrusader": 900, "AmericaTankPaladin": 1100, "AmericaVehicleHumvee": 700,+ "AmericaInfantryRanger": 225, "AmericaInfantryMissileDefender": 300,+ "ChinaTankBattleMaster": 800, "ChinaTankOverlord": 2000, "ChinaTankGattling": 800, "ChinaTankDragon": 800,+ "ChinaInfantryRedguard": 300, "ChinaInfantryTankHunter": 300,+ "GLATankScorpion": 600, "GLATankMarauder": 800, "GLAVehicleTechnical": 500, "GLAInfantryRebel": 150,+ "GLAInfantryTunnelDefender": 300, "GLAVehicleQuadCannon": 700,+}+++def run_one(exe: str, tag: str, index: int, left: str, right: str, budget: int, swapped: bool) -> dict:+ left_at, right_at = (RIGHT_AT, LEFT_AT) if swapped else (LEFT_AT, RIGHT_AT)+ left_count = max(1, round(budget / UNITS[left]))+ right_count = max(1, round(budget / UNITS[right]))+ name = "dl%s%03d" % (tag, index)+ lines = [+ "%d spawn 0 %s %d %d %d 35" % (SPAWN_FRAME, left, left_count, *left_at),+ "%d spawn 1 %s %d %d %d 35" % (SPAWN_FRAME, right, right_count, *right_at),+ "%d attackmove 0 %s %d %d" % (ATTACK_FRAME, siege.selector(left), *right_at),+ "%d attackmove 1 %s %d %d" % (ATTACK_FRAME, siege.selector(right), *left_at),+ ]+ for frame in (ATTACK_FRAME, TALLY_FRAME):+ lines.append("%d tally 0 %s" % (frame, siege.selector(left)))+ lines.append("%d tally 1 %s" % (frame, siege.selector(right)))+ scenario = siege.SCENARIO_DIR / (name + ".txt")+ scenario.write_text("\n".join(lines) + "\n", encoding="ascii")+ log = siege.RUN_DIR / (name + "_DebugLogFile.txt")+ log.unlink(missing_ok=True)+ arguments = [str(siege.RUN_DIR / exe), "-headless", "-quickstart", "-noshellmap", "-observer", "-multiInstance",+ "-noFPSLimit", "-randommap", "1", "2", "small", "-autoskirmish", "2", "-takeover",+ "-side", "0", "FactionAmerica", "-side", "1", "FactionChina", "-seed", "1",+ "-maxframes", str(MAX_FRAMES), "-scenario", name, "-logPrefix", name + "_"]+ process = subprocess.Popen(arguments, cwd=siege.RUN_DIR, creationflags=subprocess.ABOVE_NORMAL_PRIORITY_CLASS)+ try:+ process.wait(timeout=siege.TIMEOUT_SECONDS)+ except subprocess.TimeoutExpired:+ process.kill()+ scenario.unlink()+ tallies = {}+ for match in siege.TALLY.finditer(log.read_text(encoding="latin-1", errors="replace")):+ # counted in units, not worth: a Technical's chassis templates carry no build cost+ slot = int(match.group(2))+ tallies[(int(match.group(1)), slot)] = int(match.group(4)) * UNITS[left if slot == 0 else right]+ log.unlink()+ return {"left": left, "right": right, "swapped": swapped, "leftSpent": tallies.get((ATTACK_FRAME, 0)),+ "rightSpent": tallies.get((ATTACK_FRAME, 1)), "leftLeft": tallies.get((TALLY_FRAME, 0)),+ "rightLeft": tallies.get((TALLY_FRAME, 1))}+++def main() -> int:+ exe, tag = sys.argv[1], sys.argv[2]+ budget = int(sys.argv[3]) if len(sys.argv) > 3 else BUDGET+ faction = lambda name: re.match(r"America|China|GLA", name).group(0)+ pairs = [(a, b, swapped) for a, b in itertools.combinations(UNITS, 2) if faction(a) != faction(b)+ for swapped in (False, True)]+ if len(sys.argv) > 4:+ pairs = [pair for pair in pairs if re.search(sys.argv[4], pair[0] + " " + pair[1])]+ results = []+ with concurrent.futures.ThreadPoolExecutor(siege.PARALLEL_RUNS) as pool:+ for row in pool.map(lambda item: run_one(exe, tag, item[0], item[1][0], item[1][1], budget, item[1][2]), enumerate(pairs)):+ results.append(row)+ print("%-32s %s/%s vs %-32s %s/%s" % (row["left"], row["leftLeft"], row["leftSpent"], row["right"],+ row["rightLeft"], row["rightSpent"]), flush=True)+ siege.OUT_DIR.mkdir(exist_ok=True)+ (siege.OUT_DIR / ("duel_" + tag + ".json")).write_text(json.dumps(results, indent=1), encoding="utf-8")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/Tools/Balance/duel_report.py b/Tools/Balance/duel_report.pynew file mode 100644index 000000000..1ec181e01--- /dev/null+++ b/Tools/Balance/duel_report.py@@ -0,0 +1,57 @@+"""Read a mirrored duel run: each pair fought twice with the ground swapped, the two money shares averaged.++ python duel_report.py <tag>++A share is the fraction of the money still standing at the end that belongs to that side: 1.0 wiped+the other army without loss, 0.5 is even. Averaging the two orientations cancels whichever side the+terrain favours; the spread between them is printed so a pair the ground decided can be seen.+"""++import json+import sys+from collections import defaultdict++from siege import OUT_DIR+EVEN = 0.5+++def share(left_left: int, right_left: int) -> float:+ total = left_left + right_left+ return EVEN if total == 0 else left_left / total+++def main() -> int:+ rows = json.loads((OUT_DIR / ("duel_" + sys.argv[1] + ".json")).read_text())+ by_pair = defaultdict(list)+ for row in rows:+ if None in (row["leftLeft"], row["rightLeft"]):+ continue+ by_pair[(row["left"], row["right"])].append(share(row["leftLeft"], row["rightLeft"]))++ per_unit = defaultdict(list)+ decided_by_ground = 0+ matchups = []+ for (left, right), shares in by_pair.items():+ if len(shares) != 2:+ continue+ mean = sum(shares) / 2+ if (shares[0] - EVEN) * (shares[1] - EVEN) < 0:+ decided_by_ground += 1+ per_unit[left].append(mean)+ per_unit[right].append(1 - mean)+ matchups.append((mean, left, right, shares))++ print("unit mean share clear wins pairs")+ for unit, shares in sorted(per_unit.items(), key=lambda kv: -sum(kv[1]) / len(kv[1])):+ print("%-32s %10.2f %10d %5d" % (unit, sum(shares) / len(shares), sum(1 for s in shares if s > 0.75),+ len(shares)))+ print("\n%d of %d pairs flipped winner with the ground" % (decided_by_ground, len(matchups)))+ print("\nmost one-sided (both orientations agree):")+ for mean, left, right, shares in sorted(matchups, key=lambda m: -abs(m[0] - EVEN))[:25]:+ winner, loser = (left, right) if mean > EVEN else (right, left)+ print(" %-30s beats %-30s %.2f (%.2f / %.2f)" % (winner, loser, max(mean, 1 - mean), *shares))+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/Tools/Balance/siege.py b/Tools/Balance/siege.pynew file mode 100644index 000000000..124e22d99--- /dev/null+++ b/Tools/Balance/siege.py@@ -0,0 +1,155 @@+"""Stage every attacker against every stock base defence in the real engine and read the money lost.++One scenario per (defence, attacker, budget, approach). The attackers spend budget x the defence's+EA price (garrison included), walk at it over the open sand of generated map 1 from the west or the+north, and are ordered to attack it. HEADLESS TALLY lines at the start and the end give each side's+count, health and worth. Results land in Run/Balance/<tag>.json; compare.py reads two of them.++ python siege.py <exe name in Run> <tag> [defence filter] [attacker filter]++The exe reads Run/Data/INI/BalanceReforged.ini like the game does, so an A/B of two balance files+is two runs with the file swapped between them, never two at once.+"""++import concurrent.futures+import json+import os+import re+import subprocess+import sys+from pathlib import Path++# the game's data sits beside the exe; a worktree without the archives points this at a Run that has them+RUN_DIR = Path(os.environ.get("ZHR_RUN_DIR", Path(__file__).resolve().parents[2] / "GeneralsMD" / "Run"))+SCENARIO_DIR = RUN_DIR / "Scenarios"+OUT_DIR = RUN_DIR / "Balance"+PARALLEL_RUNS = 5+TIMEOUT_SECONDS = 600+MAX_FRAMES = 3600+TALLY_FRAME = 3550+SPAWN_FRAME = 30+ENTER_FRAME = 40+ATTACK_FRAME = 120+DEFENCE_AT = (1000, 1150)+POWER_AT = (1200, 950)+# west and north: the ground from the south-west hides the infantry from a defence's line of sight+APPROACHES = ((550, 1150), (1000, 1600))+GARRISON_AT = (1080, 1150)+BUDGETS = (1, 2)++# name: (EA's price, power plant or None, garrison template, garrison count). The army is sized on+# EA's price whatever the balance file charges, so two balance files meet the same army.+DEFENCES = {+ "AmericaPatriotBattery": (1000, "AmericaPowerPlant", None, 0),+ "ChinaGattlingCannon": (1200, "ChinaPowerPlant", None, 0),+ "GLAStingerSite": (900, None, None, 0),+ "GLATunnelNetwork": (800, None, None, 0),+ "ChinaBunker": (400, None, "ChinaInfantryTankHunter", 5),+ "AmericaFireBase": (1000, "AmericaPowerPlant", "AmericaInfantryMissileDefender", 4),+}+GARRISON_PRICE = {"ChinaInfantryTankHunter": 300, "AmericaInfantryMissileDefender": 300}+ATTACKERS = {+ "AmericaTankCrusader": 900, "AmericaTankPaladin": 1100, "AmericaVehicleHumvee": 700,+ "AmericaInfantryRanger": 225, "AmericaInfantryMissileDefender": 300, "AmericaVehicleTomahawk": 1200,+ "ChinaTankBattleMaster": 800, "ChinaTankOverlord": 2000, "ChinaTankGattling": 800, "ChinaTankDragon": 800,+ "ChinaInfantryRedguard": 300, "ChinaInfantryTankHunter": 300, "ChinaVehicleInfernoCannon": 900,+ "ChinaVehicleNukeLauncher": 1600,+ "GLATankScorpion": 600, "GLATankMarauder": 800, "GLAVehicleTechnical": 500, "GLAInfantryRebel": 150,+ "GLAInfantryTunnelDefender": 300, "GLAVehicleRocketBuggy": 900, "GLAVehicleQuadCannon": 700,+ "GLAVehicleScudLauncher": 1200,+}+# a Technical spawns as one of its chassis templates+CHASSIS_UNITS = {"GLAVehicleTechnical"}+TALLY = re.compile(r"HEADLESS TALLY: frame (\d+) slot (\d+) '(\S+)': (\d+) alive, health (\d+) of (\d+), worth (\d+)")+++def selector(template: str) -> str:+ return template + "*" if template in CHASSIS_UNITS else template+++def scenario_text(defence: str, attacker: str, count: int, approach: int) -> str:+ price, power, garrison, garrison_count = DEFENCES[defence]+ lines = ["%d spawn 1 %s 1 %d %d" % (SPAWN_FRAME, defence, *DEFENCE_AT)]+ if power:+ lines.append("%d spawn 1 %s 1 %d %d" % (SPAWN_FRAME, power, *POWER_AT))+ if garrison:+ lines.append("%d spawn 1 %s %d %d %d 15" % (SPAWN_FRAME, garrison, garrison_count, *GARRISON_AT))+ lines.append("%d enter 1 %s 1 %s" % (ENTER_FRAME, garrison, defence))+ lines.append("%d spawn 0 %s %d %d %d 35" % (SPAWN_FRAME, attacker, count, *APPROACHES[approach]))+ lines.append("%d attack 0 %s 1 %s" % (ATTACK_FRAME, selector(attacker), defence))+ for frame in (ATTACK_FRAME, TALLY_FRAME):+ lines.append("%d tally 0 %s" % (frame, selector(attacker)))+ lines.append("%d tally 1 %s" % (frame, defence))+ if garrison:+ lines.append("%d tally 1 %s" % (frame, garrison))+ return "\n".join(lines) + "\n"+++def run_one(exe: str, tag: str, index: int, defence: str, attacker: str, budget: int, approach: int) -> dict:+ price, _power, garrison, garrison_count = DEFENCES[defence]+ total = price + (GARRISON_PRICE[garrison] * garrison_count if garrison else 0)+ count = max(1, round(budget * total / ATTACKERS[attacker]))+ # the log prefix is cut at about thirty characters, so the name has to be short and unique+ name = "sg%s%03d" % (tag, index)+ (SCENARIO_DIR / (name + ".txt")).write_text(scenario_text(defence, attacker, count, approach), encoding="ascii")+ log = RUN_DIR / (name + "_DebugLogFile.txt")+ log.unlink(missing_ok=True)+ arguments = [str(RUN_DIR / exe), "-headless", "-quickstart", "-noshellmap", "-observer", "-multiInstance",+ "-noFPSLimit", "-randommap", "1", "2", "small", "-autoskirmish", "2", "-takeover",+ "-side", "0", "FactionAmerica", "-side", "1", "FactionChina", "-seed", "1",+ "-maxframes", str(MAX_FRAMES), "-scenario", name, "-logPrefix", name + "_"]+ process = subprocess.Popen(arguments, cwd=RUN_DIR, creationflags=subprocess.ABOVE_NORMAL_PRIORITY_CLASS)+ try:+ process.wait(timeout=TIMEOUT_SECONDS)+ except subprocess.TimeoutExpired:+ process.kill()+ (SCENARIO_DIR / (name + ".txt")).unlink()+ tallies = {}+ for match in TALLY.finditer(log.read_text(encoding="latin-1", errors="replace")):+ frame, name = int(match.group(1)), match.group(3)+ tallies[(frame, name)] = {"alive": int(match.group(4)), "health": int(match.group(5)),+ "maxHealth": int(match.group(6)), "worth": int(match.group(7))}+ log.unlink()+ start = lambda name: tallies.get((ATTACK_FRAME, selector(name)))+ end = lambda name: tallies.get((TALLY_FRAME, selector(name)))+ if not (start(attacker) and end(attacker) and start(defence) and end(defence)):+ return {"defence": defence, "attacker": attacker, "budget": budget, "error": "missing tally", "tallies": str(tallies)}+ garrison_lost = 0+ if garrison:+ garrison_lost = start(garrison)["worth"] - end(garrison)["worth"] if start(garrison) and end(garrison) else 0+ return {+ "defence": defence, "attacker": attacker, "budget": budget, "approach": approach, "count": count, "defencePrice": total,+ # counted in units, not worth: a Technical's chassis templates carry no build cost+ "attackerSpent": start(attacker)["alive"] * ATTACKERS[attacker],+ "attackerLost": (start(attacker)["alive"] - end(attacker)["alive"]) * ATTACKERS[attacker],+ "defenceStanding": end(defence)["alive"], "defenceHealth": end(defence)["health"] / max(1, start(defence)["maxHealth"]),+ "garrisonLost": garrison_lost, "defenceWorth": start(defence)["worth"],+ }+++def main() -> int:+ exe, tag = sys.argv[1], sys.argv[2]+ defence_filter = re.compile(sys.argv[3] if len(sys.argv) > 3 else ".")+ attacker_filter = re.compile(sys.argv[4] if len(sys.argv) > 4 else ".")+ jobs = [(d, a, b, approach) for d in DEFENCES if defence_filter.search(d) for a in ATTACKERS if attacker_filter.search(a)+ for b in BUDGETS for approach in range(len(APPROACHES))]+ OUT_DIR.mkdir(exist_ok=True)+ results = []+ with concurrent.futures.ThreadPoolExecutor(PARALLEL_RUNS) as pool:+ futures = [pool.submit(run_one, exe, tag, index, *job) for index, job in enumerate(jobs)]+ for future in concurrent.futures.as_completed(futures):+ row = future.result()+ results.append(row)+ if "error" in row:+ print("%-24s %-32s x%d ERROR %s" % (row["defence"], row["attacker"], row["budget"], row["tallies"]), flush=True)+ else:+ print("%-24s %-32s x%d %2d units lost $%5d of $%5d defence %s %.0f%%" % (+ row["defence"], row["attacker"], row["budget"], row["count"], row["attackerLost"],+ row["attackerSpent"], "STANDS" if row["defenceStanding"] else "dead ", row["defenceHealth"] * 100),+ flush=True)+ (OUT_DIR / (tag + ".json")).write_text(json.dumps(results, indent=1), encoding="utf-8")+ return 0+++if __name__ == "__main__":+ sys.exit(main())