From e969b48e80d45213f864cd2674805a0db0638f87 Mon Sep 17 00:00:00 2001 From: Jaredl-Dev <260281143+Jaredl-Dev@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:06:04 -0800 Subject: [PATCH 1/2] unify(rts): Merge Common/RTS and related code (#3733) --- .../GameEngine/Include/Common/ActionManager.h | 1 + .../Code/GameEngine/Include/Common/Energy.h | 5 + .../Code/GameEngine/Include/Common/Player.h | 34 +- .../Include/Common/SpecialPowerType.h | 38 ++ .../Code/GameEngine/Include/Common/Team.h | 2 +- .../GameEngine/Include/GameLogic/AIPlayer.h | 6 +- .../Include/GameLogic/AISkirmishPlayer.h | 2 +- .../Include/GameLogic/Module/CollideModule.h | 2 + .../Include/GameLogic/Module/ContainModule.h | 1 + .../Include/GameLogic/Module/CrateCollide.h | 1 + .../GameLogic/Module/MinefieldBehavior.h | 1 + .../Include/GameLogic/Module/OpenContain.h | 2 + .../Include/GameLogic/Module/PhysicsUpdate.h | 1 + .../GameLogic/Module/SpecialPowerModule.h | 6 + .../Include/GameLogic/Module/ToppleUpdate.h | 1 + .../GameEngine/Include/GameLogic/Object.h | 5 +- .../GameEngine/Include/GameLogic/WeaponSet.h | 5 +- .../Source/Common/RTS/ActionManager.cpp | 342 ++++++++++++++++-- .../GameEngine/Source/Common/RTS/Energy.cpp | 33 +- .../GameEngine/Source/Common/RTS/Money.cpp | 9 + .../GameEngine/Source/Common/RTS/Player.cpp | 247 ++++++++++++- .../Common/RTS/ProductionPrerequisite.cpp | 15 +- .../Common/RTS/ResourceGatheringManager.cpp | 2 +- .../Source/Common/RTS/SpecialPower.cpp | 30 ++ .../GameEngine/Source/Common/RTS/Team.cpp | 16 +- .../Source/Common/RTS/TunnelTracker.cpp | 6 +- .../Source/GameLogic/AI/AIPlayer.cpp | 210 ++++++++++- .../Source/GameLogic/AI/AISkirmishPlayer.cpp | 6 +- .../Source/GameLogic/Object/Object.cpp | 8 +- .../Source/GameLogic/Object/WeaponSet.cpp | 11 +- .../Code/GameEngine/Include/Common/Player.h | 11 + .../Include/Common/SpecialPowerType.h | 5 +- .../Source/Common/RTS/ActionManager.cpp | 38 +- .../GameEngine/Source/Common/RTS/Energy.cpp | 8 +- .../GameEngine/Source/Common/RTS/Player.cpp | 114 ++++++ .../Source/Common/RTS/SpecialPower.cpp | 5 +- .../GameEngine/Source/Common/RTS/Team.cpp | 9 +- .../Source/Common/RTS/TunnelTracker.cpp | 7 +- 38 files changed, 1134 insertions(+), 111 deletions(-) diff --git a/Generals/Code/GameEngine/Include/Common/ActionManager.h b/Generals/Code/GameEngine/Include/Common/ActionManager.h index cc7d70717cf..db1a515f272 100644 --- a/Generals/Code/GameEngine/Include/Common/ActionManager.h +++ b/Generals/Code/GameEngine/Include/Common/ActionManager.h @@ -78,6 +78,7 @@ class ActionManager : public SubsystemInterface CanAttackResult getCanAttackObject( const Object *obj, const Object *objectToAttack, CommandSourceType commandSource, AbleToAttackType attackType ); Bool canConvertObjectToCarBomb( const Object *obj, const Object *objectToConvert, CommandSourceType commandSource ); Bool canHijackVehicle( const Object *obj, const Object *ObjectToHijack, CommandSourceType commandSource ); // LORENZEN + Bool canSabotageBuilding( const Object *obj, const Object *objectToSabotage, CommandSourceType commandSource ); Bool canCaptureBuilding( const Object *obj, const Object *objectToCapture, CommandSourceType commandSource ); Bool canDisableVehicleViaHacking( const Object *obj, const Object *objectToHack, CommandSourceType commandSource, Bool checkSourceRequirements = true ); #ifdef ALLOW_SURRENDER diff --git a/Generals/Code/GameEngine/Include/Common/Energy.h b/Generals/Code/GameEngine/Include/Common/Energy.h index 82b6b1fbc9a..48280202cc5 100644 --- a/Generals/Code/GameEngine/Include/Common/Energy.h +++ b/Generals/Code/GameEngine/Include/Common/Energy.h @@ -70,6 +70,7 @@ class Energy : public Snapshot { m_energyProduction = 0; m_energyConsumption = 0; + m_powerSabotagedTillFrame = 0; m_owner = owner; } @@ -94,6 +95,9 @@ class Energy : public Snapshot void addPowerBonus( Object *obj ); void removePowerBonus( Object *obj ); + void setPowerSabotagedTillFrame( UnsignedInt frame ) { m_powerSabotagedTillFrame = frame; } + UnsignedInt getPowerSabotagedTillFrame() const { return m_powerSabotagedTillFrame; } + /** return the percentage of energy needed that we actually produce, as a 0.0 ... 1.0 fraction. */ @@ -113,5 +117,6 @@ class Energy : public Snapshot Int m_energyProduction; ///< level of energy production, in kw Int m_energyConsumption; ///< level of energy consumption, in kw + UnsignedInt m_powerSabotagedTillFrame; ///< If power is sabotaged, the frame will be greater than now. Player *m_owner; ///< Tight pointer to the Player I am intrinsic to. }; diff --git a/Generals/Code/GameEngine/Include/Common/Player.h b/Generals/Code/GameEngine/Include/Common/Player.h index 6f7ea69109d..06f99d50a41 100644 --- a/Generals/Code/GameEngine/Include/Common/Player.h +++ b/Generals/Code/GameEngine/Include/Common/Player.h @@ -225,6 +225,7 @@ class Player : public Snapshot NameKeyType getPlayerNameKey() const { return m_playerNameKey; } AsciiString getSide() const { return m_side; } + AsciiString getBaseSide() const { return m_baseSide; } const PlayerTemplate* getPlayerTemplate() const { return m_playerTemplate; } /// return the Player's Handicap sub-object @@ -235,7 +236,7 @@ class Player : public Snapshot Money *getMoney() { return &m_money; } const Money *getMoney() const { return &m_money; } - UnsignedInt getSupplyBoxValue();///< Many things can affect the alue of a crate, but at heart it is a GlobalData ratio. + UnsignedInt getSupplyBoxValue();///< Many things can affect the value of a crate, but at heart it is a GlobalData ratio. Energy *getEnergy() { return &m_energy; } const Energy *getEnergy() const { return &m_energy; } @@ -441,7 +442,7 @@ class Player : public Snapshot /// Have the team guard a supply center. void guardSupplyCenter( Team *team, Int minSupplies ); - virtual void computeSuperweaponTarget(const SpecialPowerTemplate *power, Coord3D *pos, Int playerNdx, Real weaponRadius); ///< Calculates best pos for weapon given radius. + virtual Bool computeSuperweaponTarget(const SpecialPowerTemplate *power, Coord3D *pos, Int playerNdx, Real weaponRadius); ///< Calculates best pos for weapon given radius. /// Get the enemy an ai player is currently focused on. NOTE - Can be nullptr. Player *getCurrentEnemy(); @@ -561,10 +562,14 @@ class Player : public Snapshot Bool getUnitsShouldHunt() const { return m_unitsShouldHunt; } /// All of our units are new spied upon; they sight for the given enemy +#if RTS_GENERALS void setUnitsVisionSpied( Bool setting, PlayerIndex byWhom ); /// This will be asked by units when they look to get extra people to sight for PlayerMaskType getVisionSpiedMask() const; +#else + void setUnitsVisionSpied( Bool setting, KindOfMaskType whichUnits, PlayerIndex byWhom ); +#endif /// Destroy all of the teams for this player, causing him to DIE. void killPlayer(); @@ -581,6 +586,9 @@ class Player : public Snapshot /// Build a building near a supply dump with at least cash. Gets passed to aiPlayer. void buildBySupplies(Int minimumCash, const AsciiString &thingName); + /// Build an instance of a specific building nearest specified team. Gets passed to aiPlayer. + void buildSpecificBuildingNearestTeam( const AsciiString &thingName, const Team *team ); + /// Build an upgrade. Gets passed to aiPlayer. void buildUpgrade(const AsciiString &upgrade); @@ -593,6 +601,9 @@ class Player : public Snapshot /// Recruits an instance of a specific team. Gets passed to aiPlayer. void recruitSpecificTeam(TeamPrototype *teamProto, Real recruitRadius); + /// Calculates the closest construction zone location based on a template. Gets plassed to aiPlayer + Bool calcClosestConstructionZoneLocation( const ThingTemplate *constructTemplate, Coord3D *location ); + /// Enable/Disable the construction of units Bool getCanBuildUnits() { return m_canBuildUnits; } void setCanBuildUnits(Bool canProduce) { m_canBuildUnits = canProduce; } @@ -742,6 +753,7 @@ class Player : public Snapshot NameKeyType m_playerNameKey; ///< This player's internal name (for matching map objects) PlayerIndex m_playerIndex; ///< player unique index. AsciiString m_side; ///< the "side" this player is on + AsciiString m_baseSide; ///< the base side, GLA, USA, or China PlayerType m_playerType; ///< human/computer control Money m_money; ///< Player's current wealth Upgrade* m_upgradeList; ///< list of all upgrades this player has @@ -768,15 +780,15 @@ class Player : public Snapshot TunnelTracker* m_tunnelSystem; ///< All TunnelContain buildings use this part of me for actual containment Team* m_defaultTeam; ///< our "default" team. - ScienceVec m_sciences; ///< (SAVE) sciences that we know (either intrinsically or via later purchases) - ScienceVec m_sciencesDisabled; ///< (SAVE) sciences that we are not permitted to purchase "yet". Controlled by mission scripts. - ScienceVec m_sciencesHidden; ///< (SAVE) sciences that aren't shown. Controlled by mission scripts. + ScienceVec m_sciences; ///< (SAVE) sciences that we know (either intrinsically or via later purchases) + ScienceVec m_sciencesDisabled; ///< (SAVE) sciences that we are not permitted to purchase "yet". Controlled by mission scripts. + ScienceVec m_sciencesHidden; ///< (SAVE) sciences that aren't shown. Controlled by mission scripts. - Int m_rankLevel; ///< (SAVE) our RankLevel, 1...n - Int m_skillPoints; ///< (SAVE) our cumulative SkillPoint total - Int m_sciencePurchasePoints; ///< (SAVE) our unspent SciencePurchasePoint total - Int m_levelUp, m_levelDown; ///< (NO-SAVE) skill points to go up/down a level (runtime only) - UnicodeString m_generalName; ///< (SAVE) This is the name of the general the player is allowed to change. + Int m_rankLevel; ///< (SAVE) our RankLevel, 1...n + Int m_skillPoints; ///< (SAVE) our cumulative SkillPoint total + Int m_sciencePurchasePoints; ///< (SAVE) our unspent SciencePurchasePoint total + Int m_levelUp, m_levelDown; ///< (NO-SAVE) skill points to go up/down a level (runtime only) + UnicodeString m_generalName; ///< (SAVE) This is the name of the general the player is allowed to change. PlayerTeamList m_playerTeamPrototypes; ///< ALL the teams we control, via prototype PlayerRelationMap *m_playerRelations; ///< allies & enemies @@ -795,8 +807,10 @@ class Player : public Snapshot Bool m_attackedBy[MAX_PLAYER_COUNT]; ///< For each player, have they attacked me? UnsignedInt m_attackedFrame; ///< Last frame attacked. +#if RTS_GENERALS Int m_visionSpiedBy[MAX_PLAYER_COUNT]; ///< Reference count of having units spied on by players. PlayerMaskType m_visionSpiedMask; ///< For quick lookup and edge triggered maintenance +#endif Real m_cashBountyPercent; diff --git a/Generals/Code/GameEngine/Include/Common/SpecialPowerType.h b/Generals/Code/GameEngine/Include/Common/SpecialPowerType.h index 4fc2a6031d0..d7a7e4edde5 100644 --- a/Generals/Code/GameEngine/Include/Common/SpecialPowerType.h +++ b/Generals/Code/GameEngine/Include/Common/SpecialPowerType.h @@ -71,6 +71,7 @@ enum SpecialPowerType CPP_11(: Int) SPECIAL_MISSILE_DEFENDER_LASER_GUIDED_MISSILES, SPECIAL_REMOTE_CHARGES, SPECIAL_TIMED_CHARGES, + SPECIAL_HELIX_NAPALM_BOMB, // Added in Zero Hour SPECIAL_HACKER_DISABLE_BUILDING, SPECIAL_TANKHUNTER_TNT_ATTACK, SPECIAL_BLACKLOTUS_CAPTURE_BUILDING, @@ -80,6 +81,7 @@ enum SpecialPowerType CPP_11(: Int) SPECIAL_RADAR_VAN_SCAN, SPECIAL_SPY_DRONE, SPECIAL_DISGUISE_AS_VEHICLE, + SPECIAL_BOOBY_TRAP, // Added in Zero Hour // don't forget to add new strings to SpecialPowerMaskType::s_bitNameList[] SPECIAL_REPAIR_VEHICLES, SPECIAL_PARTICLE_UPLINK_CANNON, @@ -90,6 +92,42 @@ enum SpecialPowerType CPP_11(: Int) // don't forget to add new strings to SpecialPowerMaskType::s_bitNameList[] SPECIAL_LAUNCH_BAIKONUR_ROCKET, + // TheSuperHackers @info Added in Zero Hour: + SPECIAL_SPECTRE_GUNSHIP, + SPECIAL_GPS_SCRAMBLER, + + SPECIAL_FRENZY, + SPECIAL_SNEAK_ATTACK, + + //Ack, this is ass. These enums fix a bug where new enums were missing for + //shortcut powers... but the real clincher was that if you were say USA and + //captured a Tank China command center, your US paradrop would be assigned + //to the china tank drop and when you tried to fire it from the shortcut + //it could pick the china one and not fire it because it didn't have + //complete connection... ugh!!! + SPECIAL_CHINA_CARPET_BOMB, + EARLY_SPECIAL_CHINA_CARPET_BOMB, + SPECIAL_LEAFLET_DROP, + EARLY_SPECIAL_LEAFLET_DROP, + EARLY_SPECIAL_FRENZY, + SPECIAL_COMMUNICATIONS_DOWNLOAD, + EARLY_SPECIAL_REPAIR_VEHICLES, + SPECIAL_TANK_PARADROP, + SUPW_SPECIAL_PARTICLE_UPLINK_CANNON, + AIRF_SPECIAL_DAISY_CUTTER, + NUKE_SPECIAL_CLUSTER_MINES, + NUKE_SPECIAL_NEUTRON_MISSILE, + AIRF_SPECIAL_A10_THUNDERBOLT_STRIKE, + AIRF_SPECIAL_SPECTRE_GUNSHIP, + INFA_SPECIAL_PARADROP_AMERICA, + SLTH_SPECIAL_GPS_SCRAMBLER, + AIRF_SPECIAL_CARPET_BOMB, + SUPR_SPECIAL_CRUISE_MISSILE, + LAZR_SPECIAL_PARTICLE_UPLINK_CANNON, + SUPW_SPECIAL_NEUTRON_MISSILE, + + SPECIAL_BATTLESHIP_BOMBARDMENT, + SPECIALPOWER_COUNT, // don't forget to add new strings to SpecialPowerMaskType::s_bitNameList[] }; diff --git a/Generals/Code/GameEngine/Include/Common/Team.h b/Generals/Code/GameEngine/Include/Common/Team.h index 65c8160b73b..58d7ed50e5e 100644 --- a/Generals/Code/GameEngine/Include/Common/Team.h +++ b/Generals/Code/GameEngine/Include/Common/Team.h @@ -471,7 +471,7 @@ class Team : public MemoryPoolObject, a convenience routine used to estimate the team's position by just returning the position of the first member of the team */ - const Coord3D* getEstimateTeamPosition(); + const Coord3D* getEstimateTeamPosition() const; /** a convenience routine to move a team's units to another team. diff --git a/Generals/Code/GameEngine/Include/GameLogic/AIPlayer.h b/Generals/Code/GameEngine/Include/GameLogic/AIPlayer.h index 81350b7c446..ce1b60f8026 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/AIPlayer.h +++ b/Generals/Code/GameEngine/Include/GameLogic/AIPlayer.h @@ -153,7 +153,7 @@ class AIPlayer : public MemoryPoolObject, AIPlayer( Player *p ); ///< constructor - virtual void computeSuperweaponTarget(const SpecialPowerTemplate *power, Coord3D *pos, Int playerNdx, Real weaponRadius); ///< Calculates best pos for weapon given radius. + virtual Bool computeSuperweaponTarget(const SpecialPowerTemplate *power, Coord3D *pos, Int playerNdx, Real weaponRadius); ///< Calculates best pos for weapon given radius. public: // AIPlayer interface, may be overridden by AISkirmishPlayer. jba. @@ -191,6 +191,7 @@ class AIPlayer : public MemoryPoolObject, GameDifficulty getAIDifficulty() const; void setAIDifficulty(GameDifficulty difficulty) {m_difficulty = difficulty;} void buildBySupplies(Int minimumCash, const AsciiString &thingName ); ///< Builds a building by supplies. + void buildSpecificBuildingNearestTeam( const AsciiString &thingName, const Team *team ); void buildUpgrade(const AsciiString &upgrade ); ///< Builds an upgrade. /// A team is about to be destroyed. void aiPreTeamDestroy( const Team *team ); @@ -206,6 +207,9 @@ class AIPlayer : public MemoryPoolObject, void setTeamDelaySeconds(Int delay) {m_teamSeconds = delay;} + /// Calculates the closest construction zone location based on a template. + Bool calcClosestConstructionZoneLocation( const ThingTemplate *constructTemplate, Coord3D *location ); + protected: // snapshot methods diff --git a/Generals/Code/GameEngine/Include/GameLogic/AISkirmishPlayer.h b/Generals/Code/GameEngine/Include/GameLogic/AISkirmishPlayer.h index a10ecf008f9..284f3efad95 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/AISkirmishPlayer.h +++ b/Generals/Code/GameEngine/Include/GameLogic/AISkirmishPlayer.h @@ -45,7 +45,7 @@ class AISkirmishPlayer : public AIPlayer public: // AISkirmish specific methods. AISkirmishPlayer( Player *p ); ///< constructor - virtual void computeSuperweaponTarget(const SpecialPowerTemplate *power, Coord3D *pos, Int playerNdx, Real weaponRadius) override; ///< Calculates best pos for weapon given radius. + virtual Bool computeSuperweaponTarget(const SpecialPowerTemplate *power, Coord3D *pos, Int playerNdx, Real weaponRadius) override; ///< Calculates best pos for weapon given radius. public: // AIPlayer interface methods. diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/CollideModule.h b/Generals/Code/GameEngine/Include/GameLogic/Module/CollideModule.h index 4ab2553d589..1e782f639e6 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/CollideModule.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/CollideModule.h @@ -47,6 +47,7 @@ class CollideModuleInterface virtual void onCollide( Object *other, const Coord3D *loc, const Coord3D *normal ) = 0; virtual Bool wouldLikeToCollideWith(const Object* other) const = 0; virtual Bool isHijackedVehicleCrateCollide() const = 0; + virtual Bool isSabotageBuildingCrateCollide() const = 0; virtual Bool isCarBombCrateCollide() const = 0; virtual Bool isRailroad() const = 0; virtual Bool isSalvageCrateCollide() const = 0; @@ -87,6 +88,7 @@ class CollideModule : public BehaviorModule, /// this is used for things like pilots, to determine if they can "enter" something virtual Bool wouldLikeToCollideWith(const Object* other) const override { return false; } virtual Bool isHijackedVehicleCrateCollide() const override { return false; } + virtual Bool isSabotageBuildingCrateCollide() const override { return false; } virtual Bool isCarBombCrateCollide() const override { return false; } virtual Bool isRailroad() const override { return false;} virtual Bool isSalvageCrateCollide() const override { return false; } diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/ContainModule.h b/Generals/Code/GameEngine/Include/GameLogic/Module/ContainModule.h index f5683c41b64..5ddc03408ef 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/ContainModule.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/ContainModule.h @@ -84,6 +84,7 @@ class ContainModuleInterface virtual Bool isSpecialZeroSlotContainer() const = 0; virtual Bool isHealContain() const = 0; virtual Bool isTunnelContain() const = 0; + virtual Bool isRiderChangeContain() const = 0; virtual Bool isImmuneToClearBuildingAttacks() const = 0; diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/CrateCollide.h b/Generals/Code/GameEngine/Include/GameLogic/Module/CrateCollide.h index a03545b4562..bc871beb1f1 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/CrateCollide.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/CrateCollide.h @@ -81,6 +81,7 @@ class CrateCollide : public CollideModule virtual Bool isRailroad() const override { return FALSE;}; virtual Bool isCarBombCrateCollide() const override { return FALSE; } virtual Bool isHijackedVehicleCrateCollide() const override { return FALSE; } + virtual Bool isSabotageBuildingCrateCollide() const override { return FALSE; } protected: diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/MinefieldBehavior.h b/Generals/Code/GameEngine/Include/GameLogic/Module/MinefieldBehavior.h index 2f4d60d1217..4ef2c1b10e1 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/MinefieldBehavior.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/MinefieldBehavior.h @@ -103,6 +103,7 @@ class MinefieldBehavior : public UpdateModule, virtual Bool isCarBombCrateCollide() const override { return false; } virtual Bool isRailroad() const override { return false;} virtual Bool isSalvageCrateCollide() const override { return false; } + virtual Bool isSabotageBuildingCrateCollide() const override { return FALSE; } // Minefield specific methods virtual void setScootParms(const Coord3D& start, const Coord3D& end) override; diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/OpenContain.h b/Generals/Code/GameEngine/Include/GameLogic/Module/OpenContain.h index 9d37912e735..af5fa59859d 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/OpenContain.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/OpenContain.h @@ -108,6 +108,7 @@ class OpenContain : public UpdateModule, virtual Bool isHijackedVehicleCrateCollide() const override { return false; } virtual Bool isRailroad() const override { return false;} virtual Bool isSalvageCrateCollide() const override { return false; } + virtual Bool isSabotageBuildingCrateCollide() const override { return FALSE; } // UpdateModule virtual UpdateSleepTime update() override; ///< called once per frame @@ -191,6 +192,7 @@ class OpenContain : public UpdateModule, virtual Bool isGarrisonable() const override { return false; } ///< can this unit be Garrisoned? (ick) virtual Bool isHealContain() const override { return false; } ///< true when container only contains units while healing (not a transport!) virtual Bool isTunnelContain() const override { return FALSE; } + virtual Bool isRiderChangeContain() const override { return FALSE; } virtual Bool isSpecialZeroSlotContainer() const override { return false; } virtual Bool isImmuneToClearBuildingAttacks() const override { return true; } diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/PhysicsUpdate.h b/Generals/Code/GameEngine/Include/GameLogic/Module/PhysicsUpdate.h index f2baddfbcd6..ab357fe8a3e 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/PhysicsUpdate.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/PhysicsUpdate.h @@ -95,6 +95,7 @@ class PhysicsBehavior : public UpdateModule, virtual Bool isHijackedVehicleCrateCollide() const override { return false; } virtual Bool isRailroad() const override { return false;} virtual Bool isSalvageCrateCollide() const override { return false; } + virtual Bool isSabotageBuildingCrateCollide() const override { return FALSE; } // UpdateModuleInterface virtual UpdateSleepTime update() override; diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/SpecialPowerModule.h b/Generals/Code/GameEngine/Include/GameLogic/Module/SpecialPowerModule.h index d878094e831..ab015d31066 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/SpecialPowerModule.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/SpecialPowerModule.h @@ -68,6 +68,9 @@ class SpecialPowerModuleInterface virtual const AudioEventRTS& getInitiateSound() const = 0; virtual Bool startsReady() const = 0; virtual Bool isScriptOnly() const = 0; + + //If the special power launches a construction site, we need to know the final product for placement purposes. + virtual const ThingTemplate* getReferenceThingTemplate() const = 0; }; //------------------------------------------------------------------------------------------------- @@ -156,6 +159,9 @@ class SpecialPowerModule : public BehaviorModule, virtual Bool startsReady() const override; virtual Bool isScriptOnly() const override; + //If the special power launches a construction site, we need to know the final product for placement purposes. + virtual const ThingTemplate* getReferenceThingTemplate() const override { return nullptr; } + protected: Bool initiateIntentToDoSpecialPower( const Object *targetObj, const Coord3D *targetPos, const Waypoint *way, UnsignedInt commandOptions ); diff --git a/Generals/Code/GameEngine/Include/GameLogic/Module/ToppleUpdate.h b/Generals/Code/GameEngine/Include/GameLogic/Module/ToppleUpdate.h index 0d1f9fefd42..7c28235e011 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Module/ToppleUpdate.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Module/ToppleUpdate.h @@ -102,6 +102,7 @@ class ToppleUpdate : public UpdateModule, virtual Bool isCarBombCrateCollide() const override { return false; } virtual Bool isRailroad() const override { return false; } virtual Bool isSalvageCrateCollide() const override { return false; } + virtual Bool isSabotageBuildingCrateCollide() const override { return FALSE; } protected: diff --git a/Generals/Code/GameEngine/Include/GameLogic/Object.h b/Generals/Code/GameEngine/Include/GameLogic/Object.h index ea38ddbc835..63694d2357e 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/Object.h +++ b/Generals/Code/GameEngine/Include/GameLogic/Object.h @@ -458,6 +458,7 @@ class Object : public Thing, public Snapshot UnsignedInt getMostPercentReadyToFireAnyWeapon() const; Weapon* getWeaponInWeaponSlot(WeaponSlotType wslot) const { return m_weaponSet.getWeaponInWeaponSlot(wslot); } + UnsignedInt getWeaponInWeaponSlotCommandSourceMask( WeaponSlotType wSlot ) const { return m_weaponSet.getNthCommandSourceMask( wSlot ); } // see if this current weapon set's weapons has shared reload times Bool isReloadTimeShared() const { return m_weaponSet.isSharedReloadTime(); } @@ -486,10 +487,10 @@ class Object : public Thing, public Snapshot where we already know that isAbleToAttack() == true. so you should always call isAbleToAttack prior to calling this! (srj) */ - CanAttackResult getAbleToAttackSpecificObject( AbleToAttackType t, const Object* target, CommandSourceType commandSource ) const; + CanAttackResult getAbleToAttackSpecificObject( AbleToAttackType t, const Object* target, CommandSourceType commandSource, WeaponSlotType specificSlot = (WeaponSlotType)-1 ) const; //Used for base defenses and otherwise stationary units to see if you can attack a position potentially out of range. - CanAttackResult getAbleToUseWeaponAgainstTarget( AbleToAttackType attackType, const Object *victim, const Coord3D *pos, CommandSourceType commandSource ) const; + CanAttackResult getAbleToUseWeaponAgainstTarget( AbleToAttackType attackType, const Object *victim, const Coord3D *pos, CommandSourceType commandSource, WeaponSlotType specificSlot = (WeaponSlotType)-1 ) const; /** Selects the best weapon for the given target, and sets it as the current weapon. diff --git a/Generals/Code/GameEngine/Include/GameLogic/WeaponSet.h b/Generals/Code/GameEngine/Include/GameLogic/WeaponSet.h index b1bec5d0293..9a1a323d07b 100644 --- a/Generals/Code/GameEngine/Include/GameLogic/WeaponSet.h +++ b/Generals/Code/GameEngine/Include/GameLogic/WeaponSet.h @@ -216,6 +216,7 @@ class WeaponSet : public Snapshot Weapon* findWaypointFollowingCapableWeapon(); const Weapon* findAmmoPipShowingWeapon() const; UnsignedInt getMostPercentReadyToFireAnyWeapon() const; + inline UnsignedInt getNthCommandSourceMask( WeaponSlotType n ) const { return m_curWeaponTemplateSet ? m_curWeaponTemplateSet->getNthCommandSourceMask( n ) : 0; } Bool setWeaponLock( WeaponSlotType weaponSlot, WeaponLockType lockType ); void releaseWeaponLock(WeaponLockType lockType); @@ -231,11 +232,11 @@ class WeaponSet : public Snapshot account, but immutable weapon properties, such as "can you target airborne victims". */ - CanAttackResult getAbleToAttackSpecificObject( AbleToAttackType t, const Object* obj, const Object* victim, CommandSourceType commandSource ) const; + CanAttackResult getAbleToAttackSpecificObject( AbleToAttackType t, const Object* obj, const Object* victim, CommandSourceType commandSource, WeaponSlotType specificSlot = (WeaponSlotType)-1 ) const; //When calling this function, all conditions must be validated to the point where we have decided that we wish to attack the object (faction checks, etc). //Now, we are determining if the attack itself is able to be performed! - CanAttackResult getAbleToUseWeaponAgainstTarget( AbleToAttackType attackType, const Object *source, const Object *victim, const Coord3D *pos, CommandSourceType commandSource ) const; + CanAttackResult getAbleToUseWeaponAgainstTarget( AbleToAttackType attackType, const Object *source, const Object *victim, const Coord3D *pos, CommandSourceType commandSource, WeaponSlotType specificSlot = (WeaponSlotType)-1 ) const; /** Selects the best weapon for the given target, and sets it as the current weapon. diff --git a/Generals/Code/GameEngine/Source/Common/RTS/ActionManager.cpp b/Generals/Code/GameEngine/Source/Common/RTS/ActionManager.cpp index b6f8417b579..07069248e59 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/ActionManager.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/ActionManager.cpp @@ -36,6 +36,7 @@ #include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine #include "Common/ActionManager.h" +#include "Common/BuildAssistant.h" #include "Common/GlobalData.h" #include "Common/Player.h" #include "Common/PlayerList.h" @@ -155,6 +156,12 @@ Bool ActionManager::canGetRepairedAt( const Object *obj, const Object *repairDes if( obj->isEffectivelyDead() ) return FALSE; +#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) + // If I can't move, I can't get repaired + if( !obj->isMobile() ) + return FALSE; +#endif + // nothing can be done with things that are under construction if( obj->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) || repairDest->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) ) @@ -564,6 +571,11 @@ Bool ActionManager::canEnterObject( const Object *obj, const Object *objectToEnt return FALSE; } + + if (objectToEnter->isDisabledByType( DISABLED_SUBDUED )) + return FALSE; // a microwave tank has soldered the doors shut + + if( obj->isKindOf( KINDOF_STRUCTURE ) || obj->isKindOf( KINDOF_IMMOBILE ) ) { //Structures or immobiles can't garrison @@ -573,12 +585,21 @@ Bool ActionManager::canEnterObject( const Object *obj, const Object *objectToEnt // Special case for unmanned vehicles. Any infantry unit can take over any unmanned vehicle! if( obj->isKindOf( KINDOF_INFANTRY ) && objectToEnter->isDisabledByType( DISABLED_UNMANNED ) ) { - return TRUE; + if( !obj->isKindOf( KINDOF_REJECT_UNMANNED ) ) + { + //But only if it's allowed to. + return TRUE; + } } // Special case for aircraft. if( obj->isKindOf( KINDOF_AIRCRAFT ) && objectToEnter->isKindOf( KINDOF_FS_AIRFIELD ) ) { + if( obj->getStatusBits().test( OBJECT_STATUS_DECK_HEIGHT_OFFSET ) && obj->getCarrierDeckHeight() >= obj->getPosition()->z ) + { + return FALSE; + } + if (!obj->isAboveTerrain()) return FALSE; @@ -726,6 +747,31 @@ CanAttackResult ActionManager::getCanAttackObject( const Object *obj, const Obje CanAttackResult result = obj->getAbleToAttackSpecificObject( attackType, objectToAttack, commandSource ); if( result != ATTACKRESULT_NOT_POSSIBLE ) { +#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) + //Kris: August 5, 2003 + //Fix a case where the Demo_GLAInfantryWorker is able to attack using his passive bomb upgrade. We don't + //want him to allow a visible attack cursor for the player. This code never checked for AutoChoosesSources + //logic, but now we will but only when the commandSource is FROM_PLAYER. + if( commandSource == CMD_FROM_PLAYER ) + { + //Check if it's got any weapons that can be used. + Bool anyValidWeapon = FALSE; + for( Int i = 0; i < WEAPONSLOT_COUNT; i++ ) + { + UnsignedInt cmdSourceMask = obj->getWeaponInWeaponSlotCommandSourceMask( (WeaponSlotType)i ); + if( cmdSourceMask ) + { + anyValidWeapon = TRUE; + break; + } + } + if( !anyValidWeapon ) + { + return ATTACKRESULT_NOT_POSSIBLE; + } + } +#endif + if( result == ATTACKRESULT_INVALID_SHOT && obj->isKindOf( KINDOF_DOZER ) ) { //For the case of dozers, we don't ever want to see an attack cursor @@ -759,6 +805,20 @@ CanAttackResult ActionManager::getCanAttackObject( const Object *obj, const Obje } } } + else if( result == ATTACKRESULT_NOT_POSSIBLE )// oh dear me. The weird case of a garrisoncontainer being a KINDOF_SPAWNS_ARE_THE_WEAPONS... the AmericaBuildingFirebase + { + ContainModuleInterface *contain = obj->getContain(); + if ( contain ) + { + Object *rider = contain->getClosestRider( objectToAttack->getPosition() ); + if ( rider ) + { + result = rider->getAbleToAttackSpecificObject( attackType, objectToAttack, commandSource ); + if( result != ATTACKRESULT_NOT_POSSIBLE ) + return result; + } + } + } } return ATTACKRESULT_NOT_POSSIBLE; @@ -803,10 +863,6 @@ Bool ActionManager::canConvertObjectToCarBomb( const Object *obj, const Object * // ------------------------------------------------------------------------------------------------ Bool ActionManager::canHijackVehicle( const Object *obj, const Object *objectToHijack, CommandSourceType commandSource ) //LORENZEN { - - int foo = 10; - ++foo; - // sanity if( obj == nullptr || objectToHijack == nullptr ) { @@ -838,25 +894,17 @@ Bool ActionManager::canHijackVehicle( const Object *obj, const Object *objectToH return FALSE; } - //Silly hijacker, you can't hijack that plane from the ground! - //if( objectToHijack->isAirborneTarget() ) - //{ - // return FALSE; - //} - //Kris -- Hijackers can no longer hijack any aircraft. if( objectToHijack->isKindOf( KINDOF_AIRCRAFT ) ) { return FALSE; } -// Dustin asked for this to be removed, 12/13... ML - //Elite and heroic units are immune to this kind of attack -// VeterancyLevel veterancyLevel = objectToHijack->getVeterancyLevel(); -// if( veterancyLevel >= LEVEL_ELITE ) -// { -// return FALSE; -// } + //Can't hijack a drone type. + if( objectToHijack->isKindOf( KINDOF_DRONE ) ) + { + return FALSE; + } // last, see if we'd like to collide with 'objectToHijack' for (BehaviorModule** m = obj->getBehaviorModules(); *m; ++m) @@ -874,6 +922,50 @@ Bool ActionManager::canHijackVehicle( const Object *obj, const Object *objectToH return FALSE; } +// ------------------------------------------------------------------------------------------------ +Bool ActionManager::canSabotageBuilding( const Object *obj, const Object *objectToSabotage, CommandSourceType commandSource ) +{ + // sanity + if( obj == nullptr || objectToSabotage == nullptr ) + { + return FALSE; + } + + //Make sure it's alive. + if( objectToSabotage->isEffectivelyDead() ) + { + return FALSE; + } + + // if the target is in the shroud, we can't do anything + if (isObjectShroudedForAction(obj, objectToSabotage, commandSource)) + { + return FALSE; + } + + Relationship r = obj->getRelationship(objectToSabotage); + //Only sabotage enemy objects + if( r != ENEMIES ) + { + return FALSE; + } + + // last, see if we'd like to collide with 'objectToSabotage' + for (BehaviorModule** m = obj->getBehaviorModules(); *m; ++m) + { + CollideModuleInterface* collide = (*m)->getCollide(); + if (!collide) + continue; + + if( collide->wouldLikeToCollideWith( objectToSabotage ) && collide->isSabotageBuildingCrateCollide() ) + { + return TRUE; + } + } + + return FALSE; +} + // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ Bool ActionManager::canMakeObjectDefector( const Object *obj, const Object *objectToMakeDefector, CommandSourceType commandSource ) //LORENZEN @@ -988,7 +1080,11 @@ Bool ActionManager::canCaptureBuilding( const Object *obj, const Object *objectT //If the enemy unit is stealthed and not detected, then we can't capture it! if( objectToCapture->testStatus( OBJECT_STATUS_STEALTHED ) && - !objectToCapture->testStatus( OBJECT_STATUS_DETECTED ) ) + !objectToCapture->testStatus( OBJECT_STATUS_DETECTED ) +#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) + && !objectToCapture->testStatus( OBJECT_STATUS_DISGUISED ) +#endif + ) { return FALSE; } @@ -1077,7 +1173,11 @@ Bool ActionManager::canDisableVehicleViaHacking( const Object *obj, const Object //If the enemy unit is stealthed and not detected, then we can't attack it! if( objectToHack->testStatus( OBJECT_STATUS_STEALTHED ) && - !objectToHack->testStatus( OBJECT_STATUS_DETECTED ) ) + !objectToHack->testStatus( OBJECT_STATUS_DETECTED ) +#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) + && !objectToHack->testStatus( OBJECT_STATUS_DISGUISED ) +#endif + ) { return FALSE; } @@ -1206,7 +1306,11 @@ Bool ActionManager::canStealCashViaHacking( const Object *obj, const Object *obj //If the enemy unit is stealthed and not detected, then we can't attack it! if( objectToHack->testStatus( OBJECT_STATUS_STEALTHED ) && - !objectToHack->testStatus( OBJECT_STATUS_DETECTED ) ) + !objectToHack->testStatus( OBJECT_STATUS_DETECTED ) +#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) + && !objectToHack->testStatus( OBJECT_STATUS_DISGUISED ) +#endif + ) { return FALSE; } @@ -1278,7 +1382,11 @@ Bool ActionManager::canDisableBuildingViaHacking( const Object *obj, const Objec //If the enemy unit is stealthed and not detected, then we can't attack it! if( objectToHack->testStatus( OBJECT_STATUS_STEALTHED ) && - !objectToHack->testStatus( OBJECT_STATUS_DETECTED ) ) + !objectToHack->testStatus( OBJECT_STATUS_DETECTED ) +#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) + && !objectToHack->testStatus( OBJECT_STATUS_DISGUISED ) +#endif + ) { return FALSE; } @@ -1333,10 +1441,16 @@ Bool ActionManager::canSnipeVehicle( const Object *obj, const Object *objectToSn return FALSE; } + //Can't be a drone type. + if( objectToSnipe->isKindOf( KINDOF_DRONE ) ) + { + return FALSE; + } + //Make sure object is not flying if( objectToSnipe->isAirborneTarget() ) { - return false; + return FALSE; } //Make sure the vehicle is manned! @@ -1345,12 +1459,32 @@ Bool ActionManager::canSnipeVehicle( const Object *obj, const Object *objectToSn return FALSE; } + // TheSuperHackers @bugfix Caball009 04/09/2025 Disabled bikes may not have a rider to snipe. + ContainModuleInterface* contain = objectToSnipe->getContain(); + if ( contain && contain->isRiderChangeContain() && contain->getContainedItemsList()->empty() ) + { + return FALSE; + } + return TRUE; } return FALSE; } + + + +//------------------------------------------------------------------------------------------------- +inline Bool isPointOnMap( const Coord3D *testPos ) +{ + Region3D mapRegion; + TheTerrainLogic->getExtent( &mapRegion ); + return mapRegion.containsWithin( testPos->asCoord2D() ); + +} + + // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ Bool ActionManager::canDoSpecialPowerAtLocation( const Object *obj, const Coord3D *loc, CommandSourceType commandSource, const SpecialPowerTemplate *spTemplate, const Object *objectInWay, UnsignedInt commandOptions, Bool checkSourceRequirements ) @@ -1380,20 +1514,32 @@ Bool ActionManager::canDoSpecialPowerAtLocation( const Object *obj, const Coord3 switch( spTemplate->getSpecialPowerType() ) { case SPECIAL_PARADROP_AMERICA: + case INFA_SPECIAL_PARADROP_AMERICA: case SPECIAL_CRATE_DROP: + case SPECIAL_TANK_PARADROP: { if( TheTerrainLogic->isUnderwater( loc->x, loc->y ) ) return FALSE; } } - // Last check is shroudedness, if it is cared about + // Second check is shroudedness, if it is cared about switch( spTemplate->getSpecialPowerType() ) { case SPECIAL_DAISY_CUTTER: + case AIRF_SPECIAL_DAISY_CUTTER: case SPECIAL_PARADROP_AMERICA: + case SPECIAL_TANK_PARADROP: + case INFA_SPECIAL_PARADROP_AMERICA: case SPECIAL_CARPET_BOMB: + case SPECIAL_CHINA_CARPET_BOMB: + case SPECIAL_LEAFLET_DROP: + case EARLY_SPECIAL_LEAFLET_DROP: + case EARLY_SPECIAL_CHINA_CARPET_BOMB: + case AIRF_SPECIAL_CARPET_BOMB: + case SUPR_SPECIAL_CRUISE_MISSILE: case SPECIAL_CLUSTER_MINES: + case NUKE_SPECIAL_CLUSTER_MINES: case SPECIAL_EMP_PULSE: case SPECIAL_CRATE_DROP: case SPECIAL_NAPALM_STRIKE: @@ -1402,29 +1548,50 @@ Bool ActionManager::canDoSpecialPowerAtLocation( const Object *obj, const Coord3 case SPECIAL_TERROR_CELL: case SPECIAL_AMBUSH: case SPECIAL_NEUTRON_MISSILE: + case NUKE_SPECIAL_NEUTRON_MISSILE: + case SUPW_SPECIAL_NEUTRON_MISSILE: case SPECIAL_SCUD_STORM: #ifdef ALLOW_DEMORALIZE case SPECIAL_DEMORALIZE: #endif case SPECIAL_A10_THUNDERBOLT_STRIKE: + case AIRF_SPECIAL_A10_THUNDERBOLT_STRIKE: + case SPECIAL_SPECTRE_GUNSHIP: + case AIRF_SPECIAL_SPECTRE_GUNSHIP: case SPECIAL_REPAIR_VEHICLES: + case EARLY_SPECIAL_REPAIR_VEHICLES: + case SPECIAL_GPS_SCRAMBLER: + case SLTH_SPECIAL_GPS_SCRAMBLER: case SPECIAL_ARTILLERY_BARRAGE: + case SPECIAL_FRENZY: + case EARLY_SPECIAL_FRENZY: case SPECIAL_PARTICLE_UPLINK_CANNON: + case SUPW_SPECIAL_PARTICLE_UPLINK_CANNON: + case LAZR_SPECIAL_PARTICLE_UPLINK_CANNON: case SPECIAL_CLEANUP_AREA: + case SPECIAL_BATTLESHIP_BOMBARDMENT: //Don't allow "damaging" special powers in shrouded areas, but Fogged are okay. return ThePartitionManager->getShroudStatusForPlayer( obj->getControllingPlayer()->getPlayerIndex(), loc ) != CELLSHROUD_SHROUDED; case SPECIAL_SPY_SATELLITE: case SPECIAL_RADAR_VAN_SCAN: case SPECIAL_SPY_DRONE: - case SPECIAL_LAUNCH_BAIKONUR_ROCKET: + case SPECIAL_HELIX_NAPALM_BOMB: +#if RTS_GENERALS && RETAIL_COMPATIBLE_CRC //These specials can be used anywhere! - return true; + return TRUE; +#else + //These specials can be used anywhere! + return isPointOnMap( loc ); +#endif + case SPECIAL_LAUNCH_BAIKONUR_ROCKET: + return TRUE; //These special powers require object targets! case SPECIAL_MISSILE_DEFENDER_LASER_GUIDED_MISSILES: case SPECIAL_HACKER_DISABLE_BUILDING: case SPECIAL_TANKHUNTER_TNT_ATTACK: + case SPECIAL_BOOBY_TRAP: case SPECIAL_CASH_HACK: case SPECIAL_DEFECTOR: case SPECIAL_BLACKLOTUS_CAPTURE_BUILDING: @@ -1439,6 +1606,34 @@ Bool ActionManager::canDoSpecialPowerAtLocation( const Object *obj, const Coord3 case SPECIAL_CHANGE_BATTLE_PLANS: return false; } + + // TheSuperHackers @fix stephanmeesters 04/04/2026 Some special powers can spawn a building. + // To avoid cheating, verify that it is legal to place this building. + switch( spTemplate->getSpecialPowerType() ) + { + case SPECIAL_SNEAK_ATTACK: + { +#if RETAIL_COMPATIBLE_CRC + return ThePartitionManager->getShroudStatusForPlayer( obj->getControllingPlayer()->getPlayerIndex(), loc ) != CELLSHROUD_SHROUDED; +#else + const ThingTemplate* referenceThing = mod->getReferenceThingTemplate(); + if (!referenceThing) + return FALSE; + + const Real angle = referenceThing->getPlacementViewAngle(); + + return TheBuildAssistant->isLocationLegalToBuild( + loc, referenceThing, angle, + BuildAssistant::USE_QUICK_PATHFIND | + BuildAssistant::TERRAIN_RESTRICTIONS | + BuildAssistant::CLEAR_PATH | + BuildAssistant::NO_OBJECT_OVERLAP | + BuildAssistant::SHROUD_REVEALED | + BuildAssistant::IGNORE_STEALTHED, + obj, nullptr) == LBC_OK; +#endif + } + } } return false; } @@ -1484,6 +1679,13 @@ Bool ActionManager::canDoSpecialPowerAtObject( const Object *obj, const Object * case SPECIAL_CASH_BOUNTY: return false; + case SPECIAL_BATTLESHIP_BOMBARDMENT: + if( obj->getRelationship( target ) != ALLIES ) + { + return TRUE; + } + return FALSE; + case SPECIAL_TANKHUNTER_TNT_ATTACK: if( target->isKindOf( KINDOF_STRUCTURE ) || (target->isKindOf( KINDOF_VEHICLE ) && !target->isKindOf(KINDOF_AIRCRAFT)) ) { @@ -1491,6 +1693,16 @@ Bool ActionManager::canDoSpecialPowerAtObject( const Object *obj, const Object * } break; + case SPECIAL_BOOBY_TRAP: + { + // We can booby trap any building that is allied or neutral + if( target->isKindOf(KINDOF_STRUCTURE) && (r == NEUTRAL || r == ALLIES) ) + { + return TRUE; + } + return FALSE; + } + case SPECIAL_MISSILE_DEFENDER_LASER_GUIDED_MISSILES: //Can only use laser guided missiles on vehicles! if( target->isKindOf( KINDOF_VEHICLE ) && r == ENEMIES ) @@ -1546,7 +1758,10 @@ Bool ActionManager::canDoSpecialPowerAtObject( const Object *obj, const Object * break; case SPECIAL_DISGUISE_AS_VEHICLE: - if( target->isKindOf( KINDOF_VEHICLE ) && !target->isKindOf( KINDOF_AIRCRAFT ) && !target->isKindOf( KINDOF_BOAT ) ) + if( target->isKindOf( KINDOF_VEHICLE ) && + !target->isKindOf( KINDOF_AIRCRAFT ) && + !target->isKindOf( KINDOF_BOAT ) && + !target->isKindOf( KINDOF_CLIFF_JUMPER ) ) { //Don't allow it to disguise as another bomb truck -- that's just plain dumb. //if( target->getTemplate() != obj->getTemplate() ) @@ -1584,15 +1799,27 @@ Bool ActionManager::canDoSpecialPowerAtObject( const Object *obj, const Object * //These special powers require locations, not objects! case SPECIAL_DAISY_CUTTER: + case AIRF_SPECIAL_DAISY_CUTTER: case SPECIAL_PARADROP_AMERICA: + case SPECIAL_TANK_PARADROP: + case INFA_SPECIAL_PARADROP_AMERICA: case SPECIAL_CARPET_BOMB: + case SPECIAL_CHINA_CARPET_BOMB: + case SPECIAL_LEAFLET_DROP: + case EARLY_SPECIAL_LEAFLET_DROP: + case EARLY_SPECIAL_CHINA_CARPET_BOMB: + case AIRF_SPECIAL_CARPET_BOMB: + case SUPR_SPECIAL_CRUISE_MISSILE: case SPECIAL_CLUSTER_MINES: + case NUKE_SPECIAL_CLUSTER_MINES: case SPECIAL_EMP_PULSE: case SPECIAL_CRATE_DROP: case SPECIAL_NAPALM_STRIKE: case SPECIAL_TERROR_CELL: case SPECIAL_AMBUSH: case SPECIAL_NEUTRON_MISSILE: + case NUKE_SPECIAL_NEUTRON_MISSILE: + case SUPW_SPECIAL_NEUTRON_MISSILE: case SPECIAL_DETONATE_DIRTY_NUKE: case SPECIAL_BLACK_MARKET_NUKE: case SPECIAL_ANTHRAX_BOMB: @@ -1601,16 +1828,26 @@ Bool ActionManager::canDoSpecialPowerAtObject( const Object *obj, const Object * case SPECIAL_RADAR_VAN_SCAN: case SPECIAL_SCUD_STORM: case SPECIAL_A10_THUNDERBOLT_STRIKE: + case AIRF_SPECIAL_A10_THUNDERBOLT_STRIKE: + case SPECIAL_SPECTRE_GUNSHIP: + case AIRF_SPECIAL_SPECTRE_GUNSHIP: case SPECIAL_ARTILLERY_BARRAGE: + case SPECIAL_FRENZY: + case EARLY_SPECIAL_FRENZY: case SPECIAL_REPAIR_VEHICLES: + case EARLY_SPECIAL_REPAIR_VEHICLES: + case SPECIAL_GPS_SCRAMBLER: + case SLTH_SPECIAL_GPS_SCRAMBLER: case SPECIAL_PARTICLE_UPLINK_CANNON: case SPECIAL_CHANGE_BATTLE_PLANS: case SPECIAL_CLEANUP_AREA: case SPECIAL_LAUNCH_BAIKONUR_ROCKET: + case SPECIAL_SNEAK_ATTACK: return false; case SPECIAL_REMOTE_CHARGES: case SPECIAL_TIMED_CHARGES: + case SPECIAL_HELIX_NAPALM_BOMB: { if( target->isEffectivelyDead() || target->isKindOf( KINDOF_BRIDGE ) || @@ -1692,11 +1929,26 @@ Bool ActionManager::canDoSpecialPower( const Object *obj, const SpecialPowerTemp { case SPECIAL_MISSILE_DEFENDER_LASER_GUIDED_MISSILES: case SPECIAL_TANKHUNTER_TNT_ATTACK: + case SPECIAL_BOOBY_TRAP: case SPECIAL_DAISY_CUTTER: + case AIRF_SPECIAL_DAISY_CUTTER: case SPECIAL_PARADROP_AMERICA: + case SPECIAL_TANK_PARADROP: + case INFA_SPECIAL_PARADROP_AMERICA: + case SPECIAL_CARPET_BOMB: + case SPECIAL_CHINA_CARPET_BOMB: + case SPECIAL_LEAFLET_DROP: + case EARLY_SPECIAL_LEAFLET_DROP: + case EARLY_SPECIAL_CHINA_CARPET_BOMB: + case AIRF_SPECIAL_CARPET_BOMB: + case SUPR_SPECIAL_CRUISE_MISSILE: + case SPECIAL_CLUSTER_MINES: + case NUKE_SPECIAL_CLUSTER_MINES: case SPECIAL_NAPALM_STRIKE: case SPECIAL_TERROR_CELL: case SPECIAL_NEUTRON_MISSILE: + case NUKE_SPECIAL_NEUTRON_MISSILE: + case SUPW_SPECIAL_NEUTRON_MISSILE: case SPECIAL_BLACK_MARKET_NUKE: case SPECIAL_ANTHRAX_BOMB: case SPECIAL_SPY_SATELLITE: @@ -1705,17 +1957,30 @@ Bool ActionManager::canDoSpecialPower( const Object *obj, const SpecialPowerTemp case SPECIAL_TIMED_CHARGES: case SPECIAL_SCUD_STORM: case SPECIAL_A10_THUNDERBOLT_STRIKE: + case AIRF_SPECIAL_A10_THUNDERBOLT_STRIKE: + case SPECIAL_SPECTRE_GUNSHIP: + case AIRF_SPECIAL_SPECTRE_GUNSHIP: case SPECIAL_ARTILLERY_BARRAGE: + case SPECIAL_FRENZY: + case EARLY_SPECIAL_FRENZY: case SPECIAL_DISGUISE_AS_VEHICLE: case SPECIAL_REPAIR_VEHICLES: + case EARLY_SPECIAL_REPAIR_VEHICLES: + case SPECIAL_GPS_SCRAMBLER: + case SLTH_SPECIAL_GPS_SCRAMBLER: case SPECIAL_PARTICLE_UPLINK_CANNON: case SPECIAL_CASH_BOUNTY: case SPECIAL_CLEANUP_AREA: + case SPECIAL_HELIX_NAPALM_BOMB: + case SPECIAL_SNEAK_ATTACK: + case SPECIAL_EMP_PULSE: + case SPECIAL_CASH_HACK: //These all require object or location targets. return false; case SPECIAL_REMOTE_CHARGES: case SPECIAL_CIA_INTELLIGENCE: + case SPECIAL_COMMUNICATIONS_DOWNLOAD: case SPECIAL_DETONATE_DIRTY_NUKE: case SPECIAL_CHANGE_BATTLE_PLANS: case SPECIAL_LAUNCH_BAIKONUR_ROCKET: @@ -1751,22 +2016,31 @@ Bool ActionManager::canFireWeaponAtObject( const Object *obj, const Object *targ //Sanity check if( obj == nullptr || target == nullptr ) { - return false; + return FALSE; } //Make sure we have the right weapon. Weapon *weapon = obj->getWeaponInWeaponSlot( slot ); if( !weapon ) { - return false; + return FALSE; } - //if( weapon->getDamageType() == DAMAGE_KILLPILOT ) - //{ - // return canSnipeVehicle( obj, target, commandSource ); - //} + Bool sniper = FALSE; + if( weapon->getDamageType() == DAMAGE_KILLPILOT ) + { + if( !canSnipeVehicle( obj, target, commandSource ) ) + { + return FALSE; + } + sniper = TRUE; + } - CanAttackResult result = obj->getAbleToAttackSpecificObject( ATTACK_NEW_TARGET, target, commandSource ); + CanAttackResult result; + if( sniper ) + result = obj->getAbleToAttackSpecificObject( ATTACK_NEW_TARGET, target, commandSource, slot ); + else + result = obj->getAbleToAttackSpecificObject( ATTACK_NEW_TARGET, target, commandSource ); if( result == ATTACKRESULT_POSSIBLE || result == ATTACKRESULT_POSSIBLE_AFTER_MOVING ) { diff --git a/Generals/Code/GameEngine/Source/Common/RTS/Energy.cpp b/Generals/Code/GameEngine/Source/Common/RTS/Energy.cpp index de7b6758919..32b5952aa4c 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/Energy.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/Energy.cpp @@ -49,6 +49,8 @@ #include "Common/PlayerList.h" #include "Common/ThingTemplate.h" #include "Common/Xfer.h" + +#include "GameLogic/GameLogic.h" #include "GameLogic/Object.h" @@ -58,11 +60,17 @@ Energy::Energy() m_energyProduction = 0; m_energyConsumption = 0; m_owner = nullptr; + m_powerSabotagedTillFrame = 0; } //----------------------------------------------------------------------------- Int Energy::getProduction() const { + if( TheGameLogic->getFrame() < m_powerSabotagedTillFrame ) + { + //Power sabotaged, therefore no power. + return 0; + } return m_energyProduction; } @@ -71,6 +79,12 @@ Real Energy::getEnergySupplyRatio() const { DEBUG_ASSERTCRASH(m_energyProduction >= 0 && m_energyConsumption >= 0, ("neg Energy numbers")); + if( TheGameLogic->getFrame() < m_powerSabotagedTillFrame ) + { + //Power sabotaged, therefore no power, no ratio. + return 0.0f; + } + if (m_energyConsumption == 0) return (Real)m_energyProduction; @@ -80,6 +94,11 @@ Real Energy::getEnergySupplyRatio() const //------------------------------------------------------------------------------------------------- Bool Energy::hasSufficientPower() const { + if( TheGameLogic->getFrame() < m_powerSabotagedTillFrame ) + { + //Power sabotaged, therefore no power. + return FALSE; + } return m_energyProduction >= m_energyConsumption; } @@ -243,13 +262,19 @@ void Energy::crc( Xfer *xfer ) // ------------------------------------------------------------------------------------------------ /** Xfer method * Version Info: - * 1: Initial version */ + * 1: Initial version + * 2: Stop saving production and consumption + * 3: Added m_powerSabotagedTillFrame (Added in Zero Hour) */ // ------------------------------------------------------------------------------------------------ void Energy::xfer( Xfer *xfer ) { // version +#if RTS_GENERALS && RETAIL_COMPATIBLE_XFER_SAVE XferVersion currentVersion = 2; +#else + XferVersion currentVersion = 3; +#endif XferVersion version = currentVersion; xfer->xferVersion( &version, currentVersion ); @@ -271,6 +296,12 @@ void Energy::xfer( Xfer *xfer ) xfer->xferInt( &owningPlayerIndex ); m_owner = ThePlayerList->getNthPlayer( owningPlayerIndex ); + //Sabotage + if( version >= 3 ) + { + xfer->xferUnsignedInt( &m_powerSabotagedTillFrame ); + } + } // ------------------------------------------------------------------------------------------------ diff --git a/Generals/Code/GameEngine/Source/Common/RTS/Money.cpp b/Generals/Code/GameEngine/Source/Common/RTS/Money.cpp index 4934c80ea6f..d321f3193f4 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/Money.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/Money.cpp @@ -96,6 +96,15 @@ void Money::deposit(UnsignedInt amountToDeposit, Bool playSound, Bool trackIncom } m_money += amountToDeposit; + + if( amountToDeposit > 0 ) + { + Player *player = ThePlayerList->getNthPlayer( m_playerIndex ); + if( player ) + { + player->getAcademyStats()->recordIncome(); + } + } } // ------------------------------------------------------------------------------------------------ diff --git a/Generals/Code/GameEngine/Source/Common/RTS/Player.cpp b/Generals/Code/GameEngine/Source/Common/RTS/Player.cpp index 454fbdfd430..58c1fc52a1f 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/Player.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/Player.cpp @@ -319,7 +319,9 @@ Player::Player( Int playerIndex ) m_searchAndDestroyBattlePlans = 0; m_tunnelSystem = nullptr; m_playerTemplate = nullptr; +#if RTS_GENERALS m_visionSpiedMask = PLAYERMASK_NONE; +#endif m_battlePlanBonuses = nullptr; m_skillPointsModifier = 1.0f; m_canBuildUnits = TRUE; @@ -330,6 +332,7 @@ Player::Player( Int playerIndex ) m_rankLevel = 0; m_sciencePurchasePoints = 0; m_side = nullptr; + m_baseSide = nullptr; m_skillPoints = 0; Int i; m_upgradeList = nullptr; @@ -340,7 +343,9 @@ Player::Player( Int playerIndex ) for (i = 0; i < MAX_PLAYER_COUNT; ++i) { m_attackedBy[i] = false; +#if RTS_GENERALS m_visionSpiedBy[i] = 0; +#endif } m_attackedFrame = 0; @@ -418,6 +423,7 @@ void Player::init(const PlayerTemplate* pt) if (pt) { m_side = pt->getSide(); + m_baseSide = pt->getBaseSide(); m_productionCostChanges = pt->getProductionCostChanges(); m_productionTimeChanges = pt->getProductionTimeChanges(); m_productionVeterancyLevels = pt->getProductionVeterancyLevels(); @@ -455,6 +461,7 @@ void Player::init(const PlayerTemplate* pt) { // no player template? must be the neutral player! m_side = ""; + m_baseSide = ""; m_productionCostChanges.clear(); m_productionTimeChanges.clear(); m_productionVeterancyLevels.clear(); @@ -490,6 +497,8 @@ void Player::init(const PlayerTemplate* pt) deleteInstance(tof); } + getAcademyStats()->init( this ); + //Always off at the beginning of a game! Only GameLogic::update has //the power to turn it on. Don't want to cause desyncs! m_logicalRetaliationModeEnabled = FALSE; @@ -669,18 +678,52 @@ void Player::update() m_ai->update(); // Allow the teams this player owns to update themselves. - - for (PlayerTeamList::iterator it = m_playerTeamPrototypes.begin(); it != m_playerTeamPrototypes.end(); ++it) { - for (DLINK_ITERATOR iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance()) { + for( PlayerTeamList::iterator it = m_playerTeamPrototypes.begin(); it != m_playerTeamPrototypes.end(); ++it ) + { + for( DLINK_ITERATOR iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance() ) + { Team *team = iter.cur(); - if (!team) { + if( !team ) + { continue; } - team->updateGenericScripts(); } } + if( m_energy.getPowerSabotagedTillFrame() != 0 && TheGameLogic->getFrame() > m_energy.getPowerSabotagedTillFrame() ) + { + m_energy.setPowerSabotagedTillFrame( 0 ); //Tells us we're no longer sabotaged for above check. + onPowerBrownOutChange( !m_energy.hasSufficientPower() ); + } + + //Update the academy stats (this only checks applicable things that require a polling method) + getAcademyStats()->update(); + +#if !(RTS_GENERALS && (RETAIL_COMPATIBLE_CRC || RETAIL_COMPATIBLE_NETWORKING)) + //Kris: August 25, 2003 (DAY OF CODE LOCK -- NO NEW FEATURES, REALLY!) + if( ThePlayerList->getLocalPlayer() == this ) + { + UnsignedInt now = TheGameLogic->getFrame(); + //Only check and post the message once every second so we don't spam the message stream to account for lag. + if( now % LOGICFRAMES_PER_SECOND == 0 ) + { + if( TheGlobalData->m_clientRetaliationModeEnabled != isLogicalRetaliationModeEnabled() ) + { + //Post a logical message that will switch the retaliation mode on or off. + GameMessage *msg = TheMessageStream->appendMessage( GameMessage::MSG_ENABLE_RETALIATION_MODE ); + if( msg ) + { +#if RETAIL_COMPATIBLE_CRC + msg->appendIntegerArgument( getPlayerIndex() ); +#endif + msg->appendBooleanArgument( TheGlobalData->m_clientRetaliationModeEnabled ); + } + } + } + } +#endif + #if !(RETAIL_COMPATIBLE_CRC || PRESERVE_TUNNEL_HEAL_STACKING) // TheSuperHackers @bugfix Stubbjax 26/09/2025 The Tunnel System now heals // all units once per frame instead of once per frame per Tunnel Network. @@ -846,14 +889,17 @@ void Player::initFromDict(const Dict* d) } Int diffInt = d->getInt(TheKey_skirmishDifficulty, &exists); GameDifficulty difficulty = TheScriptEngine->getGlobalDifficulty(); - if (exists) { + if (exists) + { difficulty = (GameDifficulty) diffInt; } - if (m_ai) { + if (m_ai) + { m_ai->setAIDifficulty(difficulty); } - if (!found) { + if (!found) + { DEBUG_CRASH(("Could not find skirmish player for side %s", mySide.str())); } else { m_playerName = qualTemplatePlayerName; @@ -948,9 +994,13 @@ void Player::initFromDict(const Dict* d) for ( i = 0; i < MAX_PLAYER_COUNT; ++i ) // For now, it has been decided to just fix this one. Dear god me must reset. { m_attackedBy[i] = false; +#if RTS_GENERALS m_visionSpiedBy[i] = 0; +#endif } +#if RTS_GENERALS m_visionSpiedMask = PLAYERMASK_NONE; +#endif Int c = d->getInt(TheKey_playerColor, &exists); if (exists) @@ -1064,7 +1114,9 @@ void Player::becomingLocalPlayer(Bool yes) Drawable *draw = object->getDrawable(); if( draw ) { - StealthUpdate *update = object->getStealth(); + + StealthUpdate *update = object->getStealth(); + if( update && update->isDisguised() ) { Player *disguisedPlayer = ThePlayerList->getNthPlayer( update->getDisguisedPlayerIndex() ); @@ -1097,6 +1149,9 @@ void Player::becomingLocalPlayer(Bool yes) } deleteInstance(iter); } + + if( TheControlBar ) + TheControlBar->markUIDirty(); } else { @@ -1117,11 +1172,13 @@ Bool Player::isSkirmishAIPlayer() /** * Find a good spot to fire a superweapon. */ -void Player::computeSuperweaponTarget(const SpecialPowerTemplate *power, Coord3D *retPos, Int playerNdx, Real weaponRadius) +Bool Player::computeSuperweaponTarget(const SpecialPowerTemplate *power, Coord3D *retPos, Int playerNdx, Real weaponRadius) { if (m_ai) { - m_ai->computeSuperweaponTarget(power, retPos, playerNdx, weaponRadius); + return m_ai->computeSuperweaponTarget(power, retPos, playerNdx, weaponRadius); } + + return FALSE; } //------------------------------------------------------------------------------------------------- @@ -1615,6 +1672,7 @@ void Player::onStructureConstructionComplete( Object *builder, Object *structure // This object may require us to play some EVA sounds. Player *localPlayer = ThePlayerList->getLocalPlayer(); +#if RTS_GENERALS if (localPlayer == structure->getControllingPlayer() || localPlayer->getRelationship(structure->getTeam()) != ENEMIES) return; @@ -1627,7 +1685,63 @@ void Player::onStructureConstructionComplete( Object *builder, Object *structure if (structure->hasSpecialPower(SPECIAL_SCUD_STORM)) TheEva->setShouldPlay(EVA_SuperweaponDetected_ScudStorm); +#else + if( structure->hasSpecialPower( SPECIAL_PARTICLE_UPLINK_CANNON ) || + structure->hasSpecialPower( SUPW_SPECIAL_PARTICLE_UPLINK_CANNON ) || + structure->hasSpecialPower( LAZR_SPECIAL_PARTICLE_UPLINK_CANNON ) ) + { + if ( localPlayer == structure->getControllingPlayer() ) + { + TheEva->setShouldPlay(EVA_SuperweaponDetected_Own_ParticleCannon); + } + else if ( localPlayer->getRelationship(structure->getTeam()) != ENEMIES ) + { + // Note: treating NEUTRAL as ally. Is this correct? + TheEva->setShouldPlay(EVA_SuperweaponDetected_Ally_ParticleCannon); + } + else + { + TheEva->setShouldPlay(EVA_SuperweaponDetected_Enemy_ParticleCannon); + } + } + + if( structure->hasSpecialPower( SPECIAL_NEUTRON_MISSILE ) || + structure->hasSpecialPower( NUKE_SPECIAL_NEUTRON_MISSILE ) || + structure->hasSpecialPower( SUPW_SPECIAL_NEUTRON_MISSILE ) ) + { + if ( localPlayer == structure->getControllingPlayer() ) + { + TheEva->setShouldPlay(EVA_SuperweaponDetected_Own_Nuke); + } + else if ( localPlayer->getRelationship(structure->getTeam()) != ENEMIES ) + { + // Note: treating NEUTRAL as ally. Is this correct? + TheEva->setShouldPlay(EVA_SuperweaponDetected_Ally_Nuke); + } + else + { + TheEva->setShouldPlay(EVA_SuperweaponDetected_Enemy_Nuke); + } + } + + if (structure->hasSpecialPower(SPECIAL_SCUD_STORM)) + { + if ( localPlayer == structure->getControllingPlayer() ) + { + TheEva->setShouldPlay(EVA_SuperweaponDetected_Own_ScudStorm); + } + else if ( localPlayer->getRelationship(structure->getTeam()) != ENEMIES ) + { + // Note: treating NEUTRAL as ally. Is this correct? + TheEva->setShouldPlay(EVA_SuperweaponDetected_Ally_ScudStorm); + } + else + { + TheEva->setShouldPlay(EVA_SuperweaponDetected_Enemy_ScudStorm); + } + } +#endif } //============================================================================= @@ -2248,9 +2362,19 @@ void Player::setUnitsShouldIdleOrResume(Bool idle) } } +//------------------------------------------------------------------------------- +void sellBuildings( Object *obj, void *userData ) +{ + if( obj->isFactionStructure() || obj->isKindOf( KINDOF_COMMANDCENTER ) || obj->isKindOf( KINDOF_FS_POWER ) ) + { + TheBuildAssistant->sellObject( obj ); + } +} + //============================================================================= void Player::sellEverythingUnderTheSun() { +#if RTS_GENERALS && RETAIL_COMPATIBLE_CRC for (PlayerTeamList::iterator it = m_playerTeamPrototypes.begin(); it != m_playerTeamPrototypes.end(); ++it) { for (DLINK_ITERATOR iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance()) { @@ -2270,6 +2394,9 @@ void Player::sellEverythingUnderTheSun() } } } +#else + iterateObjects( sellBuildings, nullptr ); +#endif } @@ -2336,6 +2463,15 @@ void Player::buildBySupplies(Int minimumCash, const AsciiString &thingName) } } +//============================================================================= +void Player::buildSpecificBuildingNearestTeam( const AsciiString &thingName, const Team *team ) +{ + if( m_ai ) + { + m_ai->buildSpecificBuildingNearestTeam( thingName, team ); + } +} + //============================================================================= void Player::buildUpgrade( const AsciiString &upgrade) { @@ -2355,6 +2491,20 @@ void Player::recruitSpecificTeam( TeamPrototype *teamProto, Real recruitRadius) } } + +//============================================================================= +// Calculates the closest construction zone location based on a template. Gets plassed to aiPlayer +//============================================================================= +Bool Player::calcClosestConstructionZoneLocation( const ThingTemplate *constructTemplate, Coord3D *location ) +{ + if( m_ai ) + { + return m_ai->calcClosestConstructionZoneLocation( constructTemplate, location ); + } + + return FALSE; +} + //============================================================================= void Player::doBountyForKill(const Object* killer, const Object* victim) { @@ -2541,6 +2691,14 @@ Bool Player::attemptToPurchaseScience(ScienceType science) Int cost = TheScienceStore->getSciencePurchaseCost(science); addSciencePurchasePoints(-cost); addScience(science); + + getAcademyStats()->recordGeneralsPointsSpent( cost ); + + if( ThePlayerList->getLocalPlayer() == this ) + { + TheControlBar->markUIDirty(); + } + return true; } @@ -2872,6 +3030,12 @@ Bool Player::canBuild(const ThingTemplate *tmplate) const } +#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) + if ( !canBuildMoreOfType( tmplate ) ) + return false; +#endif + + return true; } @@ -2990,6 +3154,11 @@ Upgrade *Player::addUpgrade( const UpgradeTemplate *upgradeTemplate, UpgradeStat onUpgradeCompleted( upgradeTemplate ); } + if( ThePlayerList->getLocalPlayer() == this ) + { + TheControlBar->markUIDirty(); + } + return u; } @@ -3052,6 +3221,11 @@ void Player::removeUpgrade( const UpgradeTemplate *upgradeTemplate ) onUpgradeRemoved(); deleteInstance(upgrade); + + if( ThePlayerList->getLocalPlayer() == this ) + { + TheControlBar->markUIDirty(); + } } } @@ -3617,9 +3791,16 @@ void Player::processSelectTeamGameMessage(Int hotkeyNum) { const VecObjectPtr& objectList = m_squads[hotkeyNum]->getLiveObjects(); Int numObjs = objectList.size(); - for (Int i = 0; i < numObjs; ++i) { + for (Int i = 0; i < numObjs; ++i) + { m_currentSelection->addObject(objectList[i]); } + + if( numObjs > 0 ) + { + getAcademyStats()->recordControlGroupsUsed(); + } + } //------------------------------------------------------------------------------------------------- @@ -3820,6 +4001,7 @@ Bool Player::getAttackedBy( Int playerNdx ) const return m_attackedBy[playerNdx]; } +#if RTS_GENERALS // ------------------------------------------------------------------------------------------------ static void callHandleShroud( Object *obj, void * ) { @@ -3870,6 +4052,37 @@ PlayerMaskType Player::getVisionSpiedMask() const { return m_visionSpiedMask; } +#else +// ------------------------------------------------------------------------------------------------ +// Little wrapper function so I can use it in iterateObjects, which is cool. +struct VisionSpiedStruct +{ + Bool setting; + KindOfMaskType whichUnits; + PlayerIndex byWhom; +}; + +static void iterator_setUnitsVisionSpied( Object *obj, void * voidData) +{ + VisionSpiedStruct *data = (VisionSpiedStruct *)voidData; + + // I feel I have to disapprove of the naming of this gathering of cell functions. It is called by death, + // alliance change, containment, spy change, and dynamic view range as well as partition cell change. + if( obj && obj->isAnyKindOf(data->whichUnits) ) + obj->setVisionSpied(data->setting, data->byWhom); +} + +// ------------------------------------------------------------------------------------------------ +void Player::setUnitsVisionSpied( Bool setting, KindOfMaskType whichUnits, PlayerIndex byWhom ) +{ + VisionSpiedStruct data; + data.setting = setting; + data.whichUnits = whichUnits; + data.byWhom = byWhom; + // Being spied is now a property of the unit, not us, since we can spy only a portion of the enemy. + iterateObjects( iterator_setUnitsVisionSpied, &data ); +} +#endif // ------------------------------------------------------------------------------------------------ Bool Player::isPlayerObserver() const @@ -3918,9 +4131,6 @@ void Player::crc( Xfer *xfer ) m_battlePlanBonuses->m_invalidKindOf.xfer(xfer); } - // People have reported memory hacking their points. That would work since - // buttons are authoritative, and these points just unhided buttons. - // Same cheat principle as pulling NeedScience off your Generals buttons. xfer->xferInt( &m_skillPoints ); xfer->xferInt( &m_sciencePurchasePoints ); @@ -4285,11 +4495,13 @@ void Player::xfer( Xfer *xfer ) // attacked by xfer->xferUser( m_attackedBy, sizeof( Bool ) * MAX_PLAYER_COUNT ); +#if RTS_GENERALS // vision spied by xfer->xferUser( m_visionSpiedBy, sizeof( Int ) * MAX_PLAYER_COUNT ); // vision spied by mask xfer->xferUser( &m_visionSpiedMask, sizeof( PlayerMaskType ) ); +#endif // cash bounty percent xfer->xferReal( &m_cashBountyPercent ); @@ -4297,11 +4509,6 @@ void Player::xfer( Xfer *xfer ) // score keeper xfer->xferSnapshot( &m_scoreKeeper ); - - - - - // size of and data for kindof percent production change list UnsignedShort percentProductionChangeCount = m_kindOfPercentProductionChangeList.size(); xfer->xferUnsignedShort( &percentProductionChangeCount ); diff --git a/Generals/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp b/Generals/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp index 4f9318e342d..446a48c266c 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp @@ -83,14 +83,17 @@ void ProductionPrerequisite::resolveNames() // sub-templates), which is what we want ... we conceptually only have one // template for any given thing, it's only the *data* that is overridden // - m_prereqUnits[i].unit = TheThingFactory->findTemplate(m_prereqUnits[i].name); // might be null + if( m_prereqUnits[ i ].name.isNotEmpty() ) + { + m_prereqUnits[i].unit = TheThingFactory->findTemplate(m_prereqUnits[i].name); // might be null - /** @todo for now removing this assert until we can completely remove - the GDF stuff, the problem is that some INI files refer to GDF names, and they - aren't yet loaded in the world builder but will all go away later anyway etc */ - DEBUG_ASSERTCRASH(m_prereqUnits[i].unit,("could not find prereq %s",m_prereqUnits[i].name.str())); + /** @todo for now removing this assert until we can completely remove + the GDF stuff, the problem is that some INI files refer to GDF names, and they + aren't yet loaded in the world builder but will all go away later anyway etc */ + DEBUG_ASSERTCRASH(m_prereqUnits[i].unit,("could not find prereq %s",m_prereqUnits[i].name.str())); - m_prereqUnits[i].name.clear(); // we're done with it + m_prereqUnits[i].name.clear(); // we're done with it + } } diff --git a/Generals/Code/GameEngine/Source/Common/RTS/ResourceGatheringManager.cpp b/Generals/Code/GameEngine/Source/Common/RTS/ResourceGatheringManager.cpp index 26b2b16608a..b7433ae5b7f 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/ResourceGatheringManager.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/ResourceGatheringManager.cpp @@ -117,7 +117,7 @@ static Real computeRelativeCost( Object *queryObject, Object *destObject, Real * return FLT_MAX; if( !TheActionManager->canTransferSuppliesAt(queryObject, destObject) ) - return FLT_MAX;// Handles emptyness and alliances + return FLT_MAX;// Handles emptiness and alliances DockUpdateInterface *dockInterface = destObject->getDockUpdateInterface(); if( !dockInterface->isClearToApproach( queryObject ) ) diff --git a/Generals/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp b/Generals/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp index 3b07f7af930..11160ede478 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp @@ -83,6 +83,7 @@ const char* const SpecialPowerMaskType::s_bitNameList[] = "SPECIAL_MISSILE_DEFENDER_LASER_GUIDED_MISSILES", "SPECIAL_REMOTE_CHARGES", "SPECIAL_TIMED_CHARGES", + "SPECIAL_HELIX_NAPALM_BOMB", // Added in Zero Hour "SPECIAL_HACKER_DISABLE_BUILDING", "SPECIAL_TANKHUNTER_TNT_ATTACK", "SPECIAL_BLACKLOTUS_CAPTURE_BUILDING", @@ -92,6 +93,7 @@ const char* const SpecialPowerMaskType::s_bitNameList[] = "SPECIAL_RADAR_VAN_SCAN", "SPECIAL_SPY_DRONE", "SPECIAL_DISGUISE_AS_VEHICLE", + "SPECIAL_BOOBY_TRAP", // Added in Zero Hour "SPECIAL_REPAIR_VEHICLES", "SPECIAL_PARTICLE_UPLINK_CANNON", "SPECIAL_CASH_BOUNTY", @@ -99,6 +101,34 @@ const char* const SpecialPowerMaskType::s_bitNameList[] = "SPECIAL_CIA_INTELLIGENCE", "SPECIAL_CLEANUP_AREA", "SPECIAL_LAUNCH_BAIKONUR_ROCKET", + // TheSuperHackers @info Added in Zero Hour: + "SPECIAL_SPECTRE_GUNSHIP", + "SPECIAL_GPS_SCRAMBLER", + "SPECIAL_FRENZY", + "SPECIAL_SNEAK_ATTACK", + + "SPECIAL_CHINA_CARPET_BOMB", + "EARLY_SPECIAL_CHINA_CARPET_BOMB", + "SPECIAL_LEAFLET_DROP", + "EARLY_SPECIAL_LEAFLET_DROP", + "EARLY_SPECIAL_FRENZY", + "SPECIAL_COMMUNICATIONS_DOWNLOAD", + "EARLY_SPECIAL_REPAIR_VEHICLES", + "SPECIAL_TANK_PARADROP", + "SUPW_SPECIAL_PARTICLE_UPLINK_CANNON", + "AIRF_SPECIAL_DAISY_CUTTER", + "NUKE_SPECIAL_CLUSTER_MINES", + "NUKE_SPECIAL_NEUTRON_MISSILE", + "AIRF_SPECIAL_A10_THUNDERBOLT_STRIKE", + "AIRF_SPECIAL_SPECTRE_GUNSHIP", + "INFA_SPECIAL_PARADROP_AMERICA", + "SLTH_SPECIAL_GPS_SCRAMBLER", + "AIRF_SPECIAL_CARPET_BOMB", + "SUPR_SPECIAL_CRUISE_MISSILE", + "LAZR_SPECIAL_PARTICLE_UPLINK_CANNON", + "SUPW_SPECIAL_NEUTRON_MISSILE", + + "SPECIAL_BATTLESHIP_BOMBARDMENT", nullptr }; diff --git a/Generals/Code/GameEngine/Source/Common/RTS/Team.cpp b/Generals/Code/GameEngine/Source/Common/RTS/Team.cpp index afe6402d0dc..4c58ee8d5ab 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/Team.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/Team.cpp @@ -1318,6 +1318,7 @@ Team::Team(TeamPrototype *proto, TeamID id ) : { m_created = FALSE; m_commonAttackTarget = INVALID_ID; + // allocate new relation map pools m_playerRelations = newInstance(PlayerRelationMap); m_teamRelations = newInstance(TeamRelationMap); @@ -1521,7 +1522,11 @@ Object *Team::getTeamTargetObject() if (target) { //If the enemy unit is stealthed and not detected, then we can't attack it! if( target->testStatus( OBJECT_STATUS_STEALTHED ) && - !target->testStatus( OBJECT_STATUS_DETECTED ) ) + !target->testStatus( OBJECT_STATUS_DETECTED ) +#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) + && !target->testStatus( OBJECT_STATUS_DISGUISED ) +#endif + ) { target = nullptr; } @@ -1532,6 +1537,13 @@ Object *Team::getTeamTargetObject() if (target && target->getContainedBy()) { target = nullptr; // target entered a building or vehicle, so stop targeting. } +#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) + if (target && target->isKindOf(KINDOF_AIRCRAFT)) { + // It is just generally bad to have an aircraft as the team target. + // Let team members acquire aircraft individually. jba. [8/27/2003] + target = nullptr; + } +#endif if (target == nullptr) { m_commonAttackTarget = INVALID_ID; } @@ -2218,7 +2230,7 @@ Bool Team::someInsideSomeOutside(PolygonTrigger *pTrigger, UnsignedInt whichToCo return anyConsidered && anyInside && anyOutside; } -const Coord3D* Team::getEstimateTeamPosition() +const Coord3D* Team::getEstimateTeamPosition() const { // this doesn't actually calculate the team position, but rather estimates it by // returning the position of the first member of the team diff --git a/Generals/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp b/Generals/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp index a8561f39c36..98fa254c058 100644 --- a/Generals/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp +++ b/Generals/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp @@ -149,7 +149,11 @@ Object *TunnelTracker::getCurNemesis() if (target) { //If the enemy unit is stealthed and not detected, then we can't attack it! if( target->testStatus( OBJECT_STATUS_STEALTHED ) && - !target->testStatus( OBJECT_STATUS_DETECTED ) ) + !target->testStatus( OBJECT_STATUS_DETECTED ) +#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) + && !target->testStatus( OBJECT_STATUS_DISGUISED ) +#endif + ) { target = nullptr; } diff --git a/Generals/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp b/Generals/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp index 1421b406483..2a606d8c4ff 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/AI/AIPlayer.cpp @@ -1164,7 +1164,7 @@ void AIPlayer::onUnitProduced( Object *factory, Object *unit ) /** * Find a good spot to fire a superweapon. */ -void AIPlayer::computeSuperweaponTarget(const SpecialPowerTemplate *power, Coord3D *retPos, Int playerNdx, Real weaponRadius) +Bool AIPlayer::computeSuperweaponTarget(const SpecialPowerTemplate *power, Coord3D *retPos, Int playerNdx, Real weaponRadius) { Region2D bounds; @@ -1236,6 +1236,7 @@ void AIPlayer::computeSuperweaponTarget(const SpecialPowerTemplate *power, Coord } veryBestPos.z = TheTerrainLogic->getGroundHeight(veryBestPos.x, veryBestPos.y); *retPos = veryBestPos; + return cash > -1; } //---------------------------------------------------------------------------------------------------------- @@ -1881,6 +1882,213 @@ void AIPlayer::buildBySupplies(Int minimumCash, const AsciiString& thingName) } } +// ------------------------------------------------------------------------------------------------ +/** Calculates the closest construction zone location based on a template. */ +// ------------------------------------------------------------------------------------------------ +Bool AIPlayer::calcClosestConstructionZoneLocation( const ThingTemplate *constructTemplate, Coord3D *location ) +{ + if( !constructTemplate || !location ) + { + return FALSE; + } + + Bool success = FALSE; + + // offset back towards the base. + Coord2D offset; + offset.x = location->x - m_baseCenter.x; + offset.y = location->y - m_baseCenter.y; + offset.normalize(); + + Real angle = constructTemplate->getPlacementViewAngle(); + + // validate the the position to build at is valid + Bool valid=false; + Coord3D newPos = *location; + if( TheBuildAssistant->isLocationLegalToBuild( location, constructTemplate, angle, BuildAssistant::NO_OBJECT_OVERLAP, nullptr, m_player ) != LBC_OK ) + { + // Warn. + AsciiString bldgName = constructTemplate->getName(); + bldgName.concat(" - calcClosestConstructionZoneLocation unable to place. Attempting to adjust position."); + TheScriptEngine->AppendDebugMessage( bldgName, false ); + // try to fix. + Real posOffset; + // Wiggle it a little :) + for( posOffset = 0; posOffset < 2 * SUPPLY_CENTER_CLOSE_DIST; posOffset += 2 * PATHFIND_CELL_SIZE_F ) + { + Real offset = posOffset / 2; + Real xPos, yPos; + yPos = location->y - offset; + for( xPos = location->x - offset; xPos <= location->x + offset; xPos += PATHFIND_CELL_SIZE_F ) + { + newPos.x = xPos; + newPos.y = yPos; + valid = TheBuildAssistant->isLocationLegalToBuild( &newPos, constructTemplate, angle, + BuildAssistant::CLEAR_PATH | + BuildAssistant::TERRAIN_RESTRICTIONS | + BuildAssistant::NO_OBJECT_OVERLAP, + nullptr, m_player ) == LBC_OK; + if( valid ) + break; + + newPos.y = yPos + posOffset; + valid = TheBuildAssistant->isLocationLegalToBuild( &newPos, constructTemplate, angle, + BuildAssistant::CLEAR_PATH | + BuildAssistant::TERRAIN_RESTRICTIONS | + BuildAssistant::NO_OBJECT_OVERLAP, + nullptr, m_player ) == LBC_OK; + } + + if( valid ) + break; + + xPos = location->x - offset; + for( yPos = location->y - offset; yPos <= location->y + offset; yPos += PATHFIND_CELL_SIZE_F ) + { + newPos.x = xPos; + newPos.y = yPos; + valid = TheBuildAssistant->isLocationLegalToBuild( &newPos, constructTemplate, angle, + BuildAssistant::CLEAR_PATH | + BuildAssistant::TERRAIN_RESTRICTIONS | + BuildAssistant::NO_OBJECT_OVERLAP, + nullptr, m_player ) == LBC_OK; + if( valid ) + break; + + newPos.x = xPos + posOffset; + valid = TheBuildAssistant->isLocationLegalToBuild( &newPos, constructTemplate, angle, + BuildAssistant::CLEAR_PATH | + BuildAssistant::TERRAIN_RESTRICTIONS | + BuildAssistant::NO_OBJECT_OVERLAP, + nullptr, m_player ) == LBC_OK; + } + + if( valid ) + break; + } + } + if( valid ) + { + //We succeeded in calculating the best position. + location->set( newPos ); + success = TRUE; + } + else + { + //We failed to calculate a position, so zero out the position. + location->zero(); + success = FALSE; + } + + TheTerrainVisual->removeAllBibs(); // isLocationLegalToBuild adds bib feedback, turn it off. jba. + + return success; + +} + +// ------------------------------------------------------------------------------------------------ +/** Build a specific building nearest specified team. */ +// ------------------------------------------------------------------------------------------------ +void AIPlayer::buildSpecificBuildingNearestTeam( const AsciiString &thingName, const Team *team ) +{ + const ThingTemplate *tTemplate = TheThingFactory->findTemplate( thingName ); + + if( !tTemplate || !team ) + { + //Assert will already happen in the failed findTemplate call. + return; + } + + //From the team's location, find the most valid build location. + const Coord3D *location = team->getEstimateTeamPosition(); + if( !location ) + { + return; + } + + // offset back towards the base. + Coord2D offset; + offset.x = location->x - m_baseCenter.x; + offset.y = location->y - m_baseCenter.y; + offset.normalize(); + + Real angle = tTemplate->getPlacementViewAngle(); + + // validate the the position to build at is valid + Bool valid=false; + Coord3D newPos = *location; + if( TheBuildAssistant->isLocationLegalToBuild( location, tTemplate, angle, BuildAssistant::NO_OBJECT_OVERLAP, nullptr, m_player ) != LBC_OK ) + { + // Warn. + AsciiString bldgName = tTemplate->getName(); + bldgName.concat(" - buildSpecificBuildingNearestTeam unable to place. Attempting to adjust position."); + TheScriptEngine->AppendDebugMessage( bldgName, false ); + // try to fix. + Real posOffset; + // Wiggle it a little :) + for( posOffset = 0; posOffset < 2 * SUPPLY_CENTER_CLOSE_DIST; posOffset += 2 * PATHFIND_CELL_SIZE_F ) + { + Real offset = posOffset / 2; + Real xPos, yPos; + yPos = location->y-offset; + for( xPos = location->x - offset; xPos <= location->x + offset; xPos += PATHFIND_CELL_SIZE_F ) + { + newPos.x = xPos; + newPos.y = yPos; + valid = TheBuildAssistant->isLocationLegalToBuild( &newPos, tTemplate, angle, + BuildAssistant::CLEAR_PATH | + BuildAssistant::TERRAIN_RESTRICTIONS | + BuildAssistant::NO_OBJECT_OVERLAP, + nullptr, m_player ) == LBC_OK; + if( valid ) + break; + + newPos.y = yPos + posOffset; + valid = TheBuildAssistant->isLocationLegalToBuild( &newPos, tTemplate, angle, + BuildAssistant::CLEAR_PATH | + BuildAssistant::TERRAIN_RESTRICTIONS | + BuildAssistant::NO_OBJECT_OVERLAP, + nullptr, m_player ) == LBC_OK; + } + + if( valid ) + break; + + xPos = location->x - offset; + for( yPos = location->y - offset; yPos <= location->y + offset; yPos += PATHFIND_CELL_SIZE_F ) + { + newPos.x = xPos; + newPos.y = yPos; + valid = TheBuildAssistant->isLocationLegalToBuild( &newPos, tTemplate, angle, + BuildAssistant::CLEAR_PATH | + BuildAssistant::TERRAIN_RESTRICTIONS | + BuildAssistant::NO_OBJECT_OVERLAP, + nullptr, m_player ) == LBC_OK; + if( valid ) + break; + + newPos.x = xPos + posOffset; + valid = TheBuildAssistant->isLocationLegalToBuild( &newPos, tTemplate, angle, + BuildAssistant::CLEAR_PATH | + BuildAssistant::TERRAIN_RESTRICTIONS | + BuildAssistant::NO_OBJECT_OVERLAP, + nullptr, m_player ) == LBC_OK; + } + + if( valid ) + break; + } + } + if( valid ) + { + newPos.z = 0; // All build list locations are ground relative. + m_player->addToPriorityBuildList( thingName, &newPos, angle ); + } + + TheTerrainVisual->removeAllBibs(); // isLocationLegalToBuild adds bib feedback, turn it off. jba. + +} + // ------------------------------------------------------------------------------------------------ /** Find a supply center we haven't built a supply depot near yet. */ // ------------------------------------------------------------------------------------------------ diff --git a/Generals/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp b/Generals/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp index 8966011fafd..9a0cf884c34 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp @@ -1121,7 +1121,7 @@ Object * AISkirmishPlayer::findDozer( const Coord3D *pos ) /** * Find a good spot to fire a superweapon. */ -void AISkirmishPlayer::computeSuperweaponTarget(const SpecialPowerTemplate *power, Coord3D *retPos, Int playerNdx, Real weaponRadius) +Bool AISkirmishPlayer::computeSuperweaponTarget(const SpecialPowerTemplate *power, Coord3D *retPos, Int playerNdx, Real weaponRadius) { Region2D bounds; @@ -1159,9 +1159,9 @@ void AISkirmishPlayer::computeSuperweaponTarget(const SpecialPowerTemplate *powe retPos->x += offset.x; retPos->y += offset.y; retPos->z = TheTerrainLogic->getGroundHeight(retPos->x, retPos->y); - return; + return TRUE; } - AIPlayer::computeSuperweaponTarget(power, retPos, playerNdx, weaponRadius); + return AIPlayer::computeSuperweaponTarget(power, retPos, playerNdx, weaponRadius); } diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp index 67b3228fab7..e0d1a75286e 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/Object.cpp @@ -1354,7 +1354,7 @@ Bool Object::getAmmoPipShowingInfo(Int& numTotal, Int& numFull) const where we already know that isAbleToAttack() == true. so you should always call isAbleToAttack prior to calling this! (srj) */ -CanAttackResult Object::getAbleToAttackSpecificObject( AbleToAttackType t, const Object* target, CommandSourceType commandSource ) const +CanAttackResult Object::getAbleToAttackSpecificObject( AbleToAttackType t, const Object* target, CommandSourceType commandSource, WeaponSlotType specificSlot ) const { // NO! BAD! WRONG! // If we can't attack at all, then we cannot attack this @@ -1362,14 +1362,14 @@ CanAttackResult Object::getAbleToAttackSpecificObject( AbleToAttackType t, const // return FALSE; // Otherwise leave it up to our weapons. - return m_weaponSet.getAbleToAttackSpecificObject( t, this, target, commandSource ); + return m_weaponSet.getAbleToAttackSpecificObject( t, this, target, commandSource, specificSlot ); } //============================================================================= //Used for base defenses and otherwise stationary units to see if you can attack a position potentially out of range. -CanAttackResult Object::getAbleToUseWeaponAgainstTarget( AbleToAttackType attackType, const Object *victim, const Coord3D *pos, CommandSourceType commandSource ) const +CanAttackResult Object::getAbleToUseWeaponAgainstTarget( AbleToAttackType attackType, const Object *victim, const Coord3D *pos, CommandSourceType commandSource, WeaponSlotType specificSlot ) const { - return m_weaponSet.getAbleToUseWeaponAgainstTarget( attackType, this, victim, pos, commandSource ); + return m_weaponSet.getAbleToUseWeaponAgainstTarget( attackType, this, victim, pos, commandSource, specificSlot ); } diff --git a/Generals/Code/GameEngine/Source/GameLogic/Object/WeaponSet.cpp b/Generals/Code/GameEngine/Source/GameLogic/Object/WeaponSet.cpp index 6b17ce12b7d..9b0611abcba 100644 --- a/Generals/Code/GameEngine/Source/GameLogic/Object/WeaponSet.cpp +++ b/Generals/Code/GameEngine/Source/GameLogic/Object/WeaponSet.cpp @@ -478,7 +478,7 @@ Bool WeaponSet::isAnyWithinTargetPitch(const Object* obj, const Object* victim) } //------------------------------------------------------------------------------------------------- -CanAttackResult WeaponSet::getAbleToAttackSpecificObject( AbleToAttackType attackType, const Object* source, const Object* victim, CommandSourceType commandSource ) const +CanAttackResult WeaponSet::getAbleToAttackSpecificObject( AbleToAttackType attackType, const Object* source, const Object* victim, CommandSourceType commandSource, WeaponSlotType specificSlot ) const { // basic sanity checks. @@ -630,14 +630,14 @@ CanAttackResult WeaponSet::getAbleToAttackSpecificObject( AbleToAttackType attac } //Check if the shot itself is valid! - return getAbleToUseWeaponAgainstTarget( attackType, source, victim, victim->getPosition(), commandSource ); + return getAbleToUseWeaponAgainstTarget( attackType, source, victim, victim->getPosition(), commandSource, specificSlot ); } //------------------------------------------------------------------------------------------------- //This is formerly the 2nd half of getAbleToAttackSpecificObject //This function is responsible for determining if our object is physically capable of attacking the target and it //supports both victim or position. -CanAttackResult WeaponSet::getAbleToUseWeaponAgainstTarget( AbleToAttackType attackType, const Object *source, const Object *victim, const Coord3D *pos, CommandSourceType commandSource ) const +CanAttackResult WeaponSet::getAbleToUseWeaponAgainstTarget( AbleToAttackType attackType, const Object *source, const Object *victim, const Coord3D *pos, CommandSourceType commandSource, WeaponSlotType specificSlot ) const { //First determine if we are attacking an object or the ground and get the @@ -743,6 +743,11 @@ CanAttackResult WeaponSet::getAbleToUseWeaponAgainstTarget( AbleToAttackType att first = m_curWeapon; last = m_curWeapon; } + else if( specificSlot != (WeaponSlotType)-1 ) + { + first = specificSlot; + last = specificSlot; + } else { first = WEAPONSLOT_COUNT - 1; diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Player.h b/GeneralsMD/Code/GameEngine/Include/Common/Player.h index d8c7940bb66..35c2a845fd0 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/Player.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/Player.h @@ -562,7 +562,14 @@ class Player : public Snapshot Bool getUnitsShouldHunt() const { return m_unitsShouldHunt; } /// All of our units are new spied upon; they sight for the given enemy +#if RTS_GENERALS + void setUnitsVisionSpied( Bool setting, PlayerIndex byWhom ); + + /// This will be asked by units when they look to get extra people to sight for + PlayerMaskType getVisionSpiedMask() const; +#else void setUnitsVisionSpied( Bool setting, KindOfMaskType whichUnits, PlayerIndex byWhom ); +#endif /// Destroy all of the teams for this player, causing him to DIE. void killPlayer(); @@ -800,6 +807,10 @@ class Player : public Snapshot Bool m_attackedBy[MAX_PLAYER_COUNT]; ///< For each player, have they attacked me? UnsignedInt m_attackedFrame; ///< Last frame attacked. +#if RTS_GENERALS + Int m_visionSpiedBy[MAX_PLAYER_COUNT]; ///< Reference count of having units spied on by players. + PlayerMaskType m_visionSpiedMask; ///< For quick lookup and edge triggered maintenance +#endif Real m_cashBountyPercent; diff --git a/GeneralsMD/Code/GameEngine/Include/Common/SpecialPowerType.h b/GeneralsMD/Code/GameEngine/Include/Common/SpecialPowerType.h index 163f410ddb7..1581fae88fb 100644 --- a/GeneralsMD/Code/GameEngine/Include/Common/SpecialPowerType.h +++ b/GeneralsMD/Code/GameEngine/Include/Common/SpecialPowerType.h @@ -71,7 +71,7 @@ enum SpecialPowerType CPP_11(: Int) SPECIAL_MISSILE_DEFENDER_LASER_GUIDED_MISSILES, SPECIAL_REMOTE_CHARGES, SPECIAL_TIMED_CHARGES, - SPECIAL_HELIX_NAPALM_BOMB, + SPECIAL_HELIX_NAPALM_BOMB, // Added in Zero Hour SPECIAL_HACKER_DISABLE_BUILDING, SPECIAL_TANKHUNTER_TNT_ATTACK, SPECIAL_BLACKLOTUS_CAPTURE_BUILDING, @@ -81,7 +81,7 @@ enum SpecialPowerType CPP_11(: Int) SPECIAL_RADAR_VAN_SCAN, SPECIAL_SPY_DRONE, SPECIAL_DISGUISE_AS_VEHICLE, - SPECIAL_BOOBY_TRAP, + SPECIAL_BOOBY_TRAP, // Added in Zero Hour // don't forget to add new strings to SpecialPowerMaskType::s_bitNameList[] SPECIAL_REPAIR_VEHICLES, SPECIAL_PARTICLE_UPLINK_CANNON, @@ -92,6 +92,7 @@ enum SpecialPowerType CPP_11(: Int) // don't forget to add new strings to SpecialPowerMaskType::s_bitNameList[] SPECIAL_LAUNCH_BAIKONUR_ROCKET, + // TheSuperHackers @info Added in Zero Hour: SPECIAL_SPECTRE_GUNSHIP, SPECIAL_GPS_SCRAMBLER, diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp index 7015b24c4cd..9614462ad11 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp @@ -156,9 +156,11 @@ Bool ActionManager::canGetRepairedAt( const Object *obj, const Object *repairDes if( obj->isEffectivelyDead() ) return FALSE; +#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) // If I can't move, I can't get repaired if( !obj->isMobile() ) return FALSE; +#endif // nothing can be done with things that are under construction if( obj->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) || @@ -745,6 +747,7 @@ CanAttackResult ActionManager::getCanAttackObject( const Object *obj, const Obje CanAttackResult result = obj->getAbleToAttackSpecificObject( attackType, objectToAttack, commandSource ); if( result != ATTACKRESULT_NOT_POSSIBLE ) { +#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) //Kris: August 5, 2003 //Fix a case where the Demo_GLAInfantryWorker is able to attack using his passive bomb upgrade. We don't //want him to allow a visible attack cursor for the player. This code never checked for AutoChoosesSources @@ -767,6 +770,7 @@ CanAttackResult ActionManager::getCanAttackObject( const Object *obj, const Obje return ATTACKRESULT_NOT_POSSIBLE; } } +#endif if( result == ATTACKRESULT_INVALID_SHOT && obj->isKindOf( KINDOF_DOZER ) ) { @@ -1076,8 +1080,11 @@ Bool ActionManager::canCaptureBuilding( const Object *obj, const Object *objectT //If the enemy unit is stealthed and not detected, then we can't capture it! if( objectToCapture->testStatus( OBJECT_STATUS_STEALTHED ) && - !objectToCapture->testStatus( OBJECT_STATUS_DETECTED ) && - !objectToCapture->testStatus( OBJECT_STATUS_DISGUISED ) ) + !objectToCapture->testStatus( OBJECT_STATUS_DETECTED ) +#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) + && !objectToCapture->testStatus( OBJECT_STATUS_DISGUISED ) +#endif + ) { return FALSE; } @@ -1166,8 +1173,11 @@ Bool ActionManager::canDisableVehicleViaHacking( const Object *obj, const Object //If the enemy unit is stealthed and not detected, then we can't attack it! if( objectToHack->testStatus( OBJECT_STATUS_STEALTHED ) && - !objectToHack->testStatus( OBJECT_STATUS_DETECTED ) && - !objectToHack->testStatus( OBJECT_STATUS_DISGUISED ) ) + !objectToHack->testStatus( OBJECT_STATUS_DETECTED ) +#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) + && !objectToHack->testStatus( OBJECT_STATUS_DISGUISED ) +#endif + ) { return FALSE; } @@ -1296,8 +1306,11 @@ Bool ActionManager::canStealCashViaHacking( const Object *obj, const Object *obj //If the enemy unit is stealthed and not detected, then we can't attack it! if( objectToHack->testStatus( OBJECT_STATUS_STEALTHED ) && - !objectToHack->testStatus( OBJECT_STATUS_DETECTED ) && - !objectToHack->testStatus( OBJECT_STATUS_DISGUISED ) ) + !objectToHack->testStatus( OBJECT_STATUS_DETECTED ) +#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) + && !objectToHack->testStatus( OBJECT_STATUS_DISGUISED ) +#endif + ) { return FALSE; } @@ -1369,8 +1382,11 @@ Bool ActionManager::canDisableBuildingViaHacking( const Object *obj, const Objec //If the enemy unit is stealthed and not detected, then we can't attack it! if( objectToHack->testStatus( OBJECT_STATUS_STEALTHED ) && - !objectToHack->testStatus( OBJECT_STATUS_DETECTED ) && - !objectToHack->testStatus( OBJECT_STATUS_DISGUISED ) ) + !objectToHack->testStatus( OBJECT_STATUS_DETECTED ) +#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) + && !objectToHack->testStatus( OBJECT_STATUS_DISGUISED ) +#endif + ) { return FALSE; } @@ -1561,9 +1577,13 @@ Bool ActionManager::canDoSpecialPowerAtLocation( const Object *obj, const Coord3 case SPECIAL_RADAR_VAN_SCAN: case SPECIAL_SPY_DRONE: case SPECIAL_HELIX_NAPALM_BOMB: - +#if RTS_GENERALS && RETAIL_COMPATIBLE_CRC + //These specials can be used anywhere! + return TRUE; +#else //These specials can be used anywhere! return isPointOnMap( loc ); +#endif case SPECIAL_LAUNCH_BAIKONUR_ROCKET: return TRUE; diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Energy.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Energy.cpp index bc5d450ca07..0e92e828f7c 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Energy.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Energy.cpp @@ -262,13 +262,19 @@ void Energy::crc( Xfer *xfer ) // ------------------------------------------------------------------------------------------------ /** Xfer method * Version Info: - * 1: Initial version */ + * 1: Initial version + * 2: Stop saving production and consumption + * 3: Added m_powerSabotagedTillFrame (Added in Zero Hour) */ // ------------------------------------------------------------------------------------------------ void Energy::xfer( Xfer *xfer ) { // version +#if RTS_GENERALS && RETAIL_COMPATIBLE_XFER_SAVE + XferVersion currentVersion = 2; +#else XferVersion currentVersion = 3; +#endif XferVersion version = currentVersion; xfer->xferVersion( &version, currentVersion ); diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp index 9439759e534..cfde237d88d 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp @@ -319,6 +319,9 @@ Player::Player( Int playerIndex ) m_searchAndDestroyBattlePlans = 0; m_tunnelSystem = nullptr; m_playerTemplate = nullptr; +#if RTS_GENERALS + m_visionSpiedMask = PLAYERMASK_NONE; +#endif m_battlePlanBonuses = nullptr; m_skillPointsModifier = 1.0f; m_canBuildUnits = TRUE; @@ -340,6 +343,9 @@ Player::Player( Int playerIndex ) for (i = 0; i < MAX_PLAYER_COUNT; ++i) { m_attackedBy[i] = false; +#if RTS_GENERALS + m_visionSpiedBy[i] = 0; +#endif } m_attackedFrame = 0; @@ -694,6 +700,7 @@ void Player::update() //Update the academy stats (this only checks applicable things that require a polling method) getAcademyStats()->update(); +#if !(RTS_GENERALS && (RETAIL_COMPATIBLE_CRC || RETAIL_COMPATIBLE_NETWORKING)) //Kris: August 25, 2003 (DAY OF CODE LOCK -- NO NEW FEATURES, REALLY!) if( ThePlayerList->getLocalPlayer() == this ) { @@ -715,6 +722,7 @@ void Player::update() } } } +#endif #if !(RETAIL_COMPATIBLE_CRC || PRESERVE_TUNNEL_HEAL_STACKING) // TheSuperHackers @bugfix Stubbjax 26/09/2025 The Tunnel System now heals @@ -986,7 +994,13 @@ void Player::initFromDict(const Dict* d) for ( i = 0; i < MAX_PLAYER_COUNT; ++i ) // For now, it has been decided to just fix this one. Dear god me must reset. { m_attackedBy[i] = false; +#if RTS_GENERALS + m_visionSpiedBy[i] = 0; +#endif } +#if RTS_GENERALS + m_visionSpiedMask = PLAYERMASK_NONE; +#endif Int c = d->getInt(TheKey_playerColor, &exists); if (exists) @@ -1658,6 +1672,20 @@ void Player::onStructureConstructionComplete( Object *builder, Object *structure // This object may require us to play some EVA sounds. Player *localPlayer = ThePlayerList->getLocalPlayer(); +#if RTS_GENERALS + if (localPlayer == structure->getControllingPlayer() || localPlayer->getRelationship(structure->getTeam()) != ENEMIES) + return; + + // We need to play some EVA sounds. + if (structure->hasSpecialPower(SPECIAL_PARTICLE_UPLINK_CANNON)) + TheEva->setShouldPlay(EVA_SuperweaponDetected_ParticleCannon); + + if (structure->hasSpecialPower(SPECIAL_NEUTRON_MISSILE)) + TheEva->setShouldPlay(EVA_SuperweaponDetected_Nuke); + + if (structure->hasSpecialPower(SPECIAL_SCUD_STORM)) + TheEva->setShouldPlay(EVA_SuperweaponDetected_ScudStorm); +#else if( structure->hasSpecialPower( SPECIAL_PARTICLE_UPLINK_CANNON ) || structure->hasSpecialPower( SUPW_SPECIAL_PARTICLE_UPLINK_CANNON ) || @@ -1713,6 +1741,7 @@ void Player::onStructureConstructionComplete( Object *builder, Object *structure TheEva->setShouldPlay(EVA_SuperweaponDetected_Enemy_ScudStorm); } } +#endif } //============================================================================= @@ -2345,7 +2374,29 @@ void sellBuildings( Object *obj, void *userData ) //============================================================================= void Player::sellEverythingUnderTheSun() { +#if RTS_GENERALS && RETAIL_COMPATIBLE_CRC + for (PlayerTeamList::iterator it = m_playerTeamPrototypes.begin(); + it != m_playerTeamPrototypes.end(); ++it) { + for (DLINK_ITERATOR iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance()) { + Team *team = iter.cur(); + if (!team) { + continue; + } + + for (DLINK_ITERATOR iterObj = team->iterate_TeamMemberList(); !iterObj.done(); iterObj.advance()) { + Object *obj = iterObj.cur(); + if (!obj) { + continue; + } + + // sell the object + TheBuildAssistant->sellObject( obj ); + } + } + } +#else iterateObjects( sellBuildings, nullptr ); +#endif } @@ -2979,8 +3030,10 @@ Bool Player::canBuild(const ThingTemplate *tmplate) const } +#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) if ( !canBuildMoreOfType( tmplate ) ) return false; +#endif return true; @@ -3948,6 +4001,58 @@ Bool Player::getAttackedBy( Int playerNdx ) const return m_attackedBy[playerNdx]; } +#if RTS_GENERALS +// ------------------------------------------------------------------------------------------------ +static void callHandleShroud( Object *obj, void * ) +{ + // I feel I have to disapprove of the naming of this gathering of cell functions. It is called by death, + // alliance change, containment, spy change, and dynamic view range as well as partition cell change. + if( obj ) + obj->handlePartitionCellMaintenance(); +} + +// ------------------------------------------------------------------------------------------------ +void Player::setUnitsVisionSpied( Bool setting, PlayerIndex byWhom ) +{ + Bool needRefresh = FALSE; // If this setting is an edge trigger on the reference count, I need + // to tell all of my guys to handleShroud so they will start/stop looking for the new team. + + if( setting ) + { + m_visionSpiedBy[ byWhom ] = m_visionSpiedBy[ byWhom ] + 1; + if( m_visionSpiedBy[ byWhom ] == 1 ) + needRefresh = TRUE; + } + else + { + m_visionSpiedBy[ byWhom ] = m_visionSpiedBy[ byWhom ] - 1; + if( m_visionSpiedBy[ byWhom ] == 0 ) + needRefresh = TRUE; + } + + if( needRefresh ) + { + PlayerMaskType workingMask = 0; + for (Int i = 0; i < MAX_PLAYER_COUNT; ++i) + { + if( m_visionSpiedBy[i] > 0 ) + BitSet( workingMask, ( 1 << i ) ); + else + BitClear( workingMask, ( 1 << i ) ); + } + + m_visionSpiedMask = workingMask; + + iterateObjects( callHandleShroud, nullptr ); + } +} + +// ------------------------------------------------------------------------------------------------ +PlayerMaskType Player::getVisionSpiedMask() const +{ + return m_visionSpiedMask; +} +#else // ------------------------------------------------------------------------------------------------ // Little wrapper function so I can use it in iterateObjects, which is cool. struct VisionSpiedStruct @@ -3977,6 +4082,7 @@ void Player::setUnitsVisionSpied( Bool setting, KindOfMaskType whichUnits, Playe // Being spied is now a property of the unit, not us, since we can spy only a portion of the enemy. iterateObjects( iterator_setUnitsVisionSpied, &data ); } +#endif // ------------------------------------------------------------------------------------------------ Bool Player::isPlayerObserver() const @@ -4389,6 +4495,14 @@ void Player::xfer( Xfer *xfer ) // attacked by xfer->xferUser( m_attackedBy, sizeof( Bool ) * MAX_PLAYER_COUNT ); +#if RTS_GENERALS + // vision spied by + xfer->xferUser( m_visionSpiedBy, sizeof( Int ) * MAX_PLAYER_COUNT ); + + // vision spied by mask + xfer->xferUser( &m_visionSpiedMask, sizeof( PlayerMaskType ) ); +#endif + // cash bounty percent xfer->xferReal( &m_cashBountyPercent ); diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp index 466ea223b31..9698cc85f3c 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp @@ -83,7 +83,7 @@ const char* const SpecialPowerMaskType::s_bitNameList[] = "SPECIAL_MISSILE_DEFENDER_LASER_GUIDED_MISSILES", "SPECIAL_REMOTE_CHARGES", "SPECIAL_TIMED_CHARGES", - "SPECIAL_HELIX_NAPALM_BOMB", + "SPECIAL_HELIX_NAPALM_BOMB", // Added in Zero Hour "SPECIAL_HACKER_DISABLE_BUILDING", "SPECIAL_TANKHUNTER_TNT_ATTACK", "SPECIAL_BLACKLOTUS_CAPTURE_BUILDING", @@ -93,7 +93,7 @@ const char* const SpecialPowerMaskType::s_bitNameList[] = "SPECIAL_RADAR_VAN_SCAN", "SPECIAL_SPY_DRONE", "SPECIAL_DISGUISE_AS_VEHICLE", - "SPECIAL_BOOBY_TRAP", + "SPECIAL_BOOBY_TRAP", // Added in Zero Hour "SPECIAL_REPAIR_VEHICLES", "SPECIAL_PARTICLE_UPLINK_CANNON", "SPECIAL_CASH_BOUNTY", @@ -101,6 +101,7 @@ const char* const SpecialPowerMaskType::s_bitNameList[] = "SPECIAL_CIA_INTELLIGENCE", "SPECIAL_CLEANUP_AREA", "SPECIAL_LAUNCH_BAIKONUR_ROCKET", + // TheSuperHackers @info Added in Zero Hour: "SPECIAL_SPECTRE_GUNSHIP", "SPECIAL_GPS_SCRAMBLER", "SPECIAL_FRENZY", diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp index 03aaead2883..1a533d7c58c 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp @@ -1522,8 +1522,11 @@ Object *Team::getTeamTargetObject() if (target) { //If the enemy unit is stealthed and not detected, then we can't attack it! if( target->testStatus( OBJECT_STATUS_STEALTHED ) && - !target->testStatus( OBJECT_STATUS_DETECTED ) && - !target->testStatus( OBJECT_STATUS_DISGUISED ) ) + !target->testStatus( OBJECT_STATUS_DETECTED ) +#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) + && !target->testStatus( OBJECT_STATUS_DISGUISED ) +#endif + ) { target = nullptr; } @@ -1534,11 +1537,13 @@ Object *Team::getTeamTargetObject() if (target && target->getContainedBy()) { target = nullptr; // target entered a building or vehicle, so stop targeting. } +#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) if (target && target->isKindOf(KINDOF_AIRCRAFT)) { // It is just generally bad to have an aircraft as the team target. // Let team members acquire aircraft individually. jba. [8/27/2003] target = nullptr; } +#endif if (target == nullptr) { m_commonAttackTarget = INVALID_ID; } diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp index 62a7bd1a112..0601ccd9dea 100644 --- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp +++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp @@ -149,8 +149,11 @@ Object *TunnelTracker::getCurNemesis() if (target) { //If the enemy unit is stealthed and not detected, then we can't attack it! if( target->testStatus( OBJECT_STATUS_STEALTHED ) && - !target->testStatus( OBJECT_STATUS_DETECTED ) && - !target->testStatus( OBJECT_STATUS_DISGUISED ) ) + !target->testStatus( OBJECT_STATUS_DETECTED ) +#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) + && !target->testStatus( OBJECT_STATUS_DISGUISED ) +#endif + ) { target = nullptr; } From 8a9ff6233597edab5205e3cb86cef97f44e7ece5 Mon Sep 17 00:00:00 2001 From: Jaredl-Dev <260281143+Jaredl-Dev@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:51:40 -0800 Subject: [PATCH 2/2] unify(rts): Move Common/RTS files to Core (#3733) --- Core/GameEngine/CMakeLists.txt | 64 +- .../GameEngine/Include/Common/ActionManager.h | 0 .../GameEngine/Include/Common/Energy.h | 0 .../GameEngine/Include/Common/Handicap.h | 0 .../GameEngine/Include/Common/MissionStats.h | 0 .../GameEngine/Include/Common/Money.h | 0 .../GameEngine/Include/Common/Player.h | 0 .../GameEngine/Include/Common/PlayerList.h | 0 .../Include/Common/PlayerTemplate.h | 0 .../Include/Common/ProductionPrerequisite.h | 0 .../Include/Common/ResourceGatheringManager.h | 0 .../GameEngine/Include/Common/Science.h | 0 .../GameEngine/Include/Common/ScoreKeeper.h | 0 .../GameEngine/Include/Common/SpecialPower.h | 0 .../Include/Common/SpecialPowerMaskType.h | 0 .../Include/Common/SpecialPowerType.h | 0 .../GameEngine/Include/Common/Team.h | 0 .../GameEngine/Include/Common/TunnelTracker.h | 0 .../Source/Common/RTS/ActionManager.cpp | 0 .../GameEngine/Source/Common/RTS/Energy.cpp | 0 .../GameEngine/Source/Common/RTS/Handicap.cpp | 0 .../Source/Common/RTS/MissionStats.cpp | 0 .../GameEngine/Source/Common/RTS/Money.cpp | 0 .../GameEngine/Source/Common/RTS/Player.cpp | 0 .../Source/Common/RTS/PlayerList.cpp | 0 .../Source/Common/RTS/PlayerTemplate.cpp | 0 .../Common/RTS/ProductionPrerequisite.cpp | 0 .../Common/RTS/ResourceGatheringManager.cpp | 0 .../GameEngine/Source/Common/RTS/Science.cpp | 0 .../Source/Common/RTS/ScoreKeeper.cpp | 0 .../Source/Common/RTS/SpecialPower.cpp | 0 .../GameEngine/Source/Common/RTS/Team.cpp | 0 .../Source/Common/RTS/TunnelTracker.cpp | 0 Generals/Code/GameEngine/CMakeLists.txt | 64 +- .../GameEngine/Include/Common/ActionManager.h | 110 - .../Code/GameEngine/Include/Common/Energy.h | 122 - .../Code/GameEngine/Include/Common/Handicap.h | 114 - .../GameEngine/Include/Common/MissionStats.h | 83 - .../Code/GameEngine/Include/Common/Money.h | 112 - .../Code/GameEngine/Include/Common/Player.h | 843 --- .../GameEngine/Include/Common/PlayerList.h | 181 - .../Include/Common/PlayerTemplate.h | 232 - .../Include/Common/ProductionPrerequisite.h | 120 - .../Include/Common/ResourceGatheringManager.h | 71 - .../Code/GameEngine/Include/Common/Science.h | 133 - .../GameEngine/Include/Common/ScoreKeeper.h | 140 - .../GameEngine/Include/Common/SpecialPower.h | 189 - .../Include/Common/SpecialPowerMaskType.h | 35 - .../Include/Common/SpecialPowerType.h | 135 - .../Code/GameEngine/Include/Common/Team.h | 755 --- .../GameEngine/Include/Common/TunnelTracker.h | 102 - .../Source/Common/RTS/ActionManager.cpp | 2154 -------- .../GameEngine/Source/Common/RTS/Energy.cpp | 313 -- .../GameEngine/Source/Common/RTS/Handicap.cpp | 128 - .../Source/Common/RTS/MissionStats.cpp | 113 - .../GameEngine/Source/Common/RTS/Money.cpp | 214 - .../GameEngine/Source/Common/RTS/Player.cpp | 4707 ----------------- .../Source/Common/RTS/PlayerList.cpp | 559 -- .../Source/Common/RTS/PlayerTemplate.cpp | 413 -- .../Common/RTS/ProductionPrerequisite.cpp | 313 -- .../Common/RTS/ResourceGatheringManager.cpp | 291 - .../GameEngine/Source/Common/RTS/Science.cpp | 376 -- .../Source/Common/RTS/ScoreKeeper.cpp | 565 -- .../Source/Common/RTS/SpecialPower.cpp | 379 -- .../GameEngine/Source/Common/RTS/Team.cpp | 2760 ---------- .../Source/Common/RTS/TunnelTracker.cpp | 569 -- GeneralsMD/Code/GameEngine/CMakeLists.txt | 64 +- scripts/cpp/unify_move_files.py | 33 + 68 files changed, 129 insertions(+), 17427 deletions(-) rename {GeneralsMD/Code => Core}/GameEngine/Include/Common/ActionManager.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Include/Common/Energy.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Include/Common/Handicap.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Include/Common/MissionStats.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Include/Common/Money.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Include/Common/Player.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Include/Common/PlayerList.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Include/Common/PlayerTemplate.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Include/Common/ProductionPrerequisite.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Include/Common/ResourceGatheringManager.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Include/Common/Science.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Include/Common/ScoreKeeper.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Include/Common/SpecialPower.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Include/Common/SpecialPowerMaskType.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Include/Common/SpecialPowerType.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Include/Common/Team.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Include/Common/TunnelTracker.h (100%) rename {GeneralsMD/Code => Core}/GameEngine/Source/Common/RTS/ActionManager.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngine/Source/Common/RTS/Energy.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngine/Source/Common/RTS/Handicap.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngine/Source/Common/RTS/MissionStats.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngine/Source/Common/RTS/Money.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngine/Source/Common/RTS/Player.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngine/Source/Common/RTS/PlayerList.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngine/Source/Common/RTS/PlayerTemplate.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngine/Source/Common/RTS/ResourceGatheringManager.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngine/Source/Common/RTS/Science.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngine/Source/Common/RTS/ScoreKeeper.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngine/Source/Common/RTS/SpecialPower.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngine/Source/Common/RTS/Team.cpp (100%) rename {GeneralsMD/Code => Core}/GameEngine/Source/Common/RTS/TunnelTracker.cpp (100%) delete mode 100644 Generals/Code/GameEngine/Include/Common/ActionManager.h delete mode 100644 Generals/Code/GameEngine/Include/Common/Energy.h delete mode 100644 Generals/Code/GameEngine/Include/Common/Handicap.h delete mode 100644 Generals/Code/GameEngine/Include/Common/MissionStats.h delete mode 100644 Generals/Code/GameEngine/Include/Common/Money.h delete mode 100644 Generals/Code/GameEngine/Include/Common/Player.h delete mode 100644 Generals/Code/GameEngine/Include/Common/PlayerList.h delete mode 100644 Generals/Code/GameEngine/Include/Common/PlayerTemplate.h delete mode 100644 Generals/Code/GameEngine/Include/Common/ProductionPrerequisite.h delete mode 100644 Generals/Code/GameEngine/Include/Common/ResourceGatheringManager.h delete mode 100644 Generals/Code/GameEngine/Include/Common/Science.h delete mode 100644 Generals/Code/GameEngine/Include/Common/ScoreKeeper.h delete mode 100644 Generals/Code/GameEngine/Include/Common/SpecialPower.h delete mode 100644 Generals/Code/GameEngine/Include/Common/SpecialPowerMaskType.h delete mode 100644 Generals/Code/GameEngine/Include/Common/SpecialPowerType.h delete mode 100644 Generals/Code/GameEngine/Include/Common/Team.h delete mode 100644 Generals/Code/GameEngine/Include/Common/TunnelTracker.h delete mode 100644 Generals/Code/GameEngine/Source/Common/RTS/ActionManager.cpp delete mode 100644 Generals/Code/GameEngine/Source/Common/RTS/Energy.cpp delete mode 100644 Generals/Code/GameEngine/Source/Common/RTS/Handicap.cpp delete mode 100644 Generals/Code/GameEngine/Source/Common/RTS/MissionStats.cpp delete mode 100644 Generals/Code/GameEngine/Source/Common/RTS/Money.cpp delete mode 100644 Generals/Code/GameEngine/Source/Common/RTS/Player.cpp delete mode 100644 Generals/Code/GameEngine/Source/Common/RTS/PlayerList.cpp delete mode 100644 Generals/Code/GameEngine/Source/Common/RTS/PlayerTemplate.cpp delete mode 100644 Generals/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp delete mode 100644 Generals/Code/GameEngine/Source/Common/RTS/ResourceGatheringManager.cpp delete mode 100644 Generals/Code/GameEngine/Source/Common/RTS/Science.cpp delete mode 100644 Generals/Code/GameEngine/Source/Common/RTS/ScoreKeeper.cpp delete mode 100644 Generals/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp delete mode 100644 Generals/Code/GameEngine/Source/Common/RTS/Team.cpp delete mode 100644 Generals/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp diff --git a/Core/GameEngine/CMakeLists.txt b/Core/GameEngine/CMakeLists.txt index e4e63bec4a8..d4e7d2d201e 100644 --- a/Core/GameEngine/CMakeLists.txt +++ b/Core/GameEngine/CMakeLists.txt @@ -1,6 +1,6 @@ set(GAMEENGINE_SRC Include/Common/AcademyStats.h -# Include/Common/ActionManager.h + Include/Common/ActionManager.h Include/Common/AddonCompat.h Include/Common/ArchiveFile.h Include/Common/ArchiveFileSystem.h @@ -37,7 +37,7 @@ set(GAMEENGINE_SRC # Include/Common/DrawModule.h Include/Common/DynamicAudioEventInfo.h # Include/Common/encrypt.h -# Include/Common/Energy.h + Include/Common/Energy.h Include/Common/Errors.h Include/Common/file.h Include/Common/FileSystem.h @@ -60,7 +60,7 @@ set(GAMEENGINE_SRC Include/Common/GameUtility.h # Include/Common/Geometry.h # Include/Common/GlobalData.h -# Include/Common/Handicap.h + Include/Common/Handicap.h # Include/Common/IgnorePreferences.h Include/Common/INI.h # Include/Common/INIException.h @@ -76,11 +76,11 @@ set(GAMEENGINE_SRC Include/Common/MessageStream.h Include/Common/MiniLog.h Include/Common/MiscAudio.h -# Include/Common/MissionStats.h + Include/Common/MissionStats.h # Include/Common/ModelState.h # Include/Common/Module.h # Include/Common/ModuleFactory.h -# Include/Common/Money.h + Include/Common/Money.h # Include/Common/MultiplayerSettings.h # Include/Common/NameKeyGenerator.h Include/Common/ObjectStatusTypes.h @@ -91,10 +91,10 @@ set(GAMEENGINE_SRC # Include/Common/PartitionSolver.h # Include/Common/PerfMetrics.h Include/Common/PerfTimer.h -# Include/Common/Player.h -# Include/Common/PlayerList.h -# Include/Common/PlayerTemplate.h -# Include/Common/ProductionPrerequisite.h + Include/Common/Player.h + Include/Common/PlayerList.h + Include/Common/PlayerTemplate.h + Include/Common/ProductionPrerequisite.h # Include/Common/QuickmatchPreferences.h # Include/Common/QuotedPrintable.h Include/Common/Radar.h @@ -103,32 +103,32 @@ set(GAMEENGINE_SRC # Include/Common/Recorder.h # Include/Common/Registry.h Include/Common/ReplaySimulation.h -# Include/Common/ResourceGatheringManager.h -# Include/Common/Science.h + Include/Common/ResourceGatheringManager.h + Include/Common/Science.h # Include/Common/ScopedMutex.h -# Include/Common/ScoreKeeper.h + Include/Common/ScoreKeeper.h #Include/Common/simpleplayer.h # unused # Include/Common/SkirmishBattleHonors.h # Include/Common/SkirmishPreferences.h Include/Common/Snapshot.h # Include/Common/SparseMatchFinder.h -# Include/Common/SpecialPower.h -# Include/Common/SpecialPowerMaskType.h -# Include/Common/SpecialPowerType.h + Include/Common/SpecialPower.h + Include/Common/SpecialPowerMaskType.h + Include/Common/SpecialPowerType.h # Include/Common/StackDump.h # Include/Common/StateMachine.h # Include/Common/StatsCollector.h Include/Common/STLTypedefs.h Include/Common/StreamingArchiveFile.h Include/Common/SubsystemInterface.h -# Include/Common/Team.h + Include/Common/Team.h # Include/Common/Terrain.h Include/Common/TerrainTypes.h # Include/Common/Thing.h # Include/Common/ThingFactory.h # Include/Common/ThingSort.h Include/Common/ThingTemplate.h -# Include/Common/TunnelTracker.h + Include/Common/TunnelTracker.h Include/Common/UnicodeString.h # Include/Common/UnitTimings.h # Include/Common/Upgrade.h @@ -633,21 +633,21 @@ set(GAMEENGINE_SRC # Source/Common/Recorder.cpp Source/Common/ReplaySimulation.cpp Source/Common/RTS/AcademyStats.cpp -# Source/Common/RTS/ActionManager.cpp -# Source/Common/RTS/Energy.cpp -# Source/Common/RTS/Handicap.cpp -# Source/Common/RTS/MissionStats.cpp -# Source/Common/RTS/Money.cpp -# Source/Common/RTS/Player.cpp -# Source/Common/RTS/PlayerList.cpp -# Source/Common/RTS/PlayerTemplate.cpp -# Source/Common/RTS/ProductionPrerequisite.cpp -# Source/Common/RTS/ResourceGatheringManager.cpp -# Source/Common/RTS/Science.cpp -# Source/Common/RTS/ScoreKeeper.cpp -# Source/Common/RTS/SpecialPower.cpp -# Source/Common/RTS/Team.cpp -# Source/Common/RTS/TunnelTracker.cpp + Source/Common/RTS/ActionManager.cpp + Source/Common/RTS/Energy.cpp + Source/Common/RTS/Handicap.cpp + Source/Common/RTS/MissionStats.cpp + Source/Common/RTS/Money.cpp + Source/Common/RTS/Player.cpp + Source/Common/RTS/PlayerList.cpp + Source/Common/RTS/PlayerTemplate.cpp + Source/Common/RTS/ProductionPrerequisite.cpp + Source/Common/RTS/ResourceGatheringManager.cpp + Source/Common/RTS/Science.cpp + Source/Common/RTS/ScoreKeeper.cpp + Source/Common/RTS/SpecialPower.cpp + Source/Common/RTS/Team.cpp + Source/Common/RTS/TunnelTracker.cpp # Source/Common/SkirmishBattleHonors.cpp # Source/Common/StateMachine.cpp # Source/Common/StatsCollector.cpp diff --git a/GeneralsMD/Code/GameEngine/Include/Common/ActionManager.h b/Core/GameEngine/Include/Common/ActionManager.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/Common/ActionManager.h rename to Core/GameEngine/Include/Common/ActionManager.h diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Energy.h b/Core/GameEngine/Include/Common/Energy.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/Common/Energy.h rename to Core/GameEngine/Include/Common/Energy.h diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Handicap.h b/Core/GameEngine/Include/Common/Handicap.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/Common/Handicap.h rename to Core/GameEngine/Include/Common/Handicap.h diff --git a/GeneralsMD/Code/GameEngine/Include/Common/MissionStats.h b/Core/GameEngine/Include/Common/MissionStats.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/Common/MissionStats.h rename to Core/GameEngine/Include/Common/MissionStats.h diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Money.h b/Core/GameEngine/Include/Common/Money.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/Common/Money.h rename to Core/GameEngine/Include/Common/Money.h diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Player.h b/Core/GameEngine/Include/Common/Player.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/Common/Player.h rename to Core/GameEngine/Include/Common/Player.h diff --git a/GeneralsMD/Code/GameEngine/Include/Common/PlayerList.h b/Core/GameEngine/Include/Common/PlayerList.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/Common/PlayerList.h rename to Core/GameEngine/Include/Common/PlayerList.h diff --git a/GeneralsMD/Code/GameEngine/Include/Common/PlayerTemplate.h b/Core/GameEngine/Include/Common/PlayerTemplate.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/Common/PlayerTemplate.h rename to Core/GameEngine/Include/Common/PlayerTemplate.h diff --git a/GeneralsMD/Code/GameEngine/Include/Common/ProductionPrerequisite.h b/Core/GameEngine/Include/Common/ProductionPrerequisite.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/Common/ProductionPrerequisite.h rename to Core/GameEngine/Include/Common/ProductionPrerequisite.h diff --git a/GeneralsMD/Code/GameEngine/Include/Common/ResourceGatheringManager.h b/Core/GameEngine/Include/Common/ResourceGatheringManager.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/Common/ResourceGatheringManager.h rename to Core/GameEngine/Include/Common/ResourceGatheringManager.h diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Science.h b/Core/GameEngine/Include/Common/Science.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/Common/Science.h rename to Core/GameEngine/Include/Common/Science.h diff --git a/GeneralsMD/Code/GameEngine/Include/Common/ScoreKeeper.h b/Core/GameEngine/Include/Common/ScoreKeeper.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/Common/ScoreKeeper.h rename to Core/GameEngine/Include/Common/ScoreKeeper.h diff --git a/GeneralsMD/Code/GameEngine/Include/Common/SpecialPower.h b/Core/GameEngine/Include/Common/SpecialPower.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/Common/SpecialPower.h rename to Core/GameEngine/Include/Common/SpecialPower.h diff --git a/GeneralsMD/Code/GameEngine/Include/Common/SpecialPowerMaskType.h b/Core/GameEngine/Include/Common/SpecialPowerMaskType.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/Common/SpecialPowerMaskType.h rename to Core/GameEngine/Include/Common/SpecialPowerMaskType.h diff --git a/GeneralsMD/Code/GameEngine/Include/Common/SpecialPowerType.h b/Core/GameEngine/Include/Common/SpecialPowerType.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/Common/SpecialPowerType.h rename to Core/GameEngine/Include/Common/SpecialPowerType.h diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Team.h b/Core/GameEngine/Include/Common/Team.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/Common/Team.h rename to Core/GameEngine/Include/Common/Team.h diff --git a/GeneralsMD/Code/GameEngine/Include/Common/TunnelTracker.h b/Core/GameEngine/Include/Common/TunnelTracker.h similarity index 100% rename from GeneralsMD/Code/GameEngine/Include/Common/TunnelTracker.h rename to Core/GameEngine/Include/Common/TunnelTracker.h diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp b/Core/GameEngine/Source/Common/RTS/ActionManager.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp rename to Core/GameEngine/Source/Common/RTS/ActionManager.cpp diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Energy.cpp b/Core/GameEngine/Source/Common/RTS/Energy.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/Common/RTS/Energy.cpp rename to Core/GameEngine/Source/Common/RTS/Energy.cpp diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Handicap.cpp b/Core/GameEngine/Source/Common/RTS/Handicap.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/Common/RTS/Handicap.cpp rename to Core/GameEngine/Source/Common/RTS/Handicap.cpp diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/MissionStats.cpp b/Core/GameEngine/Source/Common/RTS/MissionStats.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/Common/RTS/MissionStats.cpp rename to Core/GameEngine/Source/Common/RTS/MissionStats.cpp diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Money.cpp b/Core/GameEngine/Source/Common/RTS/Money.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/Common/RTS/Money.cpp rename to Core/GameEngine/Source/Common/RTS/Money.cpp diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp b/Core/GameEngine/Source/Common/RTS/Player.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp rename to Core/GameEngine/Source/Common/RTS/Player.cpp diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/PlayerList.cpp b/Core/GameEngine/Source/Common/RTS/PlayerList.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/Common/RTS/PlayerList.cpp rename to Core/GameEngine/Source/Common/RTS/PlayerList.cpp diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/PlayerTemplate.cpp b/Core/GameEngine/Source/Common/RTS/PlayerTemplate.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/Common/RTS/PlayerTemplate.cpp rename to Core/GameEngine/Source/Common/RTS/PlayerTemplate.cpp diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp b/Core/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp rename to Core/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ResourceGatheringManager.cpp b/Core/GameEngine/Source/Common/RTS/ResourceGatheringManager.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/Common/RTS/ResourceGatheringManager.cpp rename to Core/GameEngine/Source/Common/RTS/ResourceGatheringManager.cpp diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Science.cpp b/Core/GameEngine/Source/Common/RTS/Science.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/Common/RTS/Science.cpp rename to Core/GameEngine/Source/Common/RTS/Science.cpp diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ScoreKeeper.cpp b/Core/GameEngine/Source/Common/RTS/ScoreKeeper.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/Common/RTS/ScoreKeeper.cpp rename to Core/GameEngine/Source/Common/RTS/ScoreKeeper.cpp diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp b/Core/GameEngine/Source/Common/RTS/SpecialPower.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp rename to Core/GameEngine/Source/Common/RTS/SpecialPower.cpp diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp b/Core/GameEngine/Source/Common/RTS/Team.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp rename to Core/GameEngine/Source/Common/RTS/Team.cpp diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp b/Core/GameEngine/Source/Common/RTS/TunnelTracker.cpp similarity index 100% rename from GeneralsMD/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp rename to Core/GameEngine/Source/Common/RTS/TunnelTracker.cpp diff --git a/Generals/Code/GameEngine/CMakeLists.txt b/Generals/Code/GameEngine/CMakeLists.txt index 0340e0e1691..0f15c3c4d1e 100644 --- a/Generals/Code/GameEngine/CMakeLists.txt +++ b/Generals/Code/GameEngine/CMakeLists.txt @@ -1,5 +1,5 @@ set(GAMEENGINE_SRC - Include/Common/ActionManager.h +# Include/Common/ActionManager.h # Include/Common/ArchiveFile.h # Include/Common/ArchiveFileSystem.h # Include/Common/AsciiString.h @@ -31,7 +31,7 @@ set(GAMEENGINE_SRC # Include/Common/DiscreteCircle.h Include/Common/DrawModule.h Include/Common/encrypt.h - Include/Common/Energy.h +# Include/Common/Energy.h # Include/Common/Errors.h # Include/Common/file.h # Include/Common/FileSystem.h @@ -50,7 +50,7 @@ set(GAMEENGINE_SRC # Include/Common/GameType.h Include/Common/Geometry.h Include/Common/GlobalData.h - Include/Common/Handicap.h +# Include/Common/Handicap.h Include/Common/IgnorePreferences.h # Include/Common/INI.h Include/Common/INIException.h @@ -66,11 +66,11 @@ set(GAMEENGINE_SRC # Include/Common/MessageStream.h # Include/Common/MiniLog.h # Include/Common/MiscAudio.h - Include/Common/MissionStats.h +# Include/Common/MissionStats.h Include/Common/ModelState.h Include/Common/Module.h Include/Common/ModuleFactory.h - Include/Common/Money.h +# Include/Common/Money.h Include/Common/MultiplayerSettings.h Include/Common/NameKeyGenerator.h # Include/Common/ObjectStatusTypes.h @@ -80,10 +80,10 @@ set(GAMEENGINE_SRC Include/Common/PartitionSolver.h Include/Common/PerfMetrics.h # Include/Common/PerfTimer.h - Include/Common/Player.h - Include/Common/PlayerList.h - Include/Common/PlayerTemplate.h - Include/Common/ProductionPrerequisite.h +# Include/Common/Player.h +# Include/Common/PlayerList.h +# Include/Common/PlayerTemplate.h +# Include/Common/ProductionPrerequisite.h Include/Common/QuickmatchPreferences.h Include/Common/QuotedPrintable.h # Include/Common/Radar.h @@ -92,30 +92,30 @@ set(GAMEENGINE_SRC Include/Common/Recorder.h # Include/Common/ReplaySimulation.h Include/Common/Registry.h - Include/Common/ResourceGatheringManager.h - Include/Common/Science.h - Include/Common/ScoreKeeper.h +# Include/Common/ResourceGatheringManager.h +# Include/Common/Science.h +# Include/Common/ScoreKeeper.h Include/Common/SkirmishBattleHonors.h Include/Common/SkirmishPreferences.h # Include/Common/Snapshot.h Include/Common/SparseMatchFinder.h - Include/Common/SpecialPower.h - Include/Common/SpecialPowerMaskType.h - Include/Common/SpecialPowerType.h +# Include/Common/SpecialPower.h +# Include/Common/SpecialPowerMaskType.h +# Include/Common/SpecialPowerType.h Include/Common/StackDump.h Include/Common/StateMachine.h Include/Common/StatsCollector.h # Include/Common/STLTypedefs.h # Include/Common/StreamingArchiveFile.h # Include/Common/SubsystemInterface.h - Include/Common/Team.h +# Include/Common/Team.h Include/Common/Terrain.h # Include/Common/TerrainTypes.h Include/Common/Thing.h Include/Common/ThingFactory.h Include/Common/ThingSort.h # Include/Common/ThingTemplate.h - Include/Common/TunnelTracker.h +# Include/Common/TunnelTracker.h # Include/Common/UnicodeString.h Include/Common/UnitTimings.h Include/Common/Upgrade.h @@ -564,21 +564,21 @@ set(GAMEENGINE_SRC # Source/Common/PerfTimer.cpp # Source/Common/RandomValue.cpp Source/Common/Recorder.cpp - Source/Common/RTS/ActionManager.cpp - Source/Common/RTS/Energy.cpp - Source/Common/RTS/Handicap.cpp - Source/Common/RTS/MissionStats.cpp - Source/Common/RTS/Money.cpp - Source/Common/RTS/Player.cpp - Source/Common/RTS/PlayerList.cpp - Source/Common/RTS/PlayerTemplate.cpp - Source/Common/RTS/ProductionPrerequisite.cpp - Source/Common/RTS/ResourceGatheringManager.cpp - Source/Common/RTS/Science.cpp - Source/Common/RTS/ScoreKeeper.cpp - Source/Common/RTS/SpecialPower.cpp - Source/Common/RTS/Team.cpp - Source/Common/RTS/TunnelTracker.cpp +# Source/Common/RTS/ActionManager.cpp +# Source/Common/RTS/Energy.cpp +# Source/Common/RTS/Handicap.cpp +# Source/Common/RTS/MissionStats.cpp +# Source/Common/RTS/Money.cpp +# Source/Common/RTS/Player.cpp +# Source/Common/RTS/PlayerList.cpp +# Source/Common/RTS/PlayerTemplate.cpp +# Source/Common/RTS/ProductionPrerequisite.cpp +# Source/Common/RTS/ResourceGatheringManager.cpp +# Source/Common/RTS/Science.cpp +# Source/Common/RTS/ScoreKeeper.cpp +# Source/Common/RTS/SpecialPower.cpp +# Source/Common/RTS/Team.cpp +# Source/Common/RTS/TunnelTracker.cpp Source/Common/SkirmishBattleHonors.cpp Source/Common/StateMachine.cpp Source/Common/StatsCollector.cpp diff --git a/Generals/Code/GameEngine/Include/Common/ActionManager.h b/Generals/Code/GameEngine/Include/Common/ActionManager.h deleted file mode 100644 index db1a515f272..00000000000 --- a/Generals/Code/GameEngine/Include/Common/ActionManager.h +++ /dev/null @@ -1,110 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: ActionManager.h ////////////////////////////////////////////////////////////////////////// -// Author: Colin Day -// Desc: TheActionManager is a convenient place for us to wrap up all sorts of logical -// queries about what objects can do in the world and to other objects. The purpose -// of having a central place for this logic assists us in making these logical kind -// of queries in the user interface and allows us to use the same code to validate -// commands as they come in over the network interface in order to do the -// real action. -/////////////////////////////////////////////////////////////////////////////////////////////////// - -#pragma once - -// INCLUDES /////////////////////////////////////////////////////////////////////////////////////// -#include "Common/SubsystemInterface.h" - -// FORWARD REFERENCES ///////////////////////////////////////////////////////////////////////////// -class Object; -class Player; -class SpecialPowerTemplate; -enum SpecialPowerType CPP_11(: Int); -enum WeaponSlotType CPP_11(: Int); -enum CommandSourceType CPP_11(: Int); -enum CanAttackResult CPP_11(: Int); - -enum CanEnterType CPP_11(: Int) -{ - CHECK_CAPACITY, - DONT_CHECK_CAPACITY, - COMBATDROP_INTO -}; - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -class ActionManager : public SubsystemInterface -{ - -public: - - ActionManager(); - virtual ~ActionManager() override; - - virtual void init() override { }; ///< subsystem interface - virtual void reset() override { }; ///< subsystem interface - virtual void update() override { }; ///< subsystem interface - - //Single unit to unit check - Bool canGetRepairedAt( const Object *obj, const Object *repairDest, CommandSourceType commandSource ); - Bool canTransferSuppliesAt( const Object *obj, const Object *transferDest ); - Bool canDockAt( const Object *obj, const Object *dockDest, CommandSourceType commandSource ); - Bool canGetHealedAt( const Object *obj, const Object *healDest, CommandSourceType commandSource ); - Bool canRepairObject( const Object *obj, const Object *objectToRepair, CommandSourceType commandSource ); - Bool canResumeConstructionOf( const Object *obj, const Object *objectBeingConstructed, CommandSourceType commandSource ); - Bool canEnterObject( const Object *obj, const Object *objectToEnter, CommandSourceType commandSource, CanEnterType mode ); - CanAttackResult getCanAttackObject( const Object *obj, const Object *objectToAttack, CommandSourceType commandSource, AbleToAttackType attackType ); - Bool canConvertObjectToCarBomb( const Object *obj, const Object *objectToConvert, CommandSourceType commandSource ); - Bool canHijackVehicle( const Object *obj, const Object *ObjectToHijack, CommandSourceType commandSource ); // LORENZEN - Bool canSabotageBuilding( const Object *obj, const Object *objectToSabotage, CommandSourceType commandSource ); - Bool canCaptureBuilding( const Object *obj, const Object *objectToCapture, CommandSourceType commandSource ); - Bool canDisableVehicleViaHacking( const Object *obj, const Object *objectToHack, CommandSourceType commandSource, Bool checkSourceRequirements = true ); -#ifdef ALLOW_SURRENDER - Bool canPickUpPrisoner( const Object *obj, const Object *prisoner, CommandSourceType commandSource ); -#endif - Bool canStealCashViaHacking( const Object *obj, const Object *objectToHack, CommandSourceType commandSource ); - Bool canSnipeVehicle( const Object *obj, const Object *objectToSnipe, CommandSourceType commandSource ); - Bool canBribeUnit( const Object *obj, const Object *objectToBribe, CommandSourceType commandSource ); - Bool canCutBuildingPower( const Object *obj, const Object *building, CommandSourceType commandSource ); - Bool canDisableBuildingViaHacking( const Object *obj, const Object *objectToHack, CommandSourceType commandSource ); - Bool canDoSpecialPowerAtLocation( const Object *obj, const Coord3D *loc, CommandSourceType commandSource, const SpecialPowerTemplate *spTemplate, const Object *objectInWay, UnsignedInt commandOptions, Bool checkSourceRequirements = true ); - Bool canDoSpecialPowerAtObject( const Object *obj, const Object *target, CommandSourceType commandSource, const SpecialPowerTemplate *spTemplate, UnsignedInt commandOptions, Bool checkSourceRequirements = true); - Bool canDoSpecialPower( const Object *obj, const SpecialPowerTemplate *spTemplate, CommandSourceType commandSource, UnsignedInt commandOptions, Bool checkSourceRequirements = true ); - Bool canMakeObjectDefector( const Object *obj, const Object *objectToMakeDefector, CommandSourceType commandSource ); - Bool canFireWeaponAtLocation( const Object *obj, const Coord3D *loc, CommandSourceType commandSource, const WeaponSlotType slot, const Object *objectInWay ); - Bool canFireWeaponAtObject( const Object *obj, const Object *target, CommandSourceType commandSource, const WeaponSlotType slot ); - Bool canFireWeapon( const Object *obj, const WeaponSlotType slot, CommandSourceType commandSource ); - Bool canGarrison( const Object *obj, const Object *target, CommandSourceType commandSource ); - Bool canOverrideSpecialPowerDestination( const Object *obj, const Coord3D *loc, SpecialPowerType spType, CommandSourceType commandSource ); - - //Player to unit check - Bool canPlayerGarrison( const Player *player, const Object *target, CommandSourceType commandSource ); - -protected: - -}; - -// EXTERNALS ////////////////////////////////////////////////////////////////////////////////////// -extern ActionManager *TheActionManager; diff --git a/Generals/Code/GameEngine/Include/Common/Energy.h b/Generals/Code/GameEngine/Include/Common/Energy.h deleted file mode 100644 index 48280202cc5..00000000000 --- a/Generals/Code/GameEngine/Include/Common/Energy.h +++ /dev/null @@ -1,122 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: Energy.h //////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: RTS3 -// -// File name: Energy.h -// -// Created: Steven Johnson, October 2001 -// -// Desc: @todo -// -//----------------------------------------------------------------------------- - -#pragma once - -// INCLUDES ///////////////////////////////////////////////////////////////////////////////////// -#include "Common/Snapshot.h" - -// ---------------------------------------------------------------------------------------------- - -class Player; -class Object; - -// ---------------------------------------------------------------------------------------------- -/** - This class is used to encapsulate the Player's energy use and production. - for consistent nomenclature, we'll arbitrarily call energy units "kilowatts" - (though that may have no bearing on reality). -*/ -class Energy : public Snapshot -{ - -public: - - Energy(); - - // reset energy information to base values. - void init( Player *owner) - { - m_energyProduction = 0; - m_energyConsumption = 0; - m_powerSabotagedTillFrame = 0; - m_owner = owner; - } - - /// return current energy production in kilowatts - Int getProduction() const; - - /// return current energy consumption in kilowatts - Int getConsumption() const { return m_energyConsumption; } - - Bool hasSufficientPower() const; - - // If adding is false, we're supposed to be removing this. - void adjustPower(Int powerDelta, Bool adding); - - /// new 'obj' will now add/subtract from this energy construct - void objectEnteringInfluence( Object *obj ); - - /// 'obj' will now no longer add/subtrack from this energy construct - void objectLeavingInfluence( Object *obj ); - - /** Adds an energy bonus to the player's pool if the power bonus status bit is set */ - void addPowerBonus( Object *obj ); - void removePowerBonus( Object *obj ); - - void setPowerSabotagedTillFrame( UnsignedInt frame ) { m_powerSabotagedTillFrame = frame; } - UnsignedInt getPowerSabotagedTillFrame() const { return m_powerSabotagedTillFrame; } - - /** - return the percentage of energy needed that we actually produce, as a 0.0 ... 1.0 fraction. - */ - Real getEnergySupplyRatio() const; - -protected: - - // snapshot methods - virtual void crc( Xfer *xfer ) override; - virtual void xfer( Xfer *xfer ) override; - virtual void loadPostProcess() override; - - void addProduction(Int amt); - void addConsumption(Int amt); - -private: - - Int m_energyProduction; ///< level of energy production, in kw - Int m_energyConsumption; ///< level of energy consumption, in kw - UnsignedInt m_powerSabotagedTillFrame; ///< If power is sabotaged, the frame will be greater than now. - Player *m_owner; ///< Tight pointer to the Player I am intrinsic to. -}; diff --git a/Generals/Code/GameEngine/Include/Common/Handicap.h b/Generals/Code/GameEngine/Include/Common/Handicap.h deleted file mode 100644 index e73aedb9bd3..00000000000 --- a/Generals/Code/GameEngine/Include/Common/Handicap.h +++ /dev/null @@ -1,114 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: Handicap.h //////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: RTS3 -// -// File name: Handicap.h -// -// Created: Steven Johnson, October 2001 -// -// Desc: @todo -// -//----------------------------------------------------------------------------- - -#pragma once - -// ---------------------------------------------------------------------------------------------- -class Object; -class Dict; -class ThingTemplate; - -// ---------------------------------------------------------------------------------------------- -/** - Handicap encapsulates the sets of modifiers to abilities used to balance - the game and give different abilities to different Players. - Conceptually, it's a large set of coefficients (typically, but not necessarily, - in the range of 0.0...1.0). - - Usage example (conceptual): - - Real armorCoef = this->m_handicap->getHandicap(ARMOR, this); - Real actualArmor = this->getArmorValue() * armorCoef; -*/ -class Handicap -{ -public: - - // NOTE: if you ever add/remove/change the enums in HandicapType, - // you must also modify initFromDict()! - enum HandicapType - { - BUILDCOST, - BUILDTIME, - - HANDICAP_TYPE_COUNT - }; - - Handicap(); - - /// reset all handicaps to a default value. - void init(); - - /** - initialize from the fields in the Dict. Note that this does NOT call init() - internally, so only those fields that are present in the dict will be set. - if you want to ensure all fields are something reasonable, you should call init() - prior to calling this. - */ - void readFromDict(const Dict* d); - - /** - return the multiplier for the given Handicap type on the given Object. - The Object's type (unit, building, etc.) will generally be examined - to determine what value to return. - */ - Real getHandicap(HandicapType t, const ThingTemplate *tmpl) const; - -protected: -private: - - // NOTE: if you ever add/remove/change the enums in ThingType, - // you must also modify initFromDict()! - enum ThingType - { - GENERIC, // if a thing is nothing else, it's generic. - BUILDINGS, - - THING_TYPE_COUNT - }; - - Real m_handicaps[HANDICAP_TYPE_COUNT][THING_TYPE_COUNT]; - - static ThingType getBestThingType(const ThingTemplate *tmpl); -}; diff --git a/Generals/Code/GameEngine/Include/Common/MissionStats.h b/Generals/Code/GameEngine/Include/Common/MissionStats.h deleted file mode 100644 index d4f935d02e6..00000000000 --- a/Generals/Code/GameEngine/Include/Common/MissionStats.h +++ /dev/null @@ -1,83 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: MissionStats.h //////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: RTS3 -// -// File name: MissionStats.h -// -// Created: Steven Johnson, October 2001 -// -// Desc: @todo -// -//----------------------------------------------------------------------------- - -#pragma once - -#include "Common/GameCommon.h" -#include "Common/Snapshot.h" - -// ---------------------------------------------------------------------------------------------- -/** - Class that accumulates stats during a mission. Some of this will be for scoring purposes, - and some will probably be used by AI to determine future moves. - - @todo: not sure what need to be here. Alas. For now, I have just put in the fields from RA2 - that are indicated as being used for scoring in multiplayer games, so this will certainly - increase. -*/ -class MissionStats : public Snapshot -{ - -public: - - MissionStats(); - - /// reset all stats to "nothing". - void init(); - -protected: - - // snapshot methods - virtual void crc( Xfer *xfer ) override; - virtual void xfer( Xfer *xfer ) override; - virtual void loadPostProcess() override; - -private: - - Int m_unitsKilled[MAX_PLAYER_COUNT]; ///< how many units for each Player were killed by us? - Int m_unitsLost; ///< how many of our units were destroyed? - Int m_buildingsKilled[MAX_PLAYER_COUNT]; ///< how many buildings for each Player were killed by us? - Int m_buildingsLost; ///< how many of our buildings were destroyed? - //Int m_whoLastHurtMe; ///< last Player to destroy one of my units -}; diff --git a/Generals/Code/GameEngine/Include/Common/Money.h b/Generals/Code/GameEngine/Include/Common/Money.h deleted file mode 100644 index dab0b3ba89a..00000000000 --- a/Generals/Code/GameEngine/Include/Common/Money.h +++ /dev/null @@ -1,112 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: Money.h //////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: RTS3 -// -// File name: Money.h -// -// Created: Steven Johnson, October 2001 -// -// Desc: @todo -// -//----------------------------------------------------------------------------- - -#pragma once - -#include "Common/Debug.h" -#include "Common/Snapshot.h" - -class AudioEventRTS; - -// ---------------------------------------------------------------------------------------------- -/** - How much "money" (Tiberium, Gems, Magic Resource Boxes, whatever) the Player has. - This is currently a Very Simple Class but is encapsulated - in anticipation of future expansion. -*/ -class Money : public Snapshot -{ - -public: - - Money() : m_playerIndex(0) - { - init(); - } - - void init() - { - setStartingCash(0); - } - - UnsignedInt countMoney() const - { - return m_money; - } - - /// returns the actual amount withdrawn, which may be less than you want. (sorry, can't go into debt...) - UnsignedInt withdraw(UnsignedInt amountToWithdraw, Bool playSound = TRUE); - void deposit(UnsignedInt amountToDeposit, Bool playSound = TRUE, Bool trackIncome = TRUE); - - void setStartingCash(UnsignedInt amount); - void updateIncomeBucket(); - UnsignedInt getCashPerMinute() const; - - void setPlayerIndex(Int ndx) { m_playerIndex = ndx; } - - static void parseMoneyAmount( INI *ini, void *instance, void *store, const void* userData ); - - // Does the amount of this == the amount of that (compare everything except m_playerIndex) - Bool amountEqual( const Money & that ) const - { - return m_money == that.m_money; - } - -protected: - - void triggerAudioEvent(const AudioEventRTS& audioEvent); - - // snapshot methods - virtual void crc( Xfer *xfer ) override; - virtual void xfer( Xfer *xfer ) override; - virtual void loadPostProcess() override; - -private: - - UnsignedInt m_money; ///< amount of money - Int m_playerIndex; ///< what is my player index? - UnsignedInt m_incomeBuckets[60]; ///< circular buffer of 60 seconds for income tracking - UnsignedInt m_currentBucket; - UnsignedInt m_cashPerMinute; -}; diff --git a/Generals/Code/GameEngine/Include/Common/Player.h b/Generals/Code/GameEngine/Include/Common/Player.h deleted file mode 100644 index 06f99d50a41..00000000000 --- a/Generals/Code/GameEngine/Include/Common/Player.h +++ /dev/null @@ -1,843 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: Player.h //////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: RTS3 -// -// File name: Player.h -// -// Created: Steven Johnson, October 2001 -// -// Desc: @todo -// -//----------------------------------------------------------------------------- - -#pragma once - -#include "Common/AcademyStats.h" -#include "Common/Debug.h" -#include "Common/Energy.h" -#include "Common/GameType.h" -#include "Common/Handicap.h" -#include "Common/KindOf.h" -#include "Common/MissionStats.h" -#include "Common/Money.h" -#include "Common/Science.h" -#include "Common/UnicodeString.h" -#include "Common/NameKeyGenerator.h" -#include "Common/Thing.h" -#include "Common/STLTypedefs.h" -#include "Common/ScoreKeeper.h" -#include "Common/Team.h" -#include "Common/Upgrade.h" - -// ---------------------------------------------------------------------------------------------- - -class BuildListInfo; -class PolygonTrigger; -class ThingTemplate; -class AIPlayer; -class AIGroup; -class GameMessage; -class ResourceGatheringManager; -class PlayerTemplate; -class Squad; -class Team; -class TeamPrototype; -class TeamRelationMap; -class TunnelTracker; -class Upgrade; -class UpgradeTemplate; -class SpecialPowerModule; - -struct BattlePlanBonusesData; -class BattlePlanBonuses; - -enum BattlePlanStatus CPP_11(: Int); -enum UpgradeStatusType CPP_11(: Int); -enum CommandSourceType CPP_11(: Int); - -enum ScienceAvailabilityType CPP_11(: Int) -{ - SCIENCE_AVAILABILITY_INVALID = -1, - - SCIENCE_AVAILABLE, - SCIENCE_DISABLED, - SCIENCE_HIDDEN, - - SCIENCE_AVAILABILITY_COUNT, -}; - -#ifdef DEFINE_SCIENCE_AVAILABILITY_NAMES -static const char *const ScienceAvailabilityNames[] = -{ - "Available", - "Disabled", - "Hidden", - nullptr -}; -static_assert(ARRAY_SIZE(ScienceAvailabilityNames) == SCIENCE_AVAILABILITY_COUNT + 1, "Incorrect array size"); -#endif // end DEFINE_SCIENCE_AVAILABILITY_NAMES - -static const Int NUM_HOTKEY_SQUADS = 10; - -enum { NO_HOTKEY_SQUAD = -1 }; - -// ------------------------------------------------------------------------------------------------ -typedef Int PlayerIndex; -#define PLAYER_INDEX_INVALID -1 - -// ------------------------------------------------------------------------------------------------ -class KindOfPercentProductionChange : public MemoryPoolObject -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(KindOfPercentProductionChange, "KindOfPercentProductionChange") -public: - KindOfMaskType m_kindOf; - Real m_percent; - UnsignedInt m_ref; -}; -EMPTY_DTOR(KindOfPercentProductionChange) - -// ------------------------------------------------------------------------------------------------ -struct SpecialPowerReadyTimerType -{ - SpecialPowerReadyTimerType() - { - clear(); - } - void clear() - { - m_readyFrame = 0xffffffff; - m_templateID = INVALID_ID; - }; - - UnsignedInt m_templateID; ///< The ID of the specialpower template associated with this timer... no dupes allowed - UnsignedInt m_readyFrame; ///< on what game frame will this special power be ready? -}; - - - -// ------------------------------------------------------------------------------------------------ -typedef std::hash_map< PlayerIndex, Relationship, std::hash, std::equal_to/**/> PlayerRelationMapType; -class PlayerRelationMap : public MemoryPoolObject, - public Snapshot -{ - - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( PlayerRelationMap, "PlayerRelationMapPool" ) - -public: - - PlayerRelationMap(); - // virtual destructor provided by memory pool object - - /** @todo I'm just wrapping this up in a nice snapshot object, we really should isolate - * m_map from public access and make access methods for our operations */ - PlayerRelationMapType m_map; - -protected: - - virtual void crc( Xfer *xfer ) override; - virtual void xfer( Xfer *xfer ) override; - virtual void loadPostProcess() override; - -}; - -// ---------------------------------------------------------------------------------------------- -/** - A "Player" as an entity that contains the persistent info of the Player, as well as containing - transient mission data. - - Some of the Player's attributes persist between missions, whereas others are "transient" and only - have meaning in a mission, wherein they change a lot (current tech tree state, current buildings - built, units trained, money, etc). (For clarity of nomenclature, we'll refer to all "persistent" - vs "non-persistent" attributes, since "transient" has an unclear duration.) - - A "Player" consists of an entity controlling a single set of units in a mission. - A Player may be human or computer controlled. - - All Players have a (transient) "Player Index" associated which allows us to do some shorthand for - representing Players in some cases (mainly in bitfields). This is always a 0-based - number (-1 is used as an illegal index). Note that a logical conclusion of this - is that it makes it desirable to limit the maximum number of simultaneous Players - to 32, but that seems quite reasonable. - - All persistent data associated with the Player will be saved to local storage and/or - synchronized with one of our servers for online play. - - Note, simple accessor methods are omitted for brevity... for now, you may infer - them from the data structures. - - Note also that the class (and the relevant subclasses) are almost certainly incomplete; - a short perusal of the RA2 equivalent class(es) have waaay more tweaky data fields, - some of which will probably be necessary (in some form, at some point), some of - which won't ever be necessary. Rather than trying to guess at all of them here, - we're limiting the initial setup to be the almost-certainly-necessary, filling in - the extra things as needed. (Note that most of these will be non-persistent!) -*/ -class Player : public Snapshot -{ -public: - - Player( Int playerIndex ); - virtual ~Player(); - - void update(); ///< player update opportunity - - void newMap(); ///< player after map loaded opportunity - - void init(const PlayerTemplate* pt); - void initFromDict(const Dict* d); - void setDefaultTeam(); - - void deletePlayerAI(); - - UnicodeString getPlayerDisplayName() { return m_playerDisplayName; } - NameKeyType getPlayerNameKey() const { return m_playerNameKey; } - - AsciiString getSide() const { return m_side; } - AsciiString getBaseSide() const { return m_baseSide; } - - const PlayerTemplate* getPlayerTemplate() const { return m_playerTemplate; } - /// return the Player's Handicap sub-object - const Handicap *getHandicap() const { return &m_handicap; } - Handicap *getHandicap() { return &m_handicap; } - - /// return the Player's Money sub-object - Money *getMoney() { return &m_money; } - const Money *getMoney() const { return &m_money; } - - UnsignedInt getSupplyBoxValue();///< Many things can affect the value of a crate, but at heart it is a GlobalData ratio. - - Energy *getEnergy() { return &m_energy; } - const Energy *getEnergy() const { return &m_energy; } - - // adds a power bonus to this player because of energy upgrade at his power plants - void addPowerBonus(Object *obj) { m_energy.addPowerBonus(obj); } - void removePowerBonus(Object *obj) { m_energy.removePowerBonus(obj); } - - ResourceGatheringManager *getResourceGatheringManager(){ return m_resourceGatheringManager; } - TunnelTracker* getTunnelSystem(){ return m_tunnelSystem; } - - Color getPlayerColor() const { return m_color; } - Color getPlayerNightColor() const { return m_nightColor;} - /// return the type of controller - PlayerType getPlayerType() const { return m_playerType; } - void setPlayerType(PlayerType t, Bool skirmish); - - PlayerIndex getPlayerIndex() const { return m_playerIndex; } - - /// return a bitmask that is unique to this player. - PlayerMaskType getPlayerMask() const { return 1 << m_playerIndex; } - - /// a convenience function to test the ThingTemplate against the players canBuild flags - /// called by canBuild - Bool allowedToBuild(const ThingTemplate *tmplate) const; - - /// true if we have the prereqs for this item - Bool canBuild(const ThingTemplate *tmplate) const; - - // Can we afford to build? - Bool canAffordBuild( const ThingTemplate *whatToBuild ) const; - - // Check MaxSimultaneousOfType - Bool canBuildMoreOfType( const ThingTemplate *whatToBuild ) const; - - /// Difficulty level for this player. - GameDifficulty getPlayerDifficulty() const; - - /** return the player's command center. (must be one of his "normal" ones, - not a captured one.) - if he has none, return null. - if he has multiple, return one arbitrarily. */ - Object* findNaturalCommandCenter(); - - Object* findAnyExistingObjectWithThingTemplate( const ThingTemplate *thing ); - - // Finds a short-cut firing special power of specified type returning the first ready power or - // the most ready if none ready. - Object* findMostReadyShortcutSpecialPowerOfType( SpecialPowerType spType ); - - //Find specified thing template's most ready weapon. - Object* findMostReadyShortcutWeaponForThing( const ThingTemplate *thing, UnsignedInt &mostReadyPercentage ); - Object* findMostReadyShortcutSpecialPowerForThing( const ThingTemplate *thing, UnsignedInt &mostReadyPercentage ); - - // Finds a short-cut firing special power of any type arbitrarily. - Bool hasAnyShortcutSpecialPower(); - - // Counts available shortcut special power of specified type that can fire now. - Int countReadyShortcutSpecialPowersOfType( SpecialPowerType spType ); - - /// return t if the player has the given science, either intrinsically, via specialization, or via capture. - Bool hasScience(ScienceType t) const; - Bool isScienceDisabled( ScienceType t ) const; ///< Can't purchase this science because of script reasons. - Bool isScienceHidden( ScienceType t ) const; ///< This science is effectively hidden due to script reasons. - - //Allows scripts to make specific sciences available, hidden, or disabled. - void setScienceAvailability( ScienceType science, ScienceAvailabilityType type ); - - ScienceAvailabilityType getScienceAvailabilityTypeFromString( const AsciiString& name ); - - /// return t iff the player has all sciences that are prereqs for knowing the given science - Bool hasPrereqsForScience(ScienceType t) const; - - Bool hasUpgradeComplete( const UpgradeTemplate *upgradeTemplate ) const; ///< does player have totally done and produced upgrade - Bool hasUpgradeComplete( const UpgradeMaskType& testMask ) const; ///< does player have totally done and produced upgrade - const UpgradeMaskType& getCompletedUpgradeMask() const { return m_upgradesCompleted; } ///< get list of upgrades that are completed - Bool hasUpgradeInProduction( const UpgradeTemplate *upgradeTemplate ); ///< does player have this upgrade in progress right now - Upgrade *addUpgrade( const UpgradeTemplate *upgradeTemplate, - UpgradeStatusType status ); ///< add upgrade, or update existing upgrade status - void removeUpgrade( const UpgradeTemplate *upgradeTemplate ); ///< remove this upgrade from us - - /** find upgrade, NOTE, the upgrade may *NOT* be "complete" and therefore "active", it could be in production - This function is for actually retrieving the Upgrade. To test existence, use the fast bit testers hasUpgradeX() - */ - Upgrade *findUpgrade( const UpgradeTemplate *upgradeTemplate ); - - void onUpgradeCompleted( const UpgradeTemplate *upgradeTemplate ); ///< An upgrade just finished, do things like tell all objects to recheck UpgradeModules - void onUpgradeRemoved(){} ///< An upgrade just got removed, this doesn't do anything now. - -#if defined(RTS_DEBUG) - /// Prereq disabling cheat key - void toggleIgnorePrereqs(){ m_DEMO_ignorePrereqs = !m_DEMO_ignorePrereqs; } - void enableIgnorePrereqs(Bool enable) { m_DEMO_ignorePrereqs = enable; } - Bool ignoresPrereqs() const { return m_DEMO_ignorePrereqs; } - - /// No cost building cheat key - void toggleFreeBuild(){ m_DEMO_freeBuild = !m_DEMO_freeBuild; } - void enableFreeBuild(Bool enable) { m_DEMO_freeBuild = enable; } - Bool buildsForFree() const { return m_DEMO_freeBuild; } - -#endif - -#if defined(RTS_DEBUG) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) - /// No time building cheat key - void toggleInstantBuild(){ m_DEMO_instantBuild = !m_DEMO_instantBuild; } - void enableInstantBuild(Bool enable) { m_DEMO_instantBuild = enable; } - Bool buildsInstantly() const { return m_DEMO_instantBuild; } -#endif - - ///< Power just changed at all. Didn't make two functions so you can't forget to undo something you didin one of them. - ///< @todo Can't do edge trigger until after demo; make things check for power on creation - void onPowerBrownOutChange( Bool brownOut ); - - - ///< one of my command centers just fired a special power, let us reset timers for all command centers. - void resetOrStartSpecialPowerReadyFrame( const SpecialPowerTemplate *temp ); - ///< my new command center wants to init his timers to the status quo - UnsignedInt getOrStartSpecialPowerReadyFrame( const SpecialPowerTemplate *temp); - void expressSpecialPowerReadyFrame( const SpecialPowerTemplate *temp, UnsignedInt frame ); - void addNewSharedSpecialPowerTimer( const SpecialPowerTemplate *temp, UnsignedInt frame ); - - - void addRadar( Bool disableProof );///< One more producer of Radar exists - void removeRadar( Bool disableProof );///< One less thing produces radar - void disableRadar(); ///< No matter how many radar producers I have, I do not have radar - void enableRadar(); ///< remove the restriction imposed by disableRadar - Bool hasRadar() const;///< A positive number of radar producers, plus my radar is not disabled - Bool okToPlayRadarEdgeSound();///< just like it "sounds" - //Battle plans effect the players abilities... so may as well add it here. Also - //it's possible for multiple strategy centers to have the same plan, so we need - //to keep track of that like radar. Keep in mind multiple strategy centers with - //same plan do not stack, but different strategy centers with different plans do. - void changeBattlePlan( BattlePlanStatus plan, Int delta, const BattlePlanBonusesData *bonus ); - Int getNumBattlePlansActive() const { return m_bombardBattlePlans + m_holdTheLineBattlePlans + m_searchAndDestroyBattlePlans; } - Int getBattlePlansActiveSpecific( BattlePlanStatus plan ) const; - void applyBattlePlanBonusesForObject( Object *obj ) const; //New object or converted object gaining our current battle plan bonuses. - void removeBattlePlanBonusesForObject( Object *obj ) const; //Object left team - void applyBattlePlanBonusesForPlayerObjects( const BattlePlanBonusesData *bonus ); //Battle plan bonuses changing, so apply to all of our objects! - Bool doesObjectQualifyForBattlePlan( Object *obj ) const; - - // If apply is false, then we are repealing already granted bonuses. - // Note: Should only be called by Object. - void friend_applyDifficultyBonusesForObject(Object* obj, Bool apply) const; - - /// Decrement the ref counter on the typeof production list node - void removeKindOfProductionCostChange(KindOfMaskType kindOf, Real percent); - /// add type of production cost change (Used for upgrades) - void addKindOfProductionCostChange( KindOfMaskType kindOf, Real percent); - /// Returns production cost change based on typeof (Used for upgrades) - Real getProductionCostChangeBasedOnKindOf( KindOfMaskType kindOf ) const; - - /** Return bonus or penalty for construction of this thing. - */ - Real getProductionCostChangePercent( AsciiString buildTemplateName ) const; - - /** Return bonus or penalty for construction of this thing. - */ - Real getProductionTimeChangePercent( AsciiString buildTemplateName ) const; - - /** Return starting veterancy level of a newly built thing of this type - */ - VeterancyLevel getProductionVeterancyLevel( AsciiString buildTemplateName ) const; - - // Friend function for the script engine's usage. - void friend_setSkillset(Int skillSet); - - /** - the given object has just become (or just ceased to be) a member of one of our teams (or subteams) - */ - void becomingTeamMember(Object *obj, Bool yes); - - /** - this is called when the player becomes the local player (yes==true) - or ceases to be the local player (yes==false). you can't stop this - from happening; you can only react to it. - */ - void becomingLocalPlayer(Bool yes); - - /// Is this player the local player? - Bool isLocalPlayer() const; - - /// this player should be listed in the score screen. - void setListInScoreScreen(Bool listInScoreScreen); - - /// return TRUE if this player should be listed in the score screen. - Bool getListInScoreScreen(); - - /// A unit was just created and is ready to control - void onUnitCreated( Object *factory, Object *unit ); - - /// A team is about to be destroyed. - void preTeamDestroy( const Team *team ); - - /// Is the nearest supply source safe? - Bool isSupplySourceSafe( Int minSupplies ); - - /// Is a supply source attacked? - Bool isSupplySourceAttacked(); - - /// Set delay between team production. - void setTeamDelaySeconds(Int delay); - - /// Have the team guard a supply center. - void guardSupplyCenter( Team *team, Int minSupplies ); - - virtual Bool computeSuperweaponTarget(const SpecialPowerTemplate *power, Coord3D *pos, Int playerNdx, Real weaponRadius); ///< Calculates best pos for weapon given radius. - - /// Get the enemy an ai player is currently focused on. NOTE - Can be nullptr. - Player *getCurrentEnemy(); - - /// Is this player a skirmish ai player? - Bool isSkirmishAIPlayer(); - - /// Have the ai check for bridges. - virtual Bool checkBridges(Object *unit, Waypoint *way); - - /// Get the center of the ai's base. - virtual Bool getAiBaseCenter(Coord3D *pos); - - /// Have the ai check for bridges. - virtual void repairStructure(ObjectID structureID); - - /// a structure was just created, but is under construction - void onStructureCreated( Object *builder, Object *structure ); - - /// a structure that was under construction has become completed - void onStructureConstructionComplete( Object *builder, Object *structure, Bool isRebuild ); - - /// a structure that was created has been pre-emptively removed and shouldn't be counted in the score. - void onStructureUndone(Object *structure); - - /** - a convenience routine to count the number of owned objects that match a set of ThingTemplates. - You input the count and an array of ThingTemplate*, and provide an array of Int of the same - size. It fills in the array to the correct counts. This is handy because we must traverse - the player's list-of-objects only once. - */ - void countObjectsByThingTemplate(Int numTmplates, const ThingTemplate* const * things, Bool ignoreDead, Int *counts, Bool ignoreUnderConstruction = TRUE ) const; - - /** - simply returns the number of buildings owned by this player - */ - Int countBuildings(); - - /** - simply returns the number of objects owned by this player with a specific KindOfMaskType - */ - Int countObjects(KindOfMaskType setMask, KindOfMaskType clearMask); - - /// Returns the closest of a given type to the given object - Object *findClosestByKindOf( Object *queryObject, KindOfMaskType setMask, KindOfMaskType clearMask ); - - /** - a convenience routine to quickly check if any buildings are owned. - */ - Bool hasAnyBuildings() const; - - /** - a convenience routine to quickly check if any buildings with a specific KindOfType flag are owned. - */ - Bool hasAnyBuildings(KindOfMaskType kindOf) const; - - /** - a convenience routine to quickly check if any units are owned. - */ - Bool hasAnyUnits() const; - - /** - a convenience routine to quickly check if any objects are owned. - */ - Bool hasAnyObjects() const; - - /** - a convenience routine to quickly check if any buildfacilities are owned. - */ - Bool hasAnyBuildFacility() const; - - /** - a convenience routine to quickly update the state flags on all teams. - */ - void updateTeamStates(); - - /** - This player will heal everything owned by it - */ - void healAllObjects(); - - /** - * Iterate all objects that this player has - */ - void iterateObjects( ObjectIterateFunc func, void *userData ) const; - - /** - return this player's "default" team. - */ - Team *getDefaultTeam() { DEBUG_ASSERTCRASH(m_defaultTeam!=nullptr,("default team is null")); return m_defaultTeam; } - const Team *getDefaultTeam() const { DEBUG_ASSERTCRASH(m_defaultTeam!=nullptr,("default team is null")); return m_defaultTeam; } - - void setBuildList(BuildListInfo *pBuildList); ///< sets the build list. - BuildListInfo *getBuildList() { return m_pBuildList; } ///< returns the build list. (build list might be modified by the solo AI) - void addToBuildList(Object *obj); ///< Adds this to the build list. Used for factories placed instead of in build list. - void addToPriorityBuildList(AsciiString templateName, Coord3D *pos, Real angle); ///< Adds this to the build list. Used for factories placed instead of in build list. - - /// get the relationship between this->that. - Relationship getRelationship(const Team *that) const; - - /// set the relationship between this->that. (note that this doesn't affect the that->this relationship.) - void setPlayerRelationship(const Player *that, Relationship r); - Bool removePlayerRelationship(const Player *that); - void setTeamRelationship(const Team *that, Relationship r); - Bool removeTeamRelationship(const Team *that); - - void addTeamToList(TeamPrototype* team); - void removeTeamFromList(TeamPrototype* team); - - typedef std::list PlayerTeamList; - const PlayerTeamList* getPlayerTeams() const { return &m_playerTeamPrototypes; } - - Int getMpStartIndex() {return m_mpStartIndex;} - - /// Set that all units should begin hunting. - void setUnitsShouldHunt(Bool unitsShouldHunt, CommandSourceType source); - Bool getUnitsShouldHunt() const { return m_unitsShouldHunt; } - - /// All of our units are new spied upon; they sight for the given enemy -#if RTS_GENERALS - void setUnitsVisionSpied( Bool setting, PlayerIndex byWhom ); - - /// This will be asked by units when they look to get extra people to sight for - PlayerMaskType getVisionSpiedMask() const; -#else - void setUnitsVisionSpied( Bool setting, KindOfMaskType whichUnits, PlayerIndex byWhom ); -#endif - - /// Destroy all of the teams for this player, causing him to DIE. - void killPlayer(); - - /// Enabled/Disable all objects of type templateTypeToAffect - void setObjectsEnabled(AsciiString templateTypeToAffect, Bool enable); - - /// Build an instance of a specific team. Gets passed to aiPlayer. - void buildSpecificTeam(TeamPrototype *teamProto); - - /// Build an instance of a specific building. Gets passed to aiPlayer. - void buildSpecificBuilding(const AsciiString &thingName); - - /// Build a building near a supply dump with at least cash. Gets passed to aiPlayer. - void buildBySupplies(Int minimumCash, const AsciiString &thingName); - - /// Build an instance of a specific building nearest specified team. Gets passed to aiPlayer. - void buildSpecificBuildingNearestTeam( const AsciiString &thingName, const Team *team ); - - /// Build an upgrade. Gets passed to aiPlayer. - void buildUpgrade(const AsciiString &upgrade); - - /// Build base defense on front or flank of base. Gets passed to aiPlayer. - void buildBaseDefense(Bool flank); - - /// Build structure type on front or flank of base. Gets passed to aiPlayer. - void buildBaseDefenseStructure(const AsciiString &thingName, Bool flank); - - /// Recruits an instance of a specific team. Gets passed to aiPlayer. - void recruitSpecificTeam(TeamPrototype *teamProto, Real recruitRadius); - - /// Calculates the closest construction zone location based on a template. Gets plassed to aiPlayer - Bool calcClosestConstructionZoneLocation( const ThingTemplate *constructTemplate, Coord3D *location ); - - /// Enable/Disable the construction of units - Bool getCanBuildUnits() { return m_canBuildUnits; } - void setCanBuildUnits(Bool canProduce) { m_canBuildUnits = canProduce; } - - /// Enable/Disable the construction of base buildings. - Bool getCanBuildBase() { return m_canBuildBase; } - void setCanBuildBase(Bool canProduce) { m_canBuildBase = canProduce; } - - /// Transfer all assets from player that to this - void transferAssetsFromThat(Player* that); - - /// Sell everything this player owns. - void sellEverythingUnderTheSun(); - - void garrisonAllUnits(CommandSourceType source); - void ungarrisonAllUnits(CommandSourceType source); - - void setUnitsShouldIdleOrResume(Bool idle); - - Bool isPlayableSide() const; - - Bool isPlayerObserver() const; // Favor !isPlayerActive() - this is used for Observer GUI mostly, not in-game stuff - Bool isPlayerDead() const; // Favor !isPlayerActive() - this is used so OCLs don't give us stuff after death. - Bool isPlayerActive() const; // Player is alive and not observer. !isPlayerActive() is synonymous with observing. - - Bool didPlayerPreorder() const { return m_isPreorder; } - - /// Grab the scorekeeper so we can score up in here! - ScoreKeeper* getScoreKeeper() { return &m_scoreKeeper; } - - /// time to create a hotkey team based on this GameMessage - void processCreateTeamGameMessage(Int hotkeyNum, const GameMessage *msg); - - /// time to select a hotkey team based on this GameMessage - void processSelectTeamGameMessage(Int hotkeyNum); - - // add to the player's current selection this hotkey team. - void processAddTeamGameMessage(Int hotkeyNum); - - // fills an AIGroup object that is the currently selected group. - void getCurrentSelectionAsAIGroup(AIGroup *group); - - // sets the currently selected group to be the given AIGroup - void setCurrentlySelectedAIGroup(AIGroup *group); - - // adds the given AIGroup to the current selection of this player. - void addAIGroupToCurrentSelection(AIGroup *group); - - // return the requested hotkey squad - Squad *getHotkeySquad(Int squadNumber); - - // return the hotkey squad that a unit is in, or NO_HOTKEY_SQUAD if it isn't in one. - Int getSquadNumberForObject(const Object *objToFind) const; - - // remove an object from any hotkey squads that its in. - void removeObjectFromHotkeySquad(Object *objToRemove); - - void setAttackedBy( Int playerNdx ); - Bool getAttackedBy( Int playerNdx ) const; - UnsignedInt getAttackedFrame() {return m_attackedFrame;} // Return last frame attacked. - - Real getCashBounty() const { return m_cashBountyPercent; } - void setCashBounty(Real percentage) { m_cashBountyPercent = percentage; } - void doBountyForKill(const Object* killer, const Object* victim); - - AcademyStats* getAcademyStats() { return &m_academyStats; } - const AcademyStats* getAcademyStats() const { return &m_academyStats; } - - //Set via logical message. Options menu sets the client value in global data. Player::update() - //detects a change, and posts a message. When the message gets processed, this value gets set. - Bool isLogicalRetaliationModeEnabled() const { return m_logicalRetaliationModeEnabled; } - void setLogicalRetaliationModeEnabled( Bool set ) { m_logicalRetaliationModeEnabled = set; } - -private: - - /** give the science. doesn't check prereqs, nor charge to purchase points... - just grants it! so be careful! NOTE that this is private to Player, - and for a good reason; if public, this could be used to grant sciences - that shouldn't be directly granted (e.g., SCIENCE_RankX, which should - be managed via setRankLevel instead). If you think you need to use - this call externally, you probably don't... you should probably be - using grantScience() instead. - */ - Bool addScience(ScienceType science); - -public: - Int getSkillPoints() const { return m_skillPoints; } - Int getSciencePurchasePoints() const { return m_sciencePurchasePoints; } - Int getRankLevel() const { return m_rankLevel; } - Int getSkillPointsLevelUp() const { return m_levelUp; } - Int getSkillPointsLevelDown() const { return m_levelDown; } - UnicodeString getGeneralName() const { return m_generalName; } - void setGeneralName( UnicodeString name ){ m_generalName = name; } - /// returns TRUE if rank level really changed. - Bool setRankLevel(Int level); - - /// returns TRUE if the player gained/lost levels as a result. - Bool addSkillPoints(Int delta); - - /// returns TRUE if the player gained/lost levels as a result. - Bool addSkillPointsForKill(const Object* killer, const Object* victim); - - void addSciencePurchasePoints(Int delta); - - void setSkillPointsModifier(Real expMod) { m_skillPointsModifier = expMod; } - Real getSkillPointsModifier() const { return m_skillPointsModifier; } - - /// reset the sciences to just the intrinsic ones from the playertemplate, if any. - void resetSciences(); - - /// reset rank to 1. - void resetRank(); - - /** - attempt to purchase the science, but use prereqs, and charge points. - return true if successful. - */ - Bool attemptToPurchaseScience(ScienceType science); - - /** - grant the science, ignore prereqs & charge no points, - but still restrict you to purchasable sciences (ie, intrinsic and rank sciences - are not allowed) - return true if successful. - */ - Bool grantScience(ScienceType science); - - /** return true attemptToPurchaseScience() would succeed for this science. */ - Bool isCapableOfPurchasingScience(ScienceType science) const; - -protected: - - // snapshot methods - virtual void crc( Xfer *xfer ) override; - virtual void xfer( Xfer *xfer ) override; - virtual void loadPostProcess() override; - - void deleteUpgradeList(); ///< delete all our upgrades - -private: - - const PlayerTemplate* m_playerTemplate; ///< Pointer back to the Player Template - - UnicodeString m_playerDisplayName; ///< This player's persistent name. - Handicap m_handicap; ///< adjustment to varied capabilities (@todo: is this persistent or recalced each time?) - AsciiString m_playerName; ///< player's internal name (for matching map objects) - NameKeyType m_playerNameKey; ///< This player's internal name (for matching map objects) - PlayerIndex m_playerIndex; ///< player unique index. - AsciiString m_side; ///< the "side" this player is on - AsciiString m_baseSide; ///< the base side, GLA, USA, or China - PlayerType m_playerType; ///< human/computer control - Money m_money; ///< Player's current wealth - Upgrade* m_upgradeList; ///< list of all upgrades this player has - Int m_radarCount; ///< # of facilities that have a radar under the players control - Int m_disableProofRadarCount; ///< # of disable proof radars. A disable proof one will be in both refcounts - Bool m_radarDisabled; ///< The radar is disabled regardless of the number of radar objects - Int m_bombardBattlePlans; ///< Number of strategy centers with active bombardment plan - Int m_holdTheLineBattlePlans; ///< Number of strategy centers with active hold the line plan - Int m_searchAndDestroyBattlePlans;///< Number of strategy centers with active search and destroy plan - BattlePlanBonuses* m_battlePlanBonuses; - UpgradeMaskType m_upgradesInProgress; ///< Bit field of in Production status upgrades - UpgradeMaskType m_upgradesCompleted; ///< Bit field of upgrades completed. Bits are assigned by UpgradeCenter - Energy m_energy; ///< current energy production & consumption - MissionStats m_stats; ///< stats about the current mission (units destroyed, etc) - BuildListInfo* m_pBuildList; ///< linked list of buildings for PLAYER_COMPUTER. - Color m_color; ///< color for our units - Color m_nightColor; /// KindOfPercentProductionChangeList; - typedef KindOfPercentProductionChangeList::iterator KindOfPercentProductionChangeListIt; - mutable KindOfPercentProductionChangeList m_kindOfPercentProductionChangeList; - - - typedef std::list SpecialPowerReadyTimerList; - typedef SpecialPowerReadyTimerList::iterator SpecialPowerReadyTimerListIterator; - SpecialPowerReadyTimerList m_specialPowerReadyTimerList; - - Squad *m_squads[NUM_HOTKEY_SQUADS]; ///< The hotkeyed squads - Squad *m_currentSelection; ///< This player's currently selected group - - Bool m_isPlayerDead; - Bool m_logicalRetaliationModeEnabled; -}; diff --git a/Generals/Code/GameEngine/Include/Common/PlayerList.h b/Generals/Code/GameEngine/Include/Common/PlayerList.h deleted file mode 100644 index 1db78978be9..00000000000 --- a/Generals/Code/GameEngine/Include/Common/PlayerList.h +++ /dev/null @@ -1,181 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: PlayerList.h //////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: RTS3 -// -// File name: PlayerList.h -// -// Created: Steven Johnson, October 2001 -// -// Desc: @todo -// -//----------------------------------------------------------------------------- - -#pragma once - -#include "Common/SubsystemInterface.h" -#include "Common/GameCommon.h" -#include "Common/NameKeyGenerator.h" -#include "Common/Snapshot.h" -#include "GameNetwork/NetworkDefs.h" - -class DataChunkInput; -struct DataChunkInfo; -class DataChunkOutput; -class GameInfo; -class Player; -class Team; -class TeamFactory; - -//------------------------------------------------------------------------------------------------- -enum AllowPlayerRelationship CPP_11(: Int) -{ - ALLOW_SAME_PLAYER = 0x01, ///< allow only objects of the same player as m_obj - ALLOW_ALLIES = 0x02, ///< allow objects that m_obj considers allies - ALLOW_ENEMIES = 0x04, ///< allow objects that m_obj considers enemy - ALLOW_NEUTRAL = 0x08 ///< allow objects that m_obj considers neutral -}; - - -//------------------------------------------------------------------------------------------------- -/** - This is a singleton class that maintains the list of Players. -*/ -class PlayerList : public SubsystemInterface, - public Snapshot -{ - -public: - - PlayerList(); - virtual ~PlayerList() override; - - // subsystem methods - virtual void init() override; - virtual void reset() override; - virtual void update() override; - - virtual void newGame(); // called during GameLogic::startNewGame() - virtual void newMap(); // Called after a new map is loaded. - - void teamAboutToBeDeleted(Team* team); - - /** - return the total number of players (including the neutral player). - */ - inline Int getPlayerCount() { return m_playerCount; } - - /** - return the nth player. Note that players are in an arbitrary order. - you should generally only use this if you want to iterate thru - all players, NOT to get a specific player! - */ - Player *getNthPlayer(Int i); - - /** - return the "neutral" Player. there is always a player that is "neutral" wrt - all other players (this is so that everything can be associated with a nonnull - Player, to simplify the universe). This will never return null. - */ - Player *getNeutralPlayer() { DEBUG_ASSERTCRASH(m_players[0] != nullptr, ("null neutral")); return m_players[0]; } - - /** - return the Player with the given internal name, or null if none found. - */ - Player *findPlayerWithNameKey(NameKeyType key); - - /** - Return the "local" player (ie, the human playing the game). - This will never return null. - */ - inline Player *getLocalPlayer() { DEBUG_ASSERTCRASH(m_local != nullptr, ("null m_local")); return m_local; } - - /** - Set the local player. You cannot set it to null; if you pass null, you'll - end up setting the local player to be the neutral player. - */ - void setLocalPlayer(Player *player); - - /** - Return the player matching the player mask - */ - Player *getPlayerFromMask( PlayerMaskType mask ); - - /** - Get each player in numerical order that this mask represents. - Note that maskToAdjust will be adjusted by removing the associated player's mask from it. - */ - Player *getEachPlayerFromMask( PlayerMaskType& maskToAdjust ); - - Team *validateTeam( AsciiString owner ); - - /** - a convenience routine to quickly clear the entered/exited flags on all teams. - */ - void updateTeamStates(); - - /** - a convenience routine to return the players who srcPlayer considers to have one of the - relationships specified in allowedRelationships. Note that allowedRelationships should be - a bitwise OR of AllowPlayerRelationship flags. - */ - PlayerMaskType getPlayersWithRelationship( Int srcPlayerIndex, UnsignedInt allowedRelationships ); - - Int getSlotIndex(Int playerIndex) const; - Player *getPlayerFromSlotIndex(Int slotIndex) const; - -protected: - - // snapshot methods - virtual void crc( Xfer *xfer ) override; - virtual void xfer( Xfer *xfer ) override; - virtual void loadPostProcess() override; - - Int getPlayerIndexFromSlotIndex(Int slotIndex) const; - -private: - void assignSlotIndices(const GameInfo& gameInfo); - void setSlotIndex(Int playerIndex, Int slotIndex); - - Player *m_local; - Int m_playerCount; - Player *m_players[MAX_PLAYER_COUNT]; - Int m_slotIndices[MAX_PLAYER_COUNT]; - Int m_slotToPlayerIndices[MAX_SLOTS]; - -}; - - -// ---------------------------------------------------------------------------------------------- -extern PlayerList *ThePlayerList; ///< singleton instance of PlayerList diff --git a/Generals/Code/GameEngine/Include/Common/PlayerTemplate.h b/Generals/Code/GameEngine/Include/Common/PlayerTemplate.h deleted file mode 100644 index acbaeef7949..00000000000 --- a/Generals/Code/GameEngine/Include/Common/PlayerTemplate.h +++ /dev/null @@ -1,232 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: PlayerTemplate.h //////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: RTS3 -// -// File name: PlayerTemplate.h -// -// Created: Steven Johnson, October 2001 -// -// Desc: @todo -// -//----------------------------------------------------------------------------- - -#pragma once - -#include "Common/SubsystemInterface.h" -#include "Common/GameMemory.h" -#include "Common/Debug.h" -#include "Common/Handicap.h" -#include "Common/Money.h" -#include "Common/Science.h" -#include "Common/AsciiString.h" -#include "Common/UnicodeString.h" -#include "Common/NameKeyGenerator.h" -#include "Common/STLTypedefs.h" - - -// ---------------------------------------------------------------------------------------------- - -class INI; -struct FieldParse; -class Image; - -// ---------------------------------------------------------------------------------------------- - -#define MAX_MP_STARTING_UNITS 10 - -// ---------------------------------------------------------------------------------------------- -class PlayerTemplate -{ - -public: - - PlayerTemplate(); - - void setNameKey(NameKeyType namekey) { m_nameKey = namekey; } - - NameKeyType getNameKey() const { DEBUG_ASSERTCRASH(m_nameKey != NAMEKEY_INVALID, ("bad namekey")); return m_nameKey; } - AsciiString getName() const { return KEYNAME(m_nameKey); } - - UnicodeString getDisplayName() const { return m_displayName; } - - AsciiString getSide() const { return m_side; } - AsciiString getBaseSide() const { return m_baseSide; } - - /// return the tech tree for the player. - const Handicap *getHandicap() const { return &m_handicap; } - - /// return the money for the player. - const Money *getMoney() const { return &m_money; } - - const RGBColor* getPreferredColor() const { return &m_preferredColor; } - - AsciiString getStartingBuilding() const { return m_startingBuilding; } - AsciiString getStartingUnit( Int i ) const; - - const ProductionChangeMap& getProductionCostChanges() const { return m_productionCostChanges; } - const ProductionChangeMap& getProductionTimeChanges() const { return m_productionTimeChanges; } - const ProductionVeterancyMap& getProductionVeterancyLevels() const { return m_productionVeterancyLevels; } - Bool isObserver() const { return m_observer; } - Bool isPlayableSide() const { return m_playableSide; } - - AsciiString getScoreScreen () const { return m_scoreScreenImage; } - AsciiString getLoadScreen () const { return m_loadScreenImage; } - AsciiString getBeaconTemplate() const { return m_beaconTemplate; } - - const Image *getHeadWaterMarkImage() const; - const Image *getFlagWaterMarkImage() const; - const Image *getEnabledImage() const; - //const Image *getDisabledImage() const; - //const Image *getHiliteImage() const; - //const Image *getPushedImage() const; - const Image *getSideIconImage() const; - const Image *getGeneralImage() const; - const AsciiString getTooltip() const { return m_tooltip; } - const AsciiString getGeneralFeatures() const { return m_strGeneralFeatures; } - - AsciiString getMedallionNormal() const { return m_strMedallionNormal; } - AsciiString getMedallionHilite() const { return m_strMedallionHilite; } - AsciiString getMedallionSelected() const { return m_strMedallionSelected; } - - const ScienceVec& getIntrinsicSciences() const { return m_intrinsicSciences; } - Int getIntrinsicSciencePurchasePoints() const { return m_intrinsicSPP; } - AsciiString getPurchaseScienceCommandSetRank1() const {return m_purchaseScienceCommandSetRank1; } - AsciiString getPurchaseScienceCommandSetRank3() const {return m_purchaseScienceCommandSetRank3; } - AsciiString getPurchaseScienceCommandSetRank8() const {return m_purchaseScienceCommandSetRank8; } - - AsciiString getSpecialPowerShortcutCommandSet() const {return m_specialPowerShortcutCommandSet; } - AsciiString getSpecialPowerShortcutWinName() const {return m_specialPowerShortcutWinName; } - Int getSpecialPowerShortcutButtonCount() const {return m_specialPowerShortcutButtonCount; } - - AsciiString getLoadScreenMusic() const {return m_loadScreenMusic; } - AsciiString getScoreScreenMusic() const { return m_scoreScreenMusic; } - - Bool isOldFaction() const { return m_oldFaction; } - - static const FieldParse* getFieldParse(); - - -protected: - - // for parsing from INI - static void parseStartMoney( INI* ini, void *instance, void *store, const void* /*userData*/ ); - static void parseProductionCostChange( INI* ini, void *instance, void *store, const void* /*userData*/ ); - static void parseProductionTimeChange( INI* ini, void *instance, void *store, const void* /*userData*/ ); - static void parseProductionVeterancyLevel( INI* ini, void *instance, void *store, const void* /*userData*/ ); - -private: - - NameKeyType m_nameKey; - UnicodeString m_displayName; - AsciiString m_side, m_baseSide; - Handicap m_handicap; ///< initial baseline for Player capabilities - Money m_money; ///< starting credits, if any - RGBColor m_preferredColor; ///< our preferred starting color - AsciiString m_startingBuilding; ///< template name of our multiplayer start building (con yard, i'd expect) - AsciiString m_startingUnits[MAX_MP_STARTING_UNITS]; ///< template names of our multiplayer start units - ProductionChangeMap m_productionCostChanges; - ProductionChangeMap m_productionTimeChanges; - ProductionVeterancyMap m_productionVeterancyLevels; - ScienceVec m_intrinsicSciences; ///< sciences that this Player will always know - AsciiString m_purchaseScienceCommandSetRank1; ///< the command set we'll use when we want to purchase sciences - AsciiString m_purchaseScienceCommandSetRank3; ///< the command set we'll use when we want to purchase sciences - AsciiString m_purchaseScienceCommandSetRank8; ///< the command set we'll use when we want to purchase sciences - - AsciiString m_specialPowerShortcutCommandSet; ///< the command set we'll use when we want to show the shortcut to the special powers - AsciiString m_specialPowerShortcutWinName; ///< The name of the window we'll be using for the shortcut bar - Int m_specialPowerShortcutButtonCount; ///< The number of buttons located on the shortcut bar - AsciiString m_loadScreenMusic; ///< the load screen music we want to play - AsciiString m_scoreScreenMusic; ///< the score screen music we want to play - AsciiString m_tooltip; ///< The tooltip describing this player template - Bool m_observer; - Bool m_playableSide; - Bool m_oldFaction; ///< Faction existed in the original Generals - - Int m_intrinsicSPP; - - AsciiString m_scoreScreenImage; ///< Image that will be shown on the score screen - AsciiString m_loadScreenImage; - - AsciiString m_headWaterMark; ///< Image that will be the background on the observer control bar - AsciiString m_flagWaterMark; ///< Imabe that will be the background on the observer control bar - AsciiString m_enabledImage; ///< enable button image - //AsciiString m_disabledImage; ///< disabled button image - //AsciiString m_hiliteImage; ///< hilite button image - //AsciiString m_pushedImage; ///< pushed button image - AsciiString m_sideIconImage; ///< The little icon we show on game info screens for the sides - AsciiString m_generalImage; ///< The icon overlayed on the rank image in My Persona - - AsciiString m_beaconTemplate; ///< ThingTemplate name for beacons - - AsciiString m_strGeneralFeatures; ///< used in loadscreens - AsciiString m_strMedallionNormal; - AsciiString m_strMedallionHilite; - AsciiString m_strMedallionSelected; -}; - -// ---------------------------------------------------------------------------------------------- -/** - This is a singleton class that maintains the list of PlayerTemplates. -*/ -class PlayerTemplateStore : public SubsystemInterface -{ -public: - - PlayerTemplateStore(); - virtual ~PlayerTemplateStore() override; - - virtual void init() override; - virtual void reset() override; - virtual void update() override; - - static void parsePlayerTemplateDefinition( INI* ini ); - - const PlayerTemplate* getNthPlayerTemplate(Int i) const; - const PlayerTemplate* findPlayerTemplate(NameKeyType namekey) const; - Int getPlayerTemplateCount() const { return m_playerTemplates.size(); } - Int getTemplateNumByName(AsciiString name) const; - - // This function will fill outStringList with all the sides found in all the templates - void getAllSideStrings(AsciiStringList *outStringList); - -private: - - typedef std::vector PlayerTemplateVector; - - PlayerTemplateVector m_playerTemplates; -}; - -// ---------------------------------------------------------------------------------------------- -extern PlayerTemplateStore *ThePlayerTemplateStore; ///< singleton instance of PlayerTemplateStore diff --git a/Generals/Code/GameEngine/Include/Common/ProductionPrerequisite.h b/Generals/Code/GameEngine/Include/Common/ProductionPrerequisite.h deleted file mode 100644 index 62c5b0eb3f2..00000000000 --- a/Generals/Code/GameEngine/Include/Common/ProductionPrerequisite.h +++ /dev/null @@ -1,120 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: ProductionPrerequisite.h ////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: RTS3 -// -// File name: ProductionPrerequisite.h -// -// Created: Steven Johnson, October 2001 -// -//----------------------------------------------------------------------------- - -#pragma once - -//----------------------------------------------------------------------------- -// Includes -//----------------------------------------------------------------------------- -#include "Common/GameMemory.h" -#include "Common/GameCommon.h" -#include "Common/Science.h" -//#include "GameClient/ControlBar.h" - -//----------------------------------------------------------------------------- -class ThingTemplate; -class Player; - -//----------------------------------------------------------------------------- -class ProductionPrerequisite -{ -public: - - ProductionPrerequisite(); - ~ProductionPrerequisite(); - - /// init to safe default values. - void init(); - - void resetSciences() { m_prereqSciences.clear(); } - void addSciencePrereq( ScienceType science ) { m_prereqSciences.push_back(science); } - - void resetUnits() { m_prereqUnits.clear(); } - void addUnitPrereq( AsciiString units, Bool orUnitWithPrevious ); - void addUnitPrereq( const std::vector& units ); - - /// called after all ThingTemplates have been loaded. - void resolveNames(); - - /// returns an asciistring which is a list of all the prerequisites - /// not satisfied yet - UnicodeString getRequiresList(const Player *player) const; - - /// return true iff the player satisfies our set of prerequisites - Bool isSatisfied(const Player *player) const; - - /** - return the BuildFacilityTemplate, if any. - - if this template needs no build facility, null is returned. - - if the template needs a build facility but the given player doesn't have any in existence, - null will be returned. - - you may not pass 'null' for player. - */ - const ThingTemplate *getExistingBuildFacilityTemplate( const Player *player ) const; - - Int getAllPossibleBuildFacilityTemplates(const ThingTemplate* tmpls[], Int maxtmpls) const; - -private: - - enum - { - UNIT_OR_WITH_PREV = 0x01 // if set, unit is "or-ed" with prev unit, so that either one's presence satisfies - }; - - struct PrereqUnitRec - { - const ThingTemplate* unit; - Int flags; - AsciiString name; - }; - - enum { MAX_PREREQ = 32 }; - Int calcNumPrereqUnitsOwned(const Player *player, Int counts[MAX_PREREQ]) const; - - std::vector m_prereqUnits; - ScienceVec m_prereqSciences; -}; - -//----------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngine/Include/Common/ResourceGatheringManager.h b/Generals/Code/GameEngine/Include/Common/ResourceGatheringManager.h deleted file mode 100644 index 5fb0aeba684..00000000000 --- a/Generals/Code/GameEngine/Include/Common/ResourceGatheringManager.h +++ /dev/null @@ -1,71 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: ResourceGatheringManager.h /////////////////////////////////////////////////////////// -// The part of a Player's brain that keeps track of all Resource type Objects and makes -// gathering type decisions based on them. -// Author: Graham Smallwood, January, 2002 -/////////////////////////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#include "Common/GameType.h" -#include "Common/Snapshot.h" - -class Object; - -// ------------------------------------------------------------------------------------------------ -class ResourceGatheringManager : public MemoryPoolObject, - public Snapshot -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( ResourceGatheringManager, "ResourceGatheringManager" ); - -public: - ResourceGatheringManager(); - - Object *findBestSupplyWarehouse( Object *queryObject ); ///< What Warehouse should this truck go to? - Object *findBestSupplyCenter( Object *queryObject ); ///< What Center should this truck return to? - - void addSupplyCenter( Object *newCenter ); ///< I captured or built a Supply Center, so record it - void removeSupplyCenter( Object *oldCenter ); ///< Lost a supply center - - void addSupplyWarehouse( Object *newWarehouse ); ///< Warehouse created, or this is start of game recording - void removeSupplyWarehouse( Object *oldWarehouse ); ///< Warehouse that doesn't replenish has run out of Supply - -protected: - - // snapshot methods - virtual void crc( Xfer *xfer ) override; - virtual void xfer( Xfer *xfer ) override; - virtual void loadPostProcess() override; - -private: - /// @todo Make sure the allocator for std::list<> is a good one. Otherwise override it. - typedef std::list objectIDList; - typedef std::list::iterator objectIDListIterator; - - objectIDList m_supplyWarehouses; - objectIDList m_supplyCenters; - -}; diff --git a/Generals/Code/GameEngine/Include/Common/Science.h b/Generals/Code/GameEngine/Include/Common/Science.h deleted file mode 100644 index ac1f6014f97..00000000000 --- a/Generals/Code/GameEngine/Include/Common/Science.h +++ /dev/null @@ -1,133 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: Science.h //////////////////////////////////////////////////////////////////////////////// -// Author: Steven Johnson, Colin Day November 2001 -// Desc: Science descriptions -/////////////////////////////////////////////////////////////////////////////////////////////////// - -#pragma once - -// INCLUDES /////////////////////////////////////////////////////////////////////////////////////// -#include "Common/Overridable.h" -#include "Common/NameKeyGenerator.h" -#include "Common/UnicodeString.h" - -class Player; - -//------------------------------------------------------------------------------------------------- -enum ScienceType CPP_11(: Int) -{ - SCIENCE_INVALID = -1 -}; - -//------------------------------------------------------------------------------------------------- -typedef std::vector ScienceVec; - -//------------------------------------------------------------------------------------------------- -class ScienceInfo : public Overridable -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( ScienceInfo, "ScienceInfo" ) - - friend class ScienceStore; - -private: - ScienceType m_science; - UnicodeString m_name; - UnicodeString m_description; - ScienceVec m_rootSciences; // this is calced at runtime, NOT read from INI - ScienceVec m_prereqSciences; - Int m_sciencePurchasePointCost; - Bool m_grantable; - - ScienceInfo() : - m_science(SCIENCE_INVALID), - m_sciencePurchasePointCost(0), // 0 means "cannot be purchased" - m_grantable(true) - { - } - - void addRootSciences(ScienceVec& v) const; -}; -EMPTY_DTOR(ScienceInfo); - -//------------------------------------------------------------------------------------------------- -class ScienceStore : public SubsystemInterface -{ - friend class ScienceInfo; - -public: - virtual ~ScienceStore() override; - - virtual void init() override; - virtual void reset() override; - virtual void update() override { } - - Bool isValidScience(ScienceType st) const; - - Bool isScienceGrantable(ScienceType st) const; - - Bool getNameAndDescription(ScienceType st, UnicodeString& name, UnicodeString& description) const; - - Bool playerHasPrereqsForScience(const Player* player, ScienceType st) const; - - /** - this is a subtle call, and should ALMOST NEVER be called by external code... - this is used to determine if you have the "root" requirements for a given science, - and thus could *potentially* obtain it if you got extra prereqs. - - Generally, you should call getPurchasableSciences() instead of this! - */ - Bool playerHasRootPrereqsForScience(const Player* player, ScienceType st) const; - - Int getSciencePurchaseCost(ScienceType science) const; - - ScienceType getScienceFromInternalName(const AsciiString& name) const; - AsciiString getInternalNameForScience(ScienceType science) const; - - /** return a list of the sciences the given player can purchase now, and a list he might be able to purchase in the future, - but currently lacks prereqs or points for. (either might be an empty list) */ - void getPurchasableSciences(const Player* player, ScienceVec& purchasable, ScienceVec& potentiallyPurchasable) const; - - // this is intended ONLY for use by INI::scanScience. - // Don't use it anywhere else. In particular, never, ever, ever - // call this with a hardcoded science name. (srj) - ScienceType friend_lookupScience(const char* scienceName) const; - static void friend_parseScienceDefinition(INI* ini); - - // return a vector of all the currently-known science names - // NOTE: this is really only for use by WorldBuilder! Please - // do not use it in RTS! - std::vector friend_getScienceNames() const; - - -private: - - const ScienceInfo* findScienceInfo(ScienceType st) const; - - typedef std::vector ScienceInfoVec; - ScienceInfoVec m_sciences; -}; - -extern ScienceStore* TheScienceStore; diff --git a/Generals/Code/GameEngine/Include/Common/ScoreKeeper.h b/Generals/Code/GameEngine/Include/Common/ScoreKeeper.h deleted file mode 100644 index 3f01a0f511c..00000000000 --- a/Generals/Code/GameEngine/Include/Common/ScoreKeeper.h +++ /dev/null @@ -1,140 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: ScoreKeeper.h ///////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Electronic Arts Pacific. -// -// Confidential Information -// Copyright (C) 2002 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// created: Jun 2002 -// -// Filename: ScoreKeeper.h -// -// author: Chris Huybregts -// -// purpose: Header file for the scorekeeper class -// -//----------------------------------------------------------------------------- -/////////////////////////////////////////////////////////////////////////////// - -#pragma once - -//----------------------------------------------------------------------------- -// SYSTEM INCLUDES //////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- - -//----------------------------------------------------------------------------- -// USER INCLUDES ////////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -#include "Common/Snapshot.h" - -//----------------------------------------------------------------------------- -// FORWARD REFERENCES ///////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -class Object; -class ThingTemplate; -//----------------------------------------------------------------------------- -// TYPE DEFINES /////////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -class ScoreKeeper : public Snapshot -{ -public: - ScoreKeeper(); - ~ScoreKeeper(); - - void reset( Int playerIdx ); ///< Zero out the variables - Int calculateScore(); ///< Performs the equation to calculate the score - - void addMoneySpent( Int money ); ///< Adds money to the amount spent - void addMoneyEarned( Int money ); ///< Adds money to the earned amount - - void addObjectBuilt( const Object *o ); - void addObjectDestroyed( const Object *o ); - void addObjectLost( const Object *o ); - void addObjectCaptured( const Object *o ); - - void removeObjectBuilt( const Object *o ); - - Int getTotalMoneyEarned() { return m_totalMoneyEarned; } - Int getTotalMoneySpent() { return m_totalMoneySpent; } - Int getTotalUnitsDestroyed(); - Int getTotalUnitsBuilt() { return m_totalUnitsBuilt; } - Int getTotalUnitsLost() { return m_totalUnitsLost; } - Int getTotalBuildingsDestroyed(); - Int getTotalBuildingsBuilt() { return m_totalBuildingsBuilt; } - Int getTotalBuildingsLost() { return m_totalBuildingsLost; } - Int getTotalTechBuildingsCaptured() { return m_totalTechBuildingsCaptured; } - Int getTotalFactionBuildingsCaptured() { return m_totalFactionBuildingsCaptured; } - Int getTotalObjectsBuilt( const ThingTemplate *pTemplate ); // get a count of objects built matching a specific thing template - - // for battle honor calculation. done once at the end of each online game - Int getTotalUnitsBuilt( KindOfMaskType validMask, KindOfMaskType invalidMask ); - -protected: - - // snapshot methods - virtual void crc( Xfer *xfer ) override; - virtual void xfer( Xfer *xfer ) override; - virtual void loadPostProcess() override; - -private: - - Int m_totalMoneyEarned; ///< The total money that was harvested, refined, received in crates - Int m_totalMoneySpent; ///< The total money spent on units, buildings, repairs - Int m_totalUnitsDestroyed[MAX_PLAYER_COUNT]; ///< The total number of enemies that we've killed - Int m_totalUnitsBuilt; ///< The total number of units we've created (created meaning that we built from a building) - Int m_totalUnitsLost; ///< The total number of our units lost - Int m_totalBuildingsDestroyed[MAX_PLAYER_COUNT]; ///< The total number of Buildings we've destroyed - Int m_totalBuildingsBuilt; ///< The total number of buildings we've constructed - Int m_totalBuildingsLost; ///< The total number of our buildings lost - Int m_totalTechBuildingsCaptured; ///< The total number of tech buildings captured - Int m_totalFactionBuildingsCaptured; ///< The total number of faction buildings captured - Int m_currentScore; ///< Based off the stats, this is the current score - - Int m_myPlayerIdx; ///< We need to not score kills on ourselves... so we need to know who we are - - typedef std::map ObjectCountMap; - typedef ObjectCountMap::iterator ObjectCountMapIt; - ObjectCountMap m_objectsBuilt; ///< How many and what kinds of objects did we build - ObjectCountMap m_objectsDestroyed[MAX_PLAYER_COUNT]; ///< How many and what kinds and who's did we kill - ObjectCountMap m_objectsLost; ///< how many and what kinds of objects did we loose - ObjectCountMap m_objectsCaptured; - void xferObjectCountMap( Xfer *xfer, ObjectCountMap *map ); - -}; - -//----------------------------------------------------------------------------- -// INLINING /////////////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -inline void ScoreKeeper::addMoneySpent( Int money ) { m_totalMoneySpent += money; } -inline void ScoreKeeper::addMoneyEarned( Int money ) { m_totalMoneyEarned += money; } - -//----------------------------------------------------------------------------- -// EXTERNALS ////////////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- diff --git a/Generals/Code/GameEngine/Include/Common/SpecialPower.h b/Generals/Code/GameEngine/Include/Common/SpecialPower.h deleted file mode 100644 index b7bc7a77152..00000000000 --- a/Generals/Code/GameEngine/Include/Common/SpecialPower.h +++ /dev/null @@ -1,189 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: SpecialPower.h /////////////////////////////////////////////////////////////////////////// -// Author: Colin Day, April 2002 -// Desc: Special power templates and the system that holds them -// Edited: Kris Morness -- July 2002 (added BitFlag system) -/////////////////////////////////////////////////////////////////////////////////////////////////// - -#pragma once - -// USER INCLUDES ////////////////////////////////////////////////////////////////////////////////// -#include "Common/AudioEventRTS.h" -#include "Common/GameMemory.h" -#include "Common/SubsystemInterface.h" -#include "Common/BitFlags.h" -#include "Common/Overridable.h" -#include "Common/Override.h" - -// FORWARD REFERENCES ///////////////////////////////////////////////////////////////////////////// -class ObjectCreationList; -class Object; -enum ScienceType CPP_11(: Int); -struct FieldParse; -enum AcademyClassificationType CPP_11(: Int); - -// For SpecialPowerType and SpecialPowerMaskType::s_bitNameList. Part of detangling. -#include "Common/SpecialPowerType.h" - -// For SpecialPowerMaskType. Part of detangling. -#include "Common/SpecialPowerMaskType.h" - -#define MAKE_SPECIALPOWER_MASK(k) SpecialPowerMaskType(SpecialPowerMaskType::kInit, (k)) - -inline Bool TEST_SPECIALPOWERMASK(const SpecialPowerMaskType& m, SpecialPowerType t) -{ - return m.test(t); -} -inline Bool TEST_SPECIALPOWERMASK_ANY(const SpecialPowerMaskType& m, const SpecialPowerMaskType& mask) -{ - return m.anyIntersectionWith(mask); -} -inline Bool TEST_SPECIALPOWERMASK_MULTI(const SpecialPowerMaskType& m, const SpecialPowerMaskType& mustBeSet, const SpecialPowerMaskType& mustBeClear) -{ - return m.testSetAndClear(mustBeSet, mustBeClear); -} -inline Bool SPECIALPOWERMASK_ANY_SET(const SpecialPowerMaskType& m) -{ - return m.any(); -} -inline void CLEAR_SPECIALPOWERMASK(SpecialPowerMaskType& m) -{ - m.clear(); -} -inline void SET_SPECIALPOWERMASK( SpecialPowerMaskType& m, SpecialPowerType t, Int val = 1 ) -{ - m.set( t, val ); -} -inline void SET_ALL_SPECIALPOWERMASK_BITS(SpecialPowerMaskType& m) -{ - m.clear(); - m.flip(); -} -inline void FLIP_SPECIALPOWERMASK(SpecialPowerMaskType& m) -{ - m.flip(); -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -class SpecialPowerTemplate : public Overridable -{ - - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( SpecialPowerTemplate, "SpecialPowerTemplate" ) - -public: - - SpecialPowerTemplate(); - // virtual destructor prototype provided by MemoryPoolObject - - static const FieldParse* getFieldParse() { return m_specialPowerFieldParse; } - - void friend_setNameAndID(const AsciiString& name, UnsignedInt id) - { - m_name = name; - m_id = id; - } - - AsciiString getName() const { return getFO()->m_name; } - UnsignedInt getID() const { return getFO()->m_id; } - SpecialPowerType getSpecialPowerType() const { return getFO()->m_type; } - UnsignedInt getReloadTime() const { return getFO()->m_reloadTime; } - ScienceType getRequiredScience() const { return getFO()->m_requiredScience; } - const AudioEventRTS *getInitiateSound() const { return &getFO()->m_initiateSound; } - const AudioEventRTS *getInitiateAtTargetSound() const { return &getFO()->m_initiateAtLocationSound; } - Bool hasPublicTimer() const { return getFO()->m_publicTimer; } - Bool isSharedNSync() const { return getFO()->m_sharedNSync; } - UnsignedInt getDetectionTime() const { return getFO()->m_detectionTime; } - UnsignedInt getViewObjectDuration() const { return getFO()->m_viewObjectDuration; } - Real getViewObjectRange() const { return getFO()->m_viewObjectRange; } - Real getRadiusCursorRadius() const { return getFO()->m_radiusCursorRadius; } - Bool isShortcutPower() const { return getFO()->m_shortcutPower; } - AcademyClassificationType getAcademyClassificationType() const { return m_academyClassificationType; } - -private: - - const SpecialPowerTemplate* getFO() const { return (const SpecialPowerTemplate*)friend_getFinalOverride(); } - - AsciiString m_name; ///< name - UnsignedInt m_id; ///< unique identifier - SpecialPowerType m_type; ///< enum allowing for fast type checking for ability processing. - UnsignedInt m_reloadTime; ///< (frames) after using special power, how long it takes to use again - ScienceType m_requiredScience; ///< science required (if any) to actually execute this power - AudioEventRTS m_initiateSound; ///< sound to play when initiated - AudioEventRTS m_initiateAtLocationSound; ///< sound to play at target location (if any) - AcademyClassificationType m_academyClassificationType; ///< A value used by the academy to evaluate advice based on what players do. - UnsignedInt m_detectionTime; ///< (frames) after using infiltration power (defection, etc.), - ///< how long it takes for ex comrades to realize it on their own - UnsignedInt m_viewObjectDuration; ///< Lifetime of a looking object we slap down so you can watch the effect - Real m_viewObjectRange; ///< And how far that object can see. - Real m_radiusCursorRadius; ///< size of radius cursor, if any - Bool m_publicTimer; ///< display a countdown timer for this special power for all to see - Bool m_sharedNSync; ///< If true, this is a special that is shared between all of a player's command centers - Bool m_shortcutPower; ///< Is this shortcut power capable of being fired by the side panel? - - static const FieldParse m_specialPowerFieldParse[]; ///< the parse table - -}; - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -class SpecialPowerStore : public SubsystemInterface -{ - -public: - - SpecialPowerStore(); - virtual ~SpecialPowerStore() override; - - virtual void init() override { }; - virtual void update() override { }; - virtual void reset() override; - - const SpecialPowerTemplate *findSpecialPowerTemplate( AsciiString name ) { return findSpecialPowerTemplatePrivate(name); } - const SpecialPowerTemplate *findSpecialPowerTemplateByID( UnsignedInt id ); - const SpecialPowerTemplate *getSpecialPowerTemplateByIndex( UnsignedInt index ); // for WorldBuilder - - /// does the object (and therefore the player) meet all the requirements to use this power - Bool canUseSpecialPower( Object *obj, const SpecialPowerTemplate *specialPowerTemplate ); - - Int getNumSpecialPowers(); // for WorldBuilder - - static void parseSpecialPowerDefinition( INI *ini ); - -private: - -protected: - SpecialPowerTemplate *findSpecialPowerTemplatePrivate( AsciiString name ); - - typedef std::vector SpecialPowerTemplatePtrVector; - SpecialPowerTemplatePtrVector m_specialPowerTemplates; ///< the special power templates - - UnsignedInt m_nextSpecialPowerID; - -}; - -// EXTERNAL /////////////////////////////////////////////////////////////////////////////////////// -extern SpecialPowerStore *TheSpecialPowerStore; diff --git a/Generals/Code/GameEngine/Include/Common/SpecialPowerMaskType.h b/Generals/Code/GameEngine/Include/Common/SpecialPowerMaskType.h deleted file mode 100644 index 1afe14a5647..00000000000 --- a/Generals/Code/GameEngine/Include/Common/SpecialPowerMaskType.h +++ /dev/null @@ -1,35 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// SpecialPowerMaskType.h ///////////////////////////////////////////////////////////////////////// -// Part of header detangling -// JKMCD Aug 2002 - -#pragma once - -#include "Common/BitFlags.h" -#include "Common/BitFlagsIO.h" -#include "Common/SpecialPowerType.h" - -typedef BitFlags SpecialPowerMaskType; diff --git a/Generals/Code/GameEngine/Include/Common/SpecialPowerType.h b/Generals/Code/GameEngine/Include/Common/SpecialPowerType.h deleted file mode 100644 index d7a7e4edde5..00000000000 --- a/Generals/Code/GameEngine/Include/Common/SpecialPowerType.h +++ /dev/null @@ -1,135 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// SpecialPowerType.h ///////////////////////////////////////////////////////////////////////////// -// Part of header detangling -// JKMCD Aug 2002 - -#pragma once - -// ------------------------------------------------------------------------------------------------ -// don't forget to add new strings to SpecialPowerMaskType::s_bitNameList[] -// ------------------------------------------------------------------------------------------------ -// -// Note: these values are saved in save files, so you MUST NOT REMOVE OR CHANGE -// existing values! -// -enum SpecialPowerType CPP_11(: Int) -{ - SPECIAL_INVALID, - // don't forget to add new strings to SpecialPowerMaskType::s_bitNameList[] - - //Superweapons - SPECIAL_DAISY_CUTTER, - SPECIAL_PARADROP_AMERICA, - SPECIAL_CARPET_BOMB, - SPECIAL_CLUSTER_MINES, - SPECIAL_EMP_PULSE, - SPECIAL_NAPALM_STRIKE, - SPECIAL_CASH_HACK, - SPECIAL_NEUTRON_MISSILE, - SPECIAL_SPY_SATELLITE, - SPECIAL_DEFECTOR, - SPECIAL_TERROR_CELL, - SPECIAL_AMBUSH, - SPECIAL_BLACK_MARKET_NUKE, - SPECIAL_ANTHRAX_BOMB, - SPECIAL_SCUD_STORM, -#ifdef ALLOW_DEMORALIZE - SPECIAL_DEMORALIZE, -#else - SPECIAL_DEMORALIZE_OBSOLETE, -#endif - SPECIAL_CRATE_DROP, - SPECIAL_A10_THUNDERBOLT_STRIKE, - SPECIAL_DETONATE_DIRTY_NUKE, - SPECIAL_ARTILLERY_BARRAGE, - // don't forget to add new strings to SpecialPowerMaskType::s_bitNameList[] - - //Special abilities - SPECIAL_MISSILE_DEFENDER_LASER_GUIDED_MISSILES, - SPECIAL_REMOTE_CHARGES, - SPECIAL_TIMED_CHARGES, - SPECIAL_HELIX_NAPALM_BOMB, // Added in Zero Hour - SPECIAL_HACKER_DISABLE_BUILDING, - SPECIAL_TANKHUNTER_TNT_ATTACK, - SPECIAL_BLACKLOTUS_CAPTURE_BUILDING, - SPECIAL_BLACKLOTUS_DISABLE_VEHICLE_HACK, - SPECIAL_BLACKLOTUS_STEAL_CASH_HACK, - SPECIAL_INFANTRY_CAPTURE_BUILDING, - SPECIAL_RADAR_VAN_SCAN, - SPECIAL_SPY_DRONE, - SPECIAL_DISGUISE_AS_VEHICLE, - SPECIAL_BOOBY_TRAP, // Added in Zero Hour - // don't forget to add new strings to SpecialPowerMaskType::s_bitNameList[] - SPECIAL_REPAIR_VEHICLES, - SPECIAL_PARTICLE_UPLINK_CANNON, - SPECIAL_CASH_BOUNTY, - SPECIAL_CHANGE_BATTLE_PLANS, - SPECIAL_CIA_INTELLIGENCE, - SPECIAL_CLEANUP_AREA, - // don't forget to add new strings to SpecialPowerMaskType::s_bitNameList[] - SPECIAL_LAUNCH_BAIKONUR_ROCKET, - - // TheSuperHackers @info Added in Zero Hour: - SPECIAL_SPECTRE_GUNSHIP, - SPECIAL_GPS_SCRAMBLER, - - SPECIAL_FRENZY, - SPECIAL_SNEAK_ATTACK, - - //Ack, this is ass. These enums fix a bug where new enums were missing for - //shortcut powers... but the real clincher was that if you were say USA and - //captured a Tank China command center, your US paradrop would be assigned - //to the china tank drop and when you tried to fire it from the shortcut - //it could pick the china one and not fire it because it didn't have - //complete connection... ugh!!! - SPECIAL_CHINA_CARPET_BOMB, - EARLY_SPECIAL_CHINA_CARPET_BOMB, - SPECIAL_LEAFLET_DROP, - EARLY_SPECIAL_LEAFLET_DROP, - EARLY_SPECIAL_FRENZY, - SPECIAL_COMMUNICATIONS_DOWNLOAD, - EARLY_SPECIAL_REPAIR_VEHICLES, - SPECIAL_TANK_PARADROP, - SUPW_SPECIAL_PARTICLE_UPLINK_CANNON, - AIRF_SPECIAL_DAISY_CUTTER, - NUKE_SPECIAL_CLUSTER_MINES, - NUKE_SPECIAL_NEUTRON_MISSILE, - AIRF_SPECIAL_A10_THUNDERBOLT_STRIKE, - AIRF_SPECIAL_SPECTRE_GUNSHIP, - INFA_SPECIAL_PARADROP_AMERICA, - SLTH_SPECIAL_GPS_SCRAMBLER, - AIRF_SPECIAL_CARPET_BOMB, - SUPR_SPECIAL_CRUISE_MISSILE, - LAZR_SPECIAL_PARTICLE_UPLINK_CANNON, - SUPW_SPECIAL_NEUTRON_MISSILE, - - SPECIAL_BATTLESHIP_BOMBARDMENT, - - SPECIALPOWER_COUNT, - // don't forget to add new strings to SpecialPowerMaskType::s_bitNameList[] -}; - - // Definition of these names is located in SpecialPower.cpp diff --git a/Generals/Code/GameEngine/Include/Common/Team.h b/Generals/Code/GameEngine/Include/Common/Team.h deleted file mode 100644 index 58d7ed50e5e..00000000000 --- a/Generals/Code/GameEngine/Include/Common/Team.h +++ /dev/null @@ -1,755 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: Team.h /////////////////////////////////////////////////////////////// -// Team interface definition -// Author: Michael S. Booth, Steven Johnson, March 2001 - -#pragma once - -#include "Common/GameType.h" -#include "Common/Snapshot.h" -#include "Common/Thing.h" -#include "GameLogic/Object.h" - -// ------------------------------------------------------------------------------------------------ -typedef UnsignedInt TeamID; -#define TEAM_ID_INVALID 0 - -// ------------------------------------------------------------------------------------------------ -typedef UnsignedInt TeamPrototypeID; -#define TEAM_PROTOTYPE_ID_INVALID 0 - -// ------------------------------------------------------------------------------------------------ -typedef std::hash_map< TeamID, Relationship, std::hash, std::equal_to/**/> TeamRelationMapType; -class TeamRelationMap : public MemoryPoolObject, - public Snapshot -{ - - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( TeamRelationMap, "TeamRelationMapPool" ) - -public: - - TeamRelationMap(); - // virtual destructor provided by memory pool object - - /** @todo I'm just wrapping this up in a nice snapshot object, we really should isolate - * m_map from public access and make access methods for our operations */ - TeamRelationMapType m_map; - -protected: - - virtual void crc( Xfer *xfer ) override; - virtual void xfer( Xfer *xfer ) override; - virtual void loadPostProcess() override; - -}; - -// ------------------------------------------------------------------------------------------------ -typedef void (*ObjectIterateFunc)( Object *obj, void *userData ); ///< callback type for iterating objects - -// ------------------------------------------------------------------------ -/** - How are teams represented in mapfiles? - - -- All Players always have at least one top-level team, with the name "team" - (WB will enforce this in mapfiles.) - -- We'll have a TeamDict list that is parallel to the PlayerDict list - -- All Teams (toplevel and subteams) are in the list - -- Each TeamDict contains: - -- Team Name (an internal ascii str) - -- Owning Team (or Player), by Name - -- Misc Flags - -- Teams we are allies with, by name (only for toplevel teams) - -- Teams we are enemies with, by name (only for toplevel teams) - - -- Note that Players and Teams share the same namespace, so you cannot have a team - with the same name as a player (or vice versa). - - -- MapObject Dicts will be revised to have an "owning team" rather than "owning player" entry - - -- BuildLists must also have a way to assign units to Teams, as appropriate - -*/ - -// ------------------------------------------------------------------------ -class AIGroup; -class Dict; -class Player; -class PolygonTrigger; -class Script; -class SidesList; -class TeamFactory; -class TeamPrototype; -class Team; -class ThingTemplate; -class Waypoint; -class PlayerRelationMap; - -enum AttitudeType CPP_11(: Int); - -typedef struct { - Int minUnits; - Int maxUnits; - AsciiString unitThingName; -} TCreateUnitsInfo; - -enum { MAX_GENERIC_SCRIPTS = 16 }; - -// ------------------------------------------------------------------------ -/// This is the info for creating reinforcement and AI teams. -class TeamTemplateInfo : public Snapshot -{ - -public: - - TeamTemplateInfo(Dict *d); - - enum {MAX_UNIT_TYPES = 7}; - typedef enum {NORMAL=0, IGNORE_DISTRACTIONS=1, DEAL_AGGRESSIVELY=2} TBehavior; - - TCreateUnitsInfo m_unitsInfo[MAX_UNIT_TYPES]; ///< Quantity of units to create or build. - Int m_numUnitsInfo; ///< Number of entries in m_unitsInfo - Coord3D m_homeLocation; ///< Spawn location for team. - Bool m_hasHomeLocation; ///< True is m_homeLocation is valid. - AsciiString m_scriptOnCreate; ///< Script executed when team is created. - AsciiString m_scriptOnIdle; ///< Script executed when team is idle. - Int m_initialIdleFrames; ///< Number of frames to continue recruiting after the minimum team size is achieved. - AsciiString m_scriptOnEnemySighted; ///< Script executed when enemy is sighted. - AsciiString m_scriptOnAllClear; ///< Script executed when enemy is sighted. - AsciiString m_scriptOnUnitDestroyed; ///< Script executed each time a unit on this team dies. - AsciiString m_scriptOnDestroyed; ///< Script executed m_destroyedThreshold of member units are destroyed. - Real m_destroyedThreshold; ///< OnDestroyed threshold - 1.0 = 100% = all destroyed, .5 = 50% = half of the units destroyed, 0 = useless. - Bool m_isAIRecruitable; ///< True if other ai teams can recruit. - Bool m_isBaseDefense; ///< True if is base defense team. - Bool m_isPerimeterDefense; ///< True if is a perimeter base defense team. - Bool m_automaticallyReinforce; ///< True is team automatically tries to reinforce. - Bool m_transportsReturn; ///< True if transports return to base after unloading. - Bool m_avoidThreats; ///< True if the team avoids threats. - Bool m_attackCommonTarget; ///< True if the team attacks the same target unit. - Int m_maxInstances; ///< Maximum number of instances of a team that is not singleton. - mutable Int m_productionPriority; ///< Production priority. - Int m_productionPrioritySuccessIncrease; ///< Production priority increase on success. - Int m_productionPriorityFailureDecrease; ///< Production priority decrease on failure. - AttitudeType m_initialTeamAttitude; ///< The initial team attitude - - AsciiString m_transportUnitType; ///< Unit used to transport the team. - AsciiString m_startReinforceWaypoint; ///< Waypoint where the reinforcement team starts. - Bool m_teamStartsFull; ///< If true, team loads into member transports. - Bool m_transportsExit; ///< True if the transports leave after deploying team. - VeterancyLevel m_veterancy; ///< Veterancy level; - - // Production scripts stuff - AsciiString m_productionCondition; ///< Script that contains the production conditions. - Bool m_executeActions; ///< If this is true, then when the production condition becomes true, we also execute the actions. - - AsciiString m_teamGenericScripts[MAX_GENERIC_SCRIPTS]; -protected: - - // snapshot methods - virtual void crc( Xfer *xfer ) override; - virtual void xfer( Xfer *xfer ) override; - virtual void loadPostProcess() override; - -}; - -// ------------------------------------------------------------------------ -class Team : public MemoryPoolObject, - public Snapshot -{ - - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(Team, "TeamPool" ) - -private: - - TeamPrototype *m_proto; ///< the prototype used to create this Team - TeamID m_id; ///< unique team id - - // lists we own - /// @todo srj -- convert to non-DLINK list, after it is once again possible to test the change - MAKE_DLINK_HEAD(Object, TeamMemberList) ///< the members of this team - - // lists we are members of - /// @todo srj -- convert to non-DLINK list, after it is once again possible to test the change - MAKE_DLINK(Team, TeamInstanceList) ///< the instances of our prototype - - AsciiString m_state; ///< Name of the current AI state. - - Bool m_enteredOrExited; ///< True if a team member entered or exited a trigger area this frame. - Bool m_active; ///< True if a team is complete. False while members are being added. - Bool m_created; ///< True when first activated. - - // Enemy sighted & All Clear: - Bool m_checkEnemySighted;///< True if we have an on enemy sighted or all clear script. - Bool m_seeEnemy; ///< True if we see an enemy. - Bool m_prevSeeEnemy; ///< Last value. - - // Idle flag. - Bool m_wasIdle; ///< True if idle last frame. - - // On %Destroyed - Int m_destroyThreshold; - Int m_curUnits; - - // Following waypoint paths as a team. - const Waypoint *m_currentWaypoint; - - // Should check/Execute generic script - Bool m_shouldAttemptGenericScript[MAX_GENERIC_SCRIPTS]; - - // Recruitablity. - Bool m_isRecruitablitySet; ///< If false, recruitability is team proto value. If true, m_isRecruitable. - Bool m_isRecruitable; - - // Attack target. - ObjectID m_commonAttackTarget; - - TeamRelationMap *m_teamRelations; ///< override allies & enemies - PlayerRelationMap *m_playerRelations; ///< override allies & enemies - - std::list< ObjectID > m_xferMemberIDList; ///< list for post processing and restoring object pointers after a load - -protected: - - // snapshot methods - virtual void crc( Xfer *xfer ) override; - virtual void xfer( Xfer *xfer ) override; - virtual void loadPostProcess() override; - -public: - - Team( TeamPrototype *proto, TeamID id ); - // ~Team(); - - /// return the prototype used to create this team - const TeamPrototype *getPrototype() { return m_proto; } - - void setID( TeamID id ) { m_id = id; } - TeamID getID() const { return m_id; } - - /** - Set the attack priority name for a team. - */ - void setAttackPriorityName(AsciiString name); - - /** - return the player currently controlling this team (backtracking up if necessary) - */ - Player *getControllingPlayer() const; - - /** - set the team's owner. (nullptr is not allowed) - */ - void setControllingPlayer(Player *newController); - - /** - Get the team's state - */ - const AsciiString& getState() const {return m_state;} - - /** - fill pAIGroup (which must be NONNULL) with the members of this team as a Group. - */ - void getTeamAsAIGroup(AIGroup *pAIGroup); - - /** - Get the team's state - */ - inline const AsciiString& getName() const; - - /** - Get the count of live things that are either alive or are buildings. - */ - Int getTargetableCount() const; - - /** - Set the team's AI state. - */ - void setState(const AsciiString& state) {m_state = state;} - - /** - Set the team's AI recruitablity. - */ - void setRecruitable(Bool recruitable) {m_isRecruitablitySet = true; m_isRecruitable = recruitable;} - - /** - Set the team's target object. - */ - void setTeamTargetObject(const Object *target) ; - - /** - Set the team's target object. - */ - Object *getTeamTargetObject(); - - /** - Set the team as active. A team is considered created when set active. - */ - void setActive() {if (!m_active) { m_created = true;m_active = true;}} - - /** - Is this team active? - */ - Bool isActive() {return m_active;} - - /** - Is this team just createc? (stays true one logic frame.) - */ - Bool isCreated() {return m_created;} - - /** - Note that a team member entered or exited a trigger area. - */ - void setEnteredExited() {m_enteredOrExited = true;} - - /** - Did a team member enter or exit a trigger area. - */ - Bool didEnterOrExit() {return m_enteredOrExited;} - - /** - Clear the flag that a team member entered or exited a trigger area. - Also checks and executes any onCreate scripts, and clears the created flag. - */ - void updateState(); - - void notifyTeamOfObjectDeath(); - - Bool didAllEnter(PolygonTrigger *pTrigger, UnsignedInt whichToConsider) const; ///< All members entered the area - Bool didPartialEnter(PolygonTrigger *pTrigger, UnsignedInt whichToConsider) const; ///< One member entered the area - Bool didAllExit(PolygonTrigger *pTrigger, UnsignedInt whichToConsider) const; ///< All members exited the area - Bool didPartialExit(PolygonTrigger *pTrigger, UnsignedInt whichToConsider) const; ///< One member exited the area - Bool allInside(PolygonTrigger *pTrigger, UnsignedInt whichToConsider) const; ///< All members are inside the area - Bool someInsideSomeOutside(PolygonTrigger *pTrigger, UnsignedInt whichToConsider) const;///< One or more in, one or more out. - Bool noneInside(PolygonTrigger *pTrigger, UnsignedInt whichToConsider) const; ///< No members are in the area. - - Object * tryToRecruit(const ThingTemplate *, const Coord3D *teamHome, Real maxDist); ///< Try to recruit the closest unit of this thing type. Return true if successful. - - /** - return our relationship with the other team. - this is done as follows: - - -- if there's a TeamRelationship between this team and that team, return it. - -- otherwise, we use the relationship between our players. - - */ - Relationship getRelationship(const Team *that) const; - - /** - set a special relationship between this team and that team, that overrides - the one between our Players. (note that this doesn't imply anything about the - relation of that to this.) - */ - void setOverrideTeamRelationship( TeamID teamID, Relationship r ); - - /** - remove the special relation (if any) between this and that. - remove all special relations for 'this' if that==null. - return true if anything removed. - */ - Bool removeOverrideTeamRelationship( TeamID teamID ); - - /** - set a special relationship between this team and that Player, that overrides - the one between our Players. (note that this doesn't imply anything about the - relation of that to this.) Note that override-team relationships take precedence - over override-player relationships. - */ - void setOverridePlayerRelationship( Int playerIndex, Relationship r ); - - /** - remove the special relation (if any) between this and that. - remove all special relations for 'this' if that==null. - return true if anything removed. - */ - Bool removeOverridePlayerRelationship( Int playerIndex ); - - /** - a convenience routine to count the number of owned objects that match a set of ThingTemplates. - You input the count and an array of ThingTemplate*, and provide an array of Int of the same - size. It fills in the array to the correct counts. This is handy because we must traverse - the team's list-of-objects only once. - */ - void countObjectsByThingTemplate(Int numTmplates, const ThingTemplate* const* things, Bool ignoreDead, Int *counts, Bool ignoreUnderConstruction = TRUE ) const; - - - /** - returns the number of buildings on this team, by checking each things' template kindof against KINDOF_STRUCTURE - */ - Int countBuildings(); - - /** - simply returns the number of objects on this team with a specific KindOfMaskType - */ - Int countObjects(KindOfMaskType setMask, KindOfMaskType clearMask); - - /** - This Team will heal all its members - */ - void healAllObjects(); - - /** - * Iterate all members of the team - */ - void iterateObjects( ObjectIterateFunc func, void *userData ); - - /** - a convenience routine to quickly check if any buildings are owned. - */ - Bool hasAnyBuildings() const; - - /** - a convenience routine to quickly check if any buildings with a specific KindOfType flag are owned. - */ - Bool hasAnyBuildings(KindOfMaskType kindOf) const; - - /** - a convenience routine to quickly check if any units are owned. - */ - Bool hasAnyUnits() const; - - /** - a convenience routine to quickly check if any objects are owned. - */ - Bool hasAnyObjects() const; - - /** - a convenience routine to quickly check if all the units are idle. - */ - Bool isIdle() const; - - /** - a convenience routine to quickly check if any objects are in a trigger area. - */ - Bool unitsEntered(PolygonTrigger *pTrigger) const; - - /** - a convenience routine to quickly check if any buildfacilities are owned. - */ - Bool hasAnyBuildFacility() const; - - /** - Move team to destination. - */ - void moveTeamTo(Coord3D destination); - - /** - a convenience routine to quickly destroy a team. - */ - Bool damageTeamMembers(Real amount); - - /** - a convenience routine to destroy this team. The team goes through all shutdown stuff. - Note that this doesn't actually call deleteInstance, the team will actually be - deleted on the next update, if it is a deletable team. - IgnoreDead lets you not delete people who are dying anyway. Needed for scripts. - */ - void deleteTeam(Bool ignoreDead = FALSE); - - /** - a convenience routine used to estimate the team's position by just returning the position - of the first member of the team - */ - const Coord3D* getEstimateTeamPosition() const; - - /** - a convenience routine to move a team's units to another team. - */ - void transferUnitsTo(Team *newTeam); - - /** - a function to kill all members of a team - */ - void killTeam(); - - /** - a function to make all containers on a team to dump contents - */ - void evacuateTeam(); - - /** - the current waypoint for a team following a waypoint path. - */ - const Waypoint *getCurrentWaypoint() {return m_currentWaypoint;} - void setCurrentWaypoint(const Waypoint *way) {m_currentWaypoint = way;} - - /** - Update the generic scripts, allow them to see if they should run, etc. - */ - - void updateGenericScripts(); - -}; - -// ------------------------------------------------------------------------ -/** - Note that TeamPrototype is used to hold information that is invariant between - multiple instances of a given Team (e.g., alliance info). - - However, a TeamPrototype doesn't contain any build-list style info; that is handled - by the BuildList stuff. -*/ -class TeamPrototype : public MemoryPoolObject, - public Snapshot -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(TeamPrototype, "TeamPrototypePool" ) - -public: - - TeamPrototype( TeamFactory *tf, - const AsciiString& name, - Player *ownerPlayer, - Bool isSingleton, - Dict *d, - TeamPrototypeID id ); - // virtual destructor prototype provided by memory pool object - - TeamPrototypeID getID() const { return m_id; } - const AsciiString& getName() const { return m_name; } - Bool getIsSingleton() const { return (m_flags & TEAM_SINGLETON) != 0; } - const TeamTemplateInfo *getTemplateInfo() const {return &m_teamTemplate;} - /** - return the team's owner (backtracking up if necessary) - */ - Player *getControllingPlayer() const; - - /** - * Return a team with matching team ID if present - */ - Team *findTeamByID( TeamID teamID ); - - /** - set the team's owner. (nullptr is not allowed) - */ - void setControllingPlayer(Player *newController); - - /** - Evaluate team's production condition. - */ - Bool evaluateProductionCondition(); - - /** - count for all the team instances belonging to this prototype. - */ - void countObjectsByThingTemplate(Int numTmplates, const ThingTemplate* const* things, Bool ignoreDead, Int *counts, Bool ignoreUnderConstruction = TRUE ) const; - - /** - count the buildings owned by this Team template - */ - Int countBuildings(); - - /** - simply returns the number of objects on this team with a specific KindOfMaskType - */ - Int countObjects(KindOfMaskType setMask, KindOfMaskType clearMask); - - /** - This TeamProtoType will heal all objects in all its instances - */ - void healAllObjects(); - - /** - * Iterate all members of the team - */ - void iterateObjects( ObjectIterateFunc func, void *userData ); - - /// count the number of teams that have been instanced by this prototype - Int countTeamInstances(); - - /** - Checks & clears the flags that a team member entered or exited a trigger area, or was created. - */ - void updateState(); - - /** - a convenience routine to quickly check if any buildings are owned. - */ - Bool hasAnyBuildings() const; - - /** - a convenience routine to quickly check if any buildings with a specific KindOfType flag are owned. - */ - Bool hasAnyBuildings(KindOfMaskType kindOf) const; - - /** - a convenience routine to quickly check if any units are owned. - */ - Bool hasAnyUnits() const; - - /** - a convenience routine to quickly check if any objects are owned. - */ - Bool hasAnyObjects() const; - - /** - a convenience routine to quickly check if any buildfacilities are owned. - */ - Bool hasAnyBuildFacility() const; - - /** - a convenience routine to quickly destroy a team. - */ - void damageTeamMembers(Real amount); - - /** - Move team to destination. - */ - void moveTeamTo(Coord3D destination); - - // this is intended for use ONLY by class Player. - void friend_setOwningPlayer(Player* p) { m_owningPlayer = p; } - - void teamAboutToBeDeleted(Team* team); - - Script *getGenericScript(Int scriptToRetrieve); - - // Make a team more likely to be selected by the ai for building due to success. - void increaseAIPriorityForSuccess() const; - // Make a team less likely to be selected by the ai for building due to failure. - void decreaseAIPriorityForFailure() const; - - void setAttackPriorityName(const AsciiString &name) { m_attackPriorityName = name;} - AsciiString getAttackPriorityName() const { return m_attackPriorityName;} - -protected: - - // snapshot methods - virtual void crc( Xfer *xfer ) override; - virtual void xfer( Xfer *xfer ) override; - virtual void loadPostProcess() override; - -private: - - enum TeamPrototypeFlags - { - /** - if set, this prototype should only produce one team. if there's already a team - by this name, newly produced team members are added to it, rather than - put into a new team of the same name. - */ - TEAM_SINGLETON = 0x01 - }; - - TeamFactory *m_factory; ///< the factory that created us - Player *m_owningPlayer; ///< the Player that currently controls the team-proto (null if NOT a top-level team) - - TeamPrototypeID m_id; ///< unique prototype ID - AsciiString m_name; ///< name of the team(s) produced - Int m_flags; ///< misc team flags - - Bool m_productionConditionAlwaysFalse; ///< Flag set to true if we don't have a production condition. - Script *m_productionConditionScript; ///< Script to evaluate for production condition. - - Bool m_retrievedGenericScripts; - Script *m_genericScriptsToRun[MAX_GENERIC_SCRIPTS]; - - TeamTemplateInfo m_teamTemplate; ///< Team template info. - - AsciiString m_attackPriorityName; - // lists we own - /// @todo srj -- convert to non-DLINK list, after it is once again possible to test the change - MAKE_DLINK_HEAD(Team, TeamInstanceList) ///< the instances of this prototype - -}; - -// ------------------------------------------------------------------------ -class TeamFactory : public SubsystemInterface, - public Snapshot -{ -public: - - TeamFactory(); - virtual ~TeamFactory() override; - - // subsystem methods - virtual void init() override; - virtual void reset() override; - virtual void update() override; - - void clear(); - void initFromSides(SidesList *sides); - - /// create a new TeamPrototype and if singleton, a team. - void initTeam(const AsciiString& name, const AsciiString& owner, Bool isSingleton, Dict *d); - - /// return the TeamPrototype with the given name. if none exists, return null. - TeamPrototype *findTeamPrototype(const AsciiString& name); - - /// return TeamPrototype with matching ID. if none exists nullptr is returned - TeamPrototype *findTeamPrototypeByID( TeamPrototypeID id ); - - /// search all prototypes for the team with the matching id, if none found nullptr is returned - Team *findTeamByID( TeamID teamID ); - - // note that there is no way to directly destroy a specific TeamPrototype (or a Team); the only - // way to do this is to call TeamFactory::reset(), which destroys all of them. - - // ------ routines for dealing with Teams - - /// create a team. there must be a TeamPrototype with the given name, or an exception is thrown. - Team *createTeam(const AsciiString& name); - - /// create a team given an explicitly team prototype rather than a prototype name - Team *createTeamOnPrototype( TeamPrototype *prototype ); - - /// create a team. there must be a TeamPrototype with the given name, or an exception is thrown. - Team *createInactiveTeam(const AsciiString& name); - - /// return the team with the given name, or null if none exists. if multiple instances exist, return one arbitrarily. - Team *findTeam(const AsciiString& name); - - void addTeamPrototypeToList(TeamPrototype* team); - void removeTeamPrototypeFromList(TeamPrototype* team); - - void teamAboutToBeDeleted(Team* team); - -protected: - - // snapshot methods - virtual void crc( Xfer *xfer ) override; - virtual void xfer( Xfer *xfer ) override; - virtual void loadPostProcess() override; - -private: - - typedef std::map< NameKeyType, TeamPrototype*, std::less/**/> TeamPrototypeMap; - - TeamPrototypeMap m_prototypes; - TeamPrototypeID m_uniqueTeamPrototypeID; ///< used to assign unique ids to each team prototype - TeamID m_uniqueTeamID; ///< used to assign unique team ids to each team instance - -}; - -extern TeamFactory *TheTeamFactory; - - -// inline function ------------------------------------------------------------------------ -const AsciiString& Team::getName() const -{ - return m_proto->getName(); -} - - - -// ------------------------------------------------------------------------ diff --git a/Generals/Code/GameEngine/Include/Common/TunnelTracker.h b/Generals/Code/GameEngine/Include/Common/TunnelTracker.h deleted file mode 100644 index 50241906ab8..00000000000 --- a/Generals/Code/GameEngine/Include/Common/TunnelTracker.h +++ /dev/null @@ -1,102 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: TunnelTracker.h /////////////////////////////////////////////////////////// -// The part of a Player's brain that holds the communal Passenger list of all tunnels. -// This has a similar interface to a ContainModule, naturally, but players can't have modules. -// Author: Graham Smallwood, March, 2002 - -#pragma once - -#include "Common/GameType.h" -#include "Common/GameMemory.h" -#include "Common/Snapshot.h" -#include "GameLogic/Module/ContainModule.h" - -class TunnelTracker : public MemoryPoolObject, - public Snapshot -{ - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( TunnelTracker, "TunnelTracker" ); - -public: - TunnelTracker(); - // contain list access - void iterateContained( ContainIterateFunc func, void *userData, Bool reverse ); - UnsignedInt getContainCount() const { return m_containListSize; } - UnsignedInt getHeroUnitsContained() const { return m_heroUnitsContained; } - Int getContainMax() const; - const ContainedItemsList* getContainedItemsList() const { return &m_containList; } - void swapContainedItemsList(ContainedItemsList& newList); - - Bool isValidContainerFor(const Object* obj, Bool checkCapacity) const; - void addToContainList( Object *obj ); ///< add 'obj' to contain list - Bool removeFromContain( Object *obj, Bool exposeStealthUnits = FALSE ); ///< remove 'obj' from contain list - Bool isInContainer( Object *obj ); ///< Is this thing inside? - - void onTunnelCreated( const Object *newTunnel ); ///< A tunnel was made - void onTunnelDestroyed( const Object *deadTunnel ); ///< A tunnel was destroyed - - static void destroyObject( Object *obj, void *userData ); ///< Callback for Iterate Contained system - static void healObject( Object *obj, void *frames ); ///< Callback for Iterate Contained system - -#if RETAIL_COMPATIBLE_CRC || PRESERVE_TUNNEL_HEAL_STACKING - void healObjects(Real frames); ///< heal all objects within the tunnel -#else - void healObjects(); ///< heal all objects within the tunnel -#endif - -#if RETAIL_COMPATIBLE_CRC - UnsignedInt friend_getTunnelCount() const {return m_tunnelCount;}///< TunnelContains are allowed to ask if they are the last one ahead of deletion time -#else - UnsignedInt friend_getTunnelCount() const { return m_tunnelIDs.size(); }///< TunnelContains are allowed to ask if they are the last one ahead of deletion time -#endif - - const std::list< ObjectID > *getContainerList() const {return &m_tunnelIDs;} - - Object *getCurNemesis(); - void updateNemesis(const Object *target); - -protected: - - virtual void crc( Xfer *xfer ) override; - virtual void xfer( Xfer *xfer ) override; - virtual void loadPostProcess() override; - -private: - void updateFullHealTime(); - - std::list< ObjectID > m_tunnelIDs; ///< I have to try to keep track of these because Caves need to iterate on them. - ContainedItemsList m_containList; ///< the contained object pointers list - std::list< ObjectID > m_xferContainList;///< for loading of m_containList during post processing - Int m_containListSize; ///< size of the contain list - UnsignedInt m_heroUnitsContained; ///< cached hero count -#if RETAIL_COMPATIBLE_CRC - UnsignedInt m_tunnelCount; ///< How many tunnels have registered so we know when we should kill our contain list -#endif - UnsignedInt m_framesForFullHeal; ///< How many frames it takes to fully heal a unit - Bool m_needsFullHealTimeUpdate; ///< Set to true when needing to recalc full heal time to batch the operation - - ObjectID m_curNemesisID; ///< If we have team(s) guarding a tunnel network system, this is one of the current targets. - UnsignedInt m_nemesisTimestamp; ///< We only keep nemesis for a couple of seconds. -}; diff --git a/Generals/Code/GameEngine/Source/Common/RTS/ActionManager.cpp b/Generals/Code/GameEngine/Source/Common/RTS/ActionManager.cpp deleted file mode 100644 index 07069248e59..00000000000 --- a/Generals/Code/GameEngine/Source/Common/RTS/ActionManager.cpp +++ /dev/null @@ -1,2154 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: ActionManager.cpp //////////////////////////////////////////////////////////////////////// -// Author: Colin Day -// Desc: TheActionManager is a convenient place for us to wrap up all sorts of logical -// queries about what objects can do in the world and to other objects. The purpose -// of having a central place for this logic assists us in making these logical kind -// of queries in the user interface and allows us to use the same code to validate -// commands as they come in over the network interface in order to do the -// real action. -/////////////////////////////////////////////////////////////////////////////////////////////////// - -// INCLUDES /////////////////////////////////////////////////////////////////////////////////////// -#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine - -#include "Common/ActionManager.h" -#include "Common/BuildAssistant.h" -#include "Common/GlobalData.h" -#include "Common/Player.h" -#include "Common/PlayerList.h" -#include "Common/SpecialPower.h" -#include "Common/Team.h" -#include "Common/ThingTemplate.h" - -#include "GameClient/Drawable.h" -#include "GameClient/InGameUI.h" - -#include "GameLogic/Object.h" -#include "GameLogic/PartitionManager.h" -#include "GameLogic/Module/BodyModule.h" -#include "GameLogic/Module/ContainModule.h" -#include "GameLogic/Module/CollideModule.h" -#include "GameLogic/Module/DozerAIUpdate.h" -#include "GameLogic/Module/RailroadGuideAIUpdate.h" -#include "GameLogic/Module/RailedTransportDockUpdate.h" -#include "GameLogic/Module/SpawnBehavior.h" -#include "GameLogic/Module/SupplyTruckAIUpdate.h" -#include "GameLogic/Module/SupplyCenterDockUpdate.h" -#include "GameLogic/Module/SupplyWarehouseDockUpdate.h" -#include "GameLogic/Module/SpecialPowerModule.h" -#include "GameLogic/Module/SpecialAbilityUpdate.h" -#include "GameLogic/Weapon.h" - -#include "GameLogic/ExperienceTracker.h"//LORENZEN - - -// GLOBAL ///////////////////////////////////////////////////////////////////////////////////////// -ActionManager *TheActionManager = nullptr; - -// LOCAL ////////////////////////////////////////////////////////////////////////////////////////// - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -static Bool appearsToContainFriendlies(const Object* obj, const Object* otherObject) -{ - // check if the object is a container containing stealth units tricking - // the player into thinking it isn't actually an enemy. - const ContainModuleInterface *otherContain = otherObject->getContain(); - if( otherContain ) - { - const Player *otherPlayer = otherContain->getApparentControllingPlayer(obj->getControllingPlayer()); -// if( otherPlayer && otherPlayer->getRelationship( obj->getTeam() ) != ENEMIES ) -// the above test is wrong; we want to know how WE consider THEM, not how THEY consider US - if (otherPlayer && obj->getTeam()->getRelationship(otherPlayer->getDefaultTeam()) != ENEMIES) - { - return TRUE; - } - } - return FALSE; -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -static Bool isObjectShroudedForAction ( const Object *source, const Object *target, CommandSourceType commandSource ) -{ - /// @todo - reenable this when we can avoid breaking scripted actions. - // In order to support ai and scripted actions in singler player, we have to disable this for now. - // We can re-enable it when we can tell that this is a player generated action. jba. -// return false; - // GS Keeping this comment to show we now have commandSource, so everything should be fine again. - - // The target is only shrouded for action if... - - // the asking player is human - // the asking impetus is not from a script - // and the target object is Fogged or worse - - if( source && target && source->getControllingPlayer() ) - { - if( source->getControllingPlayer()->getPlayerType() == PLAYER_HUMAN && - commandSource != CMD_FROM_SCRIPT && - target->getShroudedStatus( source->getControllingPlayer()->getPlayerIndex() ) >= OBJECTSHROUD_FOGGED - ) - { - return TRUE; - } - } - - return FALSE; -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -ActionManager::ActionManager() -{ - -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -ActionManager::~ActionManager() -{ - -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -Bool ActionManager::canGetRepairedAt( const Object *obj, const Object *repairDest, CommandSourceType commandSource ) -{ - - // sanity - if( obj == nullptr || repairDest == nullptr ) - return FALSE; - - Relationship r = obj->getRelationship(repairDest); - - // only available by our allies - if( r != ALLIES ) - return FALSE; - - // dead objects cannot be repaired - if( obj->isEffectivelyDead() ) - return FALSE; - -#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) - // If I can't move, I can't get repaired - if( !obj->isMobile() ) - return FALSE; -#endif - - // nothing can be done with things that are under construction - if( obj->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) || - repairDest->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) ) - return FALSE; - - // Can't get repaired at something being sold - if( repairDest->testStatus(OBJECT_STATUS_SOLD) ) - return FALSE; - - // only vehicles can go get repaired at something - if( obj->isKindOf( KINDOF_VEHICLE ) == FALSE ) - return FALSE; - - // vehicles can only be repaired at something that is designated as a repair pad - if (obj->isKindOf( KINDOF_AIRCRAFT )) - { - // aircraft require an airfield. - if( !obj->isAboveTerrain() || - repairDest->isKindOf( KINDOF_FS_AIRFIELD ) == FALSE ) - return FALSE; - } - else - { - if( repairDest->isKindOf( KINDOF_REPAIR_PAD ) == FALSE ) - return FALSE; - } - - // if I am at full health, I can't get repair there - BodyModuleInterface *body = obj->getBodyModule(); - if( body->getHealth() == body->getMaxHealth() ) - return FALSE; - - // if the target is in the shroud, we can't do anything - if (isObjectShroudedForAction(obj, repairDest, commandSource)) - return FALSE; - - // all is well, we can be repaired here - return TRUE; - -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -// note that "dest" is typically a building... -Bool ActionManager::canTransferSuppliesAt( const Object *obj, const Object *transferDest ) -{ - - // sanity - if( obj == nullptr || transferDest == nullptr ) - return FALSE; - - if( transferDest->isEffectivelyDead() ) - { - return FALSE; - } - - // nothing can be done with things that are under construction - if( obj->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) || - transferDest->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) ) - return FALSE; - - // Can't transfer at something being sold - if( transferDest->testStatus(OBJECT_STATUS_SOLD) ) - return FALSE; - - // I must be something with a Supply Transferring AI interface - const AIUpdateInterface *ai= obj->getAI(); - if( ai == nullptr ) - return FALSE; - - const SupplyTruckAIInterface* supplyTruck = ai->getSupplyTruckAIInterface(); - if( supplyTruck == nullptr ) - return FALSE; - - // If it is a warehouse, it must have boxes left and not be an enemy - static const NameKeyType key_warehouseUpdate = NAMEKEY("SupplyWarehouseDockUpdate"); - SupplyWarehouseDockUpdate *warehouseModule = (SupplyWarehouseDockUpdate*)transferDest->findUpdateModule( key_warehouseUpdate ); - if( warehouseModule ) - if( warehouseModule->getBoxesStored() == 0 || transferDest->getRelationship( obj ) == ENEMIES ) - return FALSE; - - // if it is a supply center, I must have boxes, and must be controlled by the same player - // (not merely an ally... otherwise you may find yourself funding your allies. ick.) - static const NameKeyType key_centerUpdate = NAMEKEY("SupplyCenterDockUpdate"); - SupplyCenterDockUpdate *centerModule = (SupplyCenterDockUpdate*)transferDest->findUpdateModule( key_centerUpdate ); - if( centerModule ) - if( supplyTruck->getNumberBoxes() == 0 || transferDest->getControllingPlayer() != obj->getControllingPlayer() ) - return FALSE; - - // if he is not a warehouse or a center, then shut the hell up - if( (warehouseModule == nullptr) && (centerModule == nullptr) ) - return FALSE; - - // We do not check ClearToApproach, as it is a temporary failure that is handled - // in the state logic. This function is for Legality, not conditionals. - // however, we DO check for the unit to be available (cf Chinook) (srj) - if (!supplyTruck->isAvailableForSupplying()) - return FALSE; - - // if the target is in the shroud, we can't do anything -// if (isObjectShroudedForAction(obj, transferDest)) -// return FALSE; - //Commented out to show it is an intentional difference to most commands. - - // Fogged is okay for player, and anything is okay for AI. - Player *objPlayer = obj->getControllingPlayer(); - if( objPlayer ) - { - if( objPlayer->getPlayerType() == PLAYER_HUMAN && - transferDest->getShroudedStatus( objPlayer->getPlayerIndex() ) == OBJECTSHROUD_SHROUDED ) - { - return FALSE; - } - } - - // all is well, we can transfer here - return TRUE; - -} - -// ------------------------------------------------------------------------------------------------ -/** Can object 'obj' dock with object 'dockDest' for any reason */ -// ------------------------------------------------------------------------------------------------ -Bool ActionManager::canDockAt( const Object *obj, const Object *dockDest, CommandSourceType commandSource ) -{ - - // look for a dock interface - DockUpdateInterface *di = nullptr; - for (BehaviorModule **u = dockDest->getBehaviorModules(); *u; ++u) - { - if ((di = (*u)->getDockUpdateInterface()) != nullptr) - break; - } - if( di == nullptr ) - return FALSE; // no dock update interface, can't possibly dock - -/* - // can't dock if the dock is closed - if( di->isDockOpen() == FALSE ) - return FALSE; -*/ - - // transferring supplies is a valid docking action - if( canTransferSuppliesAt( obj, dockDest ) == TRUE ) - return TRUE; - - // units and infantry can dock with a railed transport - static const NameKeyType key = NAMEKEY( "RailedTransportDockUpdate" ); - RailedTransportDockUpdate *fdu = (RailedTransportDockUpdate *)dockDest->findUpdateModule( key ); - if( fdu ) - { - - if( obj->isKindOf( KINDOF_VEHICLE ) || obj->isKindOf( KINDOF_INFANTRY ) ) - return TRUE; - - } - - // cannot dock - return FALSE; - -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -Bool ActionManager::canGetHealedAt( const Object *obj, const Object *healDest, CommandSourceType commandSource ) -{ - - // sanity - if( obj == nullptr || healDest == nullptr ) - return FALSE; - - Relationship r = obj->getRelationship(healDest); - - // only available by our allies - if( r != ALLIES ) - return FALSE; - - // dead objects cannot be healed - if( healDest->isEffectivelyDead() ) - return FALSE; - - // nothing can be done with things that are under construction - if( obj->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) || - healDest->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) ) - return FALSE; - - // Can't get healed at something being sold - if( healDest->testStatus(OBJECT_STATUS_SOLD) ) - return FALSE; - - // only infantry can go get "healed" somewhere (vehicles get "repaired") - if( obj->isKindOf( KINDOF_INFANTRY ) == FALSE ) - return FALSE; - - // infantry can only be healed at something that is designated as a heal pad - if( healDest->isKindOf( KINDOF_HEAL_PAD ) == FALSE ) - return FALSE; - - // if the target is in the shroud, we can't do anything - if (isObjectShroudedForAction(obj, healDest, commandSource)) - return FALSE; - - BodyModuleInterface *body = obj->getBodyModule(); - if( body && body->getHealth() == body->getMaxHealth() ) - { - //No point in healing if you have full health! - return FALSE; - } - - // all is well, we can be healed here - return TRUE; - -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -Bool ActionManager::canRepairObject( const Object *obj, const Object *objectToRepair, CommandSourceType commandSource ) -{ - - // sanity - if( obj == nullptr || objectToRepair == nullptr ) - return FALSE; - - Relationship r = obj->getRelationship(objectToRepair); - - // you can only repair allies, we ignore this restriction for bridges - // srj sez: nope, allow neutral too, so civ bldgs can be repaired - // GS repairing bridges cut 12/12/02 , so this check is just no to enemies - if( r == ENEMIES ) - return FALSE; - - // - // can't repair dead things ... the exception is bridges and bridge towers, which can - // be destroyed and die, but can be repaired to bring the bring "back to life" - // - // GS and again, repairing bridges is cut, so this is just a dead check - if( objectToRepair->isEffectivelyDead() ) - { - return FALSE; - } - - //GS So here's the ensuring that they can't be repaired - if( objectToRepair->isKindOf(KINDOF_BRIDGE) || objectToRepair->isKindOf(KINDOF_BRIDGE_TOWER) ) - return FALSE; - - // nothing can be done with things that are under construction - if( obj->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) || - objectToRepair->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) ) - return FALSE; - - // we cannot manually repair things that are regeneration holes - if( objectToRepair->isKindOf( KINDOF_REBUILD_HOLE ) == TRUE ) - return FALSE; - - // only Dozers can go repair things - if( obj->isKindOf( KINDOF_DOZER ) == FALSE ) - return FALSE; - - // dozers can only repair buildings - if( objectToRepair->isKindOf( KINDOF_STRUCTURE ) == FALSE ) - return FALSE; - - // get the body module from the object to repair - BodyModuleInterface *body = objectToRepair->getBodyModule(); - - // buildings that are at full health cannot be repaired - if( body->getHealth() == body->getMaxHealth() ) - return FALSE; - - // if the target is in the shroud, we can't do anything - if (isObjectShroudedForAction(obj, objectToRepair, commandSource)) - return FALSE; - - if( obj->getContainedBy() ) - { - // We can't heal things while in a transport (especially our own transport, you cheater) - return FALSE; - } - - return TRUE; - -} - -// ------------------------------------------------------------------------------------------------ -/** Can 'obj' resume the construction of 'objectBeingConstructed' */ -// ------------------------------------------------------------------------------------------------ -Bool ActionManager::canResumeConstructionOf( const Object *obj, - const Object *objectBeingConstructed, - CommandSourceType commandSource ) -{ - - // sanity - if( obj == nullptr || objectBeingConstructed == nullptr ) - return FALSE; - - // only dozers or workers can resume construction of things - if( obj->isKindOf( KINDOF_DOZER ) == FALSE ) - return FALSE; - - // TheSuperHackers @bugfix Stubbjax 06/01/2026 Ensure only the owner of the construction can resume it. -#if RETAIL_COMPATIBLE_CRC - Relationship r = obj->getRelationship(objectBeingConstructed); - - // only available to our allies - if( r != ALLIES ) - return FALSE; -#else - if (obj->getControllingPlayer() != objectBeingConstructed->getControllingPlayer()) - return FALSE; -#endif - - // if the objectBeingConstructed is not actually under construction we can't resume that! - if( !objectBeingConstructed->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) ) - return FALSE; - - // dead things can do nothing - if( obj->isEffectivelyDead() ) - { - return FALSE; - } - - // - // if the object being constructed is actively being built by another dozer we cannot - // add more effectiveness to the construction so we'll say no (this might change for workers - // in the future) - // - Object *builder = TheGameLogic->findObjectByID( objectBeingConstructed->getBuilderID() ); -#if RETAIL_COMPATIBLE_CRC || PRESERVE_BUILDING_RESUMPTION_DELAY - if( builder ) -#else - // TheSuperHackers @bugfix Stubbjax 18/11/2025 Allow scaffold to be immediately resumed after builder death. - if (builder && !builder->isEffectivelyDead()) -#endif - { - AIUpdateInterface *ai = builder->getAI(); - DEBUG_ASSERTCRASH( ai, ("Builder object does not have an AI interface!") ); - - if( ai ) - { - DozerAIInterface *dozerAI = ai->getDozerAIInterface(); - DEBUG_ASSERTCRASH( dozerAI, ("Builder object doest not have a DozerAI interface!") ); - - if( dozerAI ) - { - - if( dozerAI->getCurrentTask() == DOZER_TASK_BUILD && - dozerAI->getTaskTarget( DOZER_TASK_BUILD ) == objectBeingConstructed->getID() ) - return FALSE; - - } - - } - - } - - // if the target is in the shroud, we can't do anything - if (isObjectShroudedForAction(obj, objectBeingConstructed, commandSource)) - return FALSE; - - // - // all is well, the objectBeingConstructeds' builder object has gone away or is no longer - // building the object anymore - // - - return TRUE; - -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -Bool ActionManager::canEnterObject( const Object *obj, const Object *objectToEnter, CommandSourceType commandSource, CanEnterType mode ) -{ - - // sanity - if( obj == nullptr || objectToEnter == nullptr ) - return FALSE; - - if( obj == objectToEnter ) - { - //You can't contain yourself (crash fix for pow truck reselection) - return FALSE; - } - - // can't enter dead things - if( objectToEnter->isEffectivelyDead() ) - return FALSE; - - // if the target is in the shroud, we can't do anything - if (isObjectShroudedForAction(obj, objectToEnter, commandSource)) - return FALSE; - - // nothing can be done with things that are under construction - if( obj->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) || - objectToEnter->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) ) - { - return FALSE; - } - - // Can't enter something being sold - if( objectToEnter->testStatus(OBJECT_STATUS_SOLD) ) - return FALSE; - if ( obj->isKindOf( KINDOF_IGNORED_IN_GUI ) || //As in, Angry Mob Members, Cargo Planes - obj->isKindOf( KINDOF_MOB_NEXUS ) || - objectToEnter->isKindOf( KINDOF_IGNORED_IN_GUI ) ) // As in Cargo Planes - { - - return FALSE; - } - - - if (objectToEnter->isDisabledByType( DISABLED_SUBDUED )) - return FALSE; // a microwave tank has soldered the doors shut - - - if( obj->isKindOf( KINDOF_STRUCTURE ) || obj->isKindOf( KINDOF_IMMOBILE ) ) - { - //Structures or immobiles can't garrison - return FALSE; - } - - // Special case for unmanned vehicles. Any infantry unit can take over any unmanned vehicle! - if( obj->isKindOf( KINDOF_INFANTRY ) && objectToEnter->isDisabledByType( DISABLED_UNMANNED ) ) - { - if( !obj->isKindOf( KINDOF_REJECT_UNMANNED ) ) - { - //But only if it's allowed to. - return TRUE; - } - } - - // Special case for aircraft. - if( obj->isKindOf( KINDOF_AIRCRAFT ) && objectToEnter->isKindOf( KINDOF_FS_AIRFIELD ) ) - { - if( obj->getStatusBits().test( OBJECT_STATUS_DECK_HEIGHT_OFFSET ) && obj->getCarrierDeckHeight() >= obj->getPosition()->z ) - { - return FALSE; - } - - if (!obj->isAboveTerrain()) - return FALSE; - - if( obj->getControllingPlayer() == objectToEnter->getControllingPlayer() ) - { - //Kris -- added code to prevent aircraft from landing in any airstrips other than their own! - - /// @todo srj -- this is horrible, but expedient. - for (BehaviorModule** i = objectToEnter->getBehaviorModules(); *i; ++i) - { - ParkingPlaceBehaviorInterface* pp = (*i)->getParkingPlaceBehaviorInterface(); - if (pp == nullptr) - continue; - - if (pp->hasReservedSpace(obj->getID())) - return TRUE; - - if (pp->shouldReserveDoorWhenQueued(obj->getTemplate()) && pp->hasAvailableSpaceFor(obj->getTemplate())) - return TRUE; - } - } - return FALSE; - } - - // first, see if we'd like to collide with 'other' - for (BehaviorModule** m = obj->getBehaviorModules(); *m; ++m) - { - CollideModuleInterface* collide = (*m)->getCollide(); - if (!collide) - continue; - - if( collide->wouldLikeToCollideWith( objectToEnter ) ) - { - //I thought this was a little confusing that it would return TRUE here before - //getting to any of the other checks. The key is that it usually doesn't return - //TRUE because most things aren't trying to collide with objects. This is different - //for terrorist converting carbombs, and pilots entering vehicles. In these cases, - //the vehicles don't have transport capacities, therefore returning true here - //foregoes that checking later on. - return TRUE; - } - } - -#ifdef ALLOW_SURRENDER - if( objectToEnter->isKindOf( KINDOF_PRISON ) ) - { - //We can't manually enter a prison! - return FALSE; - } -#endif - -#ifdef ALLOW_SURRENDER - if( objectToEnter->isKindOf( KINDOF_POW_TRUCK ) ) - { - //We can't manually enter POWTruck, either! - return FALSE; - } -#endif - - // make sure our objectToEnter has a contain module. - ContainModuleInterface *contain = objectToEnter->getContain(); - if( !contain ) - { - return FALSE; - } - - if( contain->isHealContain() ) - { - BodyModuleInterface *body = obj->getBodyModule(); - if( body->getHealth() == body->getMaxHealth() ) - { - //This container is only used for the purposes of healing and we cannot - //enter it with full health. This is not a normal container. - return FALSE; - } - } - - if (mode == COMBATDROP_INTO) - { - // we don't care about valid container-ness, but we DO care about faction structures... - // we aren't allowed to combat drop into them - if (objectToEnter->isFactionStructure()) - return FALSE; - } - else - { - Bool checkCapacity = (mode == CHECK_CAPACITY); - Int containCount = contain->getContainCount(); - Int stealthContainCount = contain->getStealthUnitsContained(); - Int nonStealthContainCount = containCount - stealthContainCount; - - // not ours... must do special checks. - if (objectToEnter->getControllingPlayer() != obj->getControllingPlayer()) - { - // not empty... can't do it. - if (nonStealthContainCount > 0) - return FALSE; - - // faction structure... can't do it. - if (objectToEnter->isFactionStructure()) - return FALSE; - - // it's stealth-garrisoned... ignore check-cap and fall thru to - // normal isValid test. - if (stealthContainCount > 0 && nonStealthContainCount == 0) - checkCapacity = FALSE; - } - - // if our transport slot count is zero, we can't be transported. so punt. - /// @todo srj -- seems like we should check always (not just for checkCap), but scared to change now -- check later - if( checkCapacity && obj->getTransportSlotCount() == 0 ) - { - return FALSE; - } - - // finally: make sure that objectToEnter is a valid container for obj - if( contain->isValidContainerFor( obj, checkCapacity ) == FALSE ) - { - return FALSE; - } - } - - return TRUE; - -} - - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -CanAttackResult ActionManager::getCanAttackObject( const Object *obj, const Object *objectToAttack, CommandSourceType commandSource, AbleToAttackType attackType ) -{ - // sanity - if( !obj || !objectToAttack || obj->isEffectivelyDead() || objectToAttack->isEffectivelyDead() || objectToAttack == obj ) - { - return ATTACKRESULT_NOT_POSSIBLE; - } - - if( !obj->isAbleToAttack() ) - { - return ATTACKRESULT_NOT_POSSIBLE; - } - - //has any weapons that are capable of inflicting damage. Special damage types are rejected - //such as hack weapons... others can be added. - CanAttackResult result = obj->getAbleToAttackSpecificObject( attackType, objectToAttack, commandSource ); - if( result != ATTACKRESULT_NOT_POSSIBLE ) - { -#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) - //Kris: August 5, 2003 - //Fix a case where the Demo_GLAInfantryWorker is able to attack using his passive bomb upgrade. We don't - //want him to allow a visible attack cursor for the player. This code never checked for AutoChoosesSources - //logic, but now we will but only when the commandSource is FROM_PLAYER. - if( commandSource == CMD_FROM_PLAYER ) - { - //Check if it's got any weapons that can be used. - Bool anyValidWeapon = FALSE; - for( Int i = 0; i < WEAPONSLOT_COUNT; i++ ) - { - UnsignedInt cmdSourceMask = obj->getWeaponInWeaponSlotCommandSourceMask( (WeaponSlotType)i ); - if( cmdSourceMask ) - { - anyValidWeapon = TRUE; - break; - } - } - if( !anyValidWeapon ) - { - return ATTACKRESULT_NOT_POSSIBLE; - } - } -#endif - - if( result == ATTACKRESULT_INVALID_SHOT && obj->isKindOf( KINDOF_DOZER ) ) - { - //For the case of dozers, we don't ever want to see an attack cursor - //unless it's valid on a mine. - const Weapon *weapon = obj->getCurrentWeapon(); - if( weapon && weapon->getDamageType() == DAMAGE_DISARM ) - { - return ATTACKRESULT_NOT_POSSIBLE; - } - } - return result; - } - - //Special case code for stinger sites: Stinger sites have no weapons, instead -- their spawns are the weapons, in this case the - //stinger soldiers. - if( obj->isKindOf( KINDOF_SPAWNS_ARE_THE_WEAPONS ) ) - { - //Look at the spawn behavior and evaluate them! - SpawnBehaviorInterface *spawnInterface = obj->getSpawnBehaviorInterface(); - if( spawnInterface ) - { - //We found the spawn interface, now get the closest slave to the target. - Object *slave = spawnInterface->getClosestSlave( objectToAttack->getPosition() ); - - if( slave ) - { - result = slave->getAbleToAttackSpecificObject( attackType, objectToAttack, commandSource ); - if( result != ATTACKRESULT_NOT_POSSIBLE ) - { - return result; - } - } - } - else if( result == ATTACKRESULT_NOT_POSSIBLE )// oh dear me. The weird case of a garrisoncontainer being a KINDOF_SPAWNS_ARE_THE_WEAPONS... the AmericaBuildingFirebase - { - ContainModuleInterface *contain = obj->getContain(); - if ( contain ) - { - Object *rider = contain->getClosestRider( objectToAttack->getPosition() ); - if ( rider ) - { - result = rider->getAbleToAttackSpecificObject( attackType, objectToAttack, commandSource ); - if( result != ATTACKRESULT_NOT_POSSIBLE ) - return result; - } - } - } - } - - return ATTACKRESULT_NOT_POSSIBLE; -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -Bool ActionManager::canConvertObjectToCarBomb( const Object *obj, const Object *objectToConvert, CommandSourceType commandSource ) -{ - - // sanity - if( obj == nullptr || objectToConvert == nullptr ) - { - return FALSE; - } - - if( objectToConvert->isEffectivelyDead() ) - { - return FALSE; - } - - // if the target is in the shroud, we can't do anything - if (isObjectShroudedForAction(obj, objectToConvert, commandSource)) - return FALSE; - - // first, see if we'd like to collide with 'other' - for (BehaviorModule** m = obj->getBehaviorModules(); *m; ++m) - { - CollideModuleInterface* collide = (*m)->getCollide(); - if (!collide) - continue; - - if( collide->wouldLikeToCollideWith( objectToConvert ) && collide->isCarBombCrateCollide() ) - { - return TRUE; - } - } - return FALSE; -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -Bool ActionManager::canHijackVehicle( const Object *obj, const Object *objectToHijack, CommandSourceType commandSource ) //LORENZEN -{ - // sanity - if( obj == nullptr || objectToHijack == nullptr ) - { - return FALSE; - } - - //Make sure it's alive. - if( objectToHijack->isEffectivelyDead() ) - { - return FALSE; - } - - // if the target is in the shroud, we can't do anything - if (isObjectShroudedForAction(obj, objectToHijack, commandSource)) - { - return FALSE; - } - - Relationship r = obj->getRelationship(objectToHijack); - //Only hijack enemy objects - if( r != ENEMIES ) - { - return FALSE; - } - - //Make sure target is a vehicle. - if( ! objectToHijack->isKindOf( KINDOF_VEHICLE ) ) - { - return FALSE; - } - - //Kris -- Hijackers can no longer hijack any aircraft. - if( objectToHijack->isKindOf( KINDOF_AIRCRAFT ) ) - { - return FALSE; - } - - //Can't hijack a drone type. - if( objectToHijack->isKindOf( KINDOF_DRONE ) ) - { - return FALSE; - } - - // last, see if we'd like to collide with 'objectToHijack' - for (BehaviorModule** m = obj->getBehaviorModules(); *m; ++m) - { - CollideModuleInterface* collide = (*m)->getCollide(); - if (!collide) - continue; - - if( collide->wouldLikeToCollideWith( objectToHijack ) && collide->isHijackedVehicleCrateCollide() ) - { - return TRUE; - } - } - - return FALSE; -} - -// ------------------------------------------------------------------------------------------------ -Bool ActionManager::canSabotageBuilding( const Object *obj, const Object *objectToSabotage, CommandSourceType commandSource ) -{ - // sanity - if( obj == nullptr || objectToSabotage == nullptr ) - { - return FALSE; - } - - //Make sure it's alive. - if( objectToSabotage->isEffectivelyDead() ) - { - return FALSE; - } - - // if the target is in the shroud, we can't do anything - if (isObjectShroudedForAction(obj, objectToSabotage, commandSource)) - { - return FALSE; - } - - Relationship r = obj->getRelationship(objectToSabotage); - //Only sabotage enemy objects - if( r != ENEMIES ) - { - return FALSE; - } - - // last, see if we'd like to collide with 'objectToSabotage' - for (BehaviorModule** m = obj->getBehaviorModules(); *m; ++m) - { - CollideModuleInterface* collide = (*m)->getCollide(); - if (!collide) - continue; - - if( collide->wouldLikeToCollideWith( objectToSabotage ) && collide->isSabotageBuildingCrateCollide() ) - { - return TRUE; - } - } - - return FALSE; -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -Bool ActionManager::canMakeObjectDefector( const Object *obj, const Object *objectToMakeDefector, CommandSourceType commandSource ) //LORENZEN -{ - // sanity - if( obj == nullptr || objectToMakeDefector == nullptr ) - { - return FALSE; - } - - Relationship r = obj->getRelationship(objectToMakeDefector); - - //Only make defectors of enemy objects - if( r != ENEMIES ) - { - return FALSE; - } - - //Make sure it's alive. - if( objectToMakeDefector->isEffectivelyDead() ) - { - return FALSE; - } - - // if the target is in the shroud, we can't do anything - if (isObjectShroudedForAction(obj, objectToMakeDefector, commandSource)) - { - return FALSE; - } - - - return TRUE; -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ - -Bool ActionManager::canCaptureBuilding( const Object *obj, const Object *objectToCapture, CommandSourceType commandSource ) -{ - - // sanity - if( obj == nullptr || objectToCapture == nullptr ) - return FALSE; - - //Make sure our object has the capability of performing this special ability. - - Bool isOwnerBlackLotus = obj->hasSpecialPower( SPECIAL_BLACKLOTUS_CAPTURE_BUILDING ); - - if( !obj->hasSpecialPower( SPECIAL_INFANTRY_CAPTURE_BUILDING ) && !isOwnerBlackLotus) - { - return false; - } - - if( objectToCapture->isKindOf( KINDOF_IMMUNE_TO_CAPTURE ) ) - { - return false; - } - -// This is the althernate way to one-at-a-time BlackLotus' specials; we'll keep it commented her until Dustin decides, or until 12/10/02 -// if ( isOwnerBlackLotus ) -// { -// SpecialPowerModuleInterface *disableSPI = obj->findSpecialPowerModuleInterface( SPECIAL_BLACKLOTUS_DISABLE_VEHICLE_HACK ); -// if ( disableSPI && disableSPI->isBusy() ) -// return FALSE; -// SpecialPowerModuleInterface *cashSPI = obj->findSpecialPowerModuleInterface( SPECIAL_BLACKLOTUS_STEAL_CASH_HACK ); -// if ( cashSPI && cashSPI->isBusy() ) -// return FALSE; -// } - - - SpecialPowerModuleInterface *spInterface = obj->findSpecialPowerModuleInterface( SPECIAL_INFANTRY_CAPTURE_BUILDING ); - if (!spInterface) - spInterface = obj->findSpecialPowerModuleInterface( SPECIAL_BLACKLOTUS_CAPTURE_BUILDING ); - if (!spInterface) - return false; - - if( spInterface->getPercentReady() < 1.0f ) - { - // Special not ready or non-existent. - return false; - } - - // can't capture dead things. - if (objectToCapture->isEffectivelyDead()) - { - return FALSE; - } - - // Make sure we are targeting a building! - if( !objectToCapture->isKindOf( KINDOF_STRUCTURE ) ) - { - return FALSE; - } - - // can't capture things that are under construction, or sold. - if (objectToCapture->testStatus(OBJECT_STATUS_UNDER_CONSTRUCTION) || - objectToCapture->testStatus(OBJECT_STATUS_SOLD)) - { - return FALSE; - } - - // if the target is in the shroud, we can't do anything - if (isObjectShroudedForAction(obj, objectToCapture, commandSource)) - return FALSE; - - Relationship r = obj->getRelationship(objectToCapture); - - // ensure that it's capturable, and not allied - // exception: we can always capture enemy bldgs, regardless of kindof - if (!(r == ENEMIES || (objectToCapture->isKindOf(KINDOF_CAPTURABLE) && r != ALLIES))) - return false; - - //If the enemy unit is stealthed and not detected, then we can't capture it! - if( objectToCapture->testStatus( OBJECT_STATUS_STEALTHED ) && - !objectToCapture->testStatus( OBJECT_STATUS_DETECTED ) -#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) - && !objectToCapture->testStatus( OBJECT_STATUS_DISGUISED ) -#endif - ) - { - return FALSE; - } - - // if it's garrisoned already, we cannot capture it. - // (unless it's just stealth-garrisoned.) - ContainModuleInterface *contain = objectToCapture->getContain(); - if (contain != nullptr && contain->isGarrisonable()) - { - Int containCount = contain->getContainCount(); - Int stealthContainCount = contain->getStealthUnitsContained(); - Int nonStealthContainCount = containCount - stealthContainCount; - if (nonStealthContainCount > 0) - return FALSE; - } - - // Also check if the object is a container containing stealth units, tricking - // the player into thinking it isn't actually an enemy. - if (appearsToContainFriendlies(obj, objectToCapture)) - return FALSE; - - return TRUE; -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -Bool ActionManager::canDisableVehicleViaHacking( const Object *obj, const Object *objectToHack, CommandSourceType commandSource, Bool checkSourceRequirements) -{ - // sanity - if( obj == nullptr || objectToHack == nullptr ) - return FALSE; - - if (checkSourceRequirements) - { - //Make sure our object has the capability of performing this special ability. - if( !obj->hasSpecialPower( SPECIAL_BLACKLOTUS_DISABLE_VEHICLE_HACK ) ) - { - return false; - } - } - -// This is the althernate way to one-at-a-time BlackLotus' specials; we'll keep it commented her until Dustin decides, or until 12/10/02 -// SpecialPowerModuleInterface *captureSPI = obj->findSpecialPowerModuleInterface( SPECIAL_BLACKLOTUS_CAPTURE_BUILDING ); -// if ( captureSPI && captureSPI->isBusy() ) -// return FALSE; -// SpecialPowerModuleInterface *cashSPI = obj->findSpecialPowerModuleInterface( SPECIAL_BLACKLOTUS_STEAL_CASH_HACK ); -// if ( cashSPI && cashSPI->isBusy() ) -// return FALSE; - - - SpecialPowerModuleInterface *spInterface = obj->findSpecialPowerModuleInterface( SPECIAL_BLACKLOTUS_DISABLE_VEHICLE_HACK ); - if (checkSourceRequirements) - { - if( !spInterface || spInterface->getPercentReady() < 1.0f ) - { - //Special not ready or non-existent. - return FALSE; - } - } - - if( objectToHack->isEffectivelyDead() ) - { - return FALSE; - } - - if( objectToHack->isKindOf( KINDOF_AIRCRAFT ) || objectToHack->isAirborneTarget() ) - { - return false; - } - - // if the target is in the shroud, we can't do anything - if (isObjectShroudedForAction(obj, objectToHack, commandSource)) - return FALSE; - - Relationship r = obj->getRelationship(objectToHack); - - // Make sure object is an enemy - if( r == ENEMIES ) - { - - //Make sure we are targeting a building! - if( !objectToHack->isKindOf( KINDOF_VEHICLE ) ) - { - return FALSE; - } - - //If the enemy unit is stealthed and not detected, then we can't attack it! - if( objectToHack->testStatus( OBJECT_STATUS_STEALTHED ) && - !objectToHack->testStatus( OBJECT_STATUS_DETECTED ) -#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) - && !objectToHack->testStatus( OBJECT_STATUS_DISGUISED ) -#endif - ) - { - return FALSE; - } - - //Also check if the object is a container containing stealth units tricking - //the player into thinking it isn't actually an enemy. - if (appearsToContainFriendlies(obj, objectToHack)) - return FALSE; - - return TRUE; - } - return FALSE; -} - -#ifdef ALLOW_SURRENDER -// ------------------------------------------------------------------------------------------------ -/** Can 'obj' pick up the prisoner 'prisoner' */ -// ------------------------------------------------------------------------------------------------ -Bool ActionManager::canPickUpPrisoner( const Object *obj, const Object *prisoner, CommandSourceType commandSource ) -{ - - // sanity - if( obj == nullptr || prisoner == nullptr ) - return FALSE; - - // only pow trucks can pick up anything - if( obj->isKindOf( KINDOF_POW_TRUCK ) == FALSE ) - return FALSE; - - // only infantry can be picked up - if( prisoner->isKindOf( KINDOF_INFANTRY ) == FALSE ) - return FALSE; - - // prisoner cannot be contained inside anything - if( prisoner->getContainedBy() ) - return FALSE; - - // prisoner must be in a surrendered state - const AIUpdateInterface *ai = prisoner->getAI(); - if( ai == nullptr || ai->isSurrendered() == FALSE ) - return FALSE; - - // prisoner must have been put in a surrendered state by our own player - // (or be surrendered to "everyone") - Int idx = ai->getSurrenderedPlayerIndex(); - Player* surrenderedToPlayer = (idx >= 0) ? ThePlayerList->getNthPlayer(idx) : nullptr; - if (surrenderedToPlayer != nullptr && surrenderedToPlayer != obj->getControllingPlayer()) - return FALSE; - - // we must be enemies - if( obj->getRelationship( prisoner ) != ENEMIES ) - return FALSE; - - return TRUE; - -} -#endif - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -Bool ActionManager::canStealCashViaHacking( const Object *obj, const Object *objectToHack, CommandSourceType commandSource ) -{ - // sanity - if( obj == nullptr || objectToHack == nullptr ) - return FALSE; - - //Make sure our object has the capability of performing this special ability. - if( !obj->hasSpecialPower( SPECIAL_BLACKLOTUS_STEAL_CASH_HACK ) ) - { - return false; - } - -// This is the althernate way to one-at-a-time BlackLotus' specials; we'll keep it commented her until Dustin decides, or until 12/10/02 -// SpecialPowerModuleInterface *captureSPI = obj->findSpecialPowerModuleInterface( SPECIAL_BLACKLOTUS_CAPTURE_BUILDING ); -// if ( captureSPI && captureSPI->isBusy() ) -// return FALSE; -// SpecialPowerModuleInterface *disableSPI = obj->findSpecialPowerModuleInterface( SPECIAL_BLACKLOTUS_DISABLE_VEHICLE_HACK ); -// if ( disableSPI && disableSPI->isBusy() ) -// return FALSE; - - - SpecialPowerModuleInterface *spInterface = obj->findSpecialPowerModuleInterface( SPECIAL_BLACKLOTUS_STEAL_CASH_HACK ); - if( !spInterface || spInterface->getPercentReady() < 1.0f ) - { - //Special not ready or non-existent. - return false; - } - - if( objectToHack->isEffectivelyDead() ) - { - return FALSE; - } - - if( objectToHack->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) ) - { - return FALSE; - } - - // if the target is in the shroud, we can't do anything - if (isObjectShroudedForAction(obj, objectToHack, commandSource)) - return FALSE; - - Relationship r = obj->getRelationship(objectToHack); - - // Make sure object is an enemy - if( r == ENEMIES ) - { - - //Make sure we are targeting something that contains cash! - if( !objectToHack->isKindOf( KINDOF_CASH_GENERATOR ) ) - { - return FALSE; - } - - //Make sure object isn't under construction! - if( objectToHack->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) ) - { - return FALSE; - } - - //Make sure the building is considered hackable (temp: using capturable) - if( !objectToHack->isKindOf( KINDOF_CAPTURABLE ) || objectToHack->isKindOf( KINDOF_REBUILD_HOLE ) ) - { - return FALSE; - } - - //If the enemy unit is stealthed and not detected, then we can't attack it! - if( objectToHack->testStatus( OBJECT_STATUS_STEALTHED ) && - !objectToHack->testStatus( OBJECT_STATUS_DETECTED ) -#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) - && !objectToHack->testStatus( OBJECT_STATUS_DISGUISED ) -#endif - ) - { - return FALSE; - } - - //Also check if the object is a container containing stealth units tricking - //the player into thinking it isn't actually an enemy. - if (appearsToContainFriendlies(obj, objectToHack)) - return FALSE; - - return TRUE; - } - return FALSE; -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -Bool ActionManager::canDisableBuildingViaHacking( const Object *obj, const Object *objectToHack, CommandSourceType commandSource ) -{ - // sanity - if( obj == nullptr || objectToHack == nullptr ) - return FALSE; - - //Make sure our object has the capability of performing this special ability. - if( !obj->hasSpecialPower( SPECIAL_HACKER_DISABLE_BUILDING ) ) - { - return FALSE; - } - - SpecialPowerModuleInterface *spInterface = obj->findSpecialPowerModuleInterface( SPECIAL_HACKER_DISABLE_BUILDING ); - if( !spInterface || spInterface->getPercentReady() < 1.0f ) - { - //Special not ready or non-existent. - return FALSE; - } - - if( objectToHack->isEffectivelyDead() ) - { - return FALSE; - } - - // if the target is in the shroud, we can't do anything - if (isObjectShroudedForAction(obj, objectToHack, commandSource)) - return FALSE; - - Relationship r = obj->getRelationship(objectToHack); - - // Make sure object is an enemy - if( r != ENEMIES ) - return FALSE; - - //Make sure we are targeting a building! - if( !objectToHack->isKindOf( KINDOF_STRUCTURE ) ) - { - return FALSE; - } - - //Make sure the building is considered hackable (temp: using capturable) - // An exception is any TechFactionBuilding that is not explicitly immune to capture - if( ( !objectToHack->isKindOf( KINDOF_CAPTURABLE ) || objectToHack->isKindOf( KINDOF_REBUILD_HOLE ) ) && - ! (objectToHack->isKindOf(KINDOF_FS_TECHNOLOGY) && ! objectToHack->isKindOf(KINDOF_IMMUNE_TO_CAPTURE)) ) - { - return FALSE; - } - - - if ( objectToHack->isKindOf( KINDOF_REBUILD_HOLE ) || objectToHack->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION )) - return FALSE; - - - //If the enemy unit is stealthed and not detected, then we can't attack it! - if( objectToHack->testStatus( OBJECT_STATUS_STEALTHED ) && - !objectToHack->testStatus( OBJECT_STATUS_DETECTED ) -#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) - && !objectToHack->testStatus( OBJECT_STATUS_DISGUISED ) -#endif - ) - { - return FALSE; - } - - //Also check if the object is a container containing stealth units tricking - //the player into thinking it isn't actually an enemy. - if (appearsToContainFriendlies(obj, objectToHack)) - return FALSE; - - return TRUE; -} - -// ------------------------------------------------------------------------------------------------ -Bool ActionManager::canBribeUnit( const Object *obj, const Object *objectToBribe, CommandSourceType commandSource ) -{ - return FALSE; -} - -// ------------------------------------------------------------------------------------------------ -Bool ActionManager::canCutBuildingPower( const Object *obj, const Object *building, CommandSourceType commandSource ) -{ - return FALSE; -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -Bool ActionManager::canSnipeVehicle( const Object *obj, const Object *objectToSnipe, CommandSourceType commandSource ) -{ - //Sanity check - if( obj == nullptr || objectToSnipe == nullptr ) - { - return FALSE; - } - - //Make sure it's alive. - if( objectToSnipe->isEffectivelyDead() ) - { - return FALSE; - } - - // if the target is in the shroud, we can't do anything - if (isObjectShroudedForAction(obj, objectToSnipe, commandSource)) - return FALSE; - - Relationship r = obj->getRelationship(objectToSnipe); - - if( r == ENEMIES ) - { - //Make sure target is a vehicle. - if( !objectToSnipe->isKindOf( KINDOF_VEHICLE ) ) - { - return FALSE; - } - - //Can't be a drone type. - if( objectToSnipe->isKindOf( KINDOF_DRONE ) ) - { - return FALSE; - } - - //Make sure object is not flying - if( objectToSnipe->isAirborneTarget() ) - { - return FALSE; - } - - //Make sure the vehicle is manned! - if( objectToSnipe->isDisabledByType( DISABLED_UNMANNED ) ) - { - return FALSE; - } - - // TheSuperHackers @bugfix Caball009 04/09/2025 Disabled bikes may not have a rider to snipe. - ContainModuleInterface* contain = objectToSnipe->getContain(); - if ( contain && contain->isRiderChangeContain() && contain->getContainedItemsList()->empty() ) - { - return FALSE; - } - - return TRUE; - } - - return FALSE; -} - - - - -//------------------------------------------------------------------------------------------------- -inline Bool isPointOnMap( const Coord3D *testPos ) -{ - Region3D mapRegion; - TheTerrainLogic->getExtent( &mapRegion ); - return mapRegion.containsWithin( testPos->asCoord2D() ); - -} - - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -Bool ActionManager::canDoSpecialPowerAtLocation( const Object *obj, const Coord3D *loc, CommandSourceType commandSource, const SpecialPowerTemplate *spTemplate, const Object *objectInWay, UnsignedInt commandOptions, Bool checkSourceRequirements ) -{ - if (checkSourceRequirements) - { - //First check, if our object can do this special power. - if( !obj->hasSpecialPower( spTemplate->getSpecialPowerType() ) ) - { - return false; - } - } - - SpecialPowerModuleInterface *mod = obj->getSpecialPowerModule( spTemplate ); - if( mod ) - { - if (checkSourceRequirements) - { - if( mod->getPercentReady() < 1.0f ) - { - //Not fully ready - return false; - } - } - - // First check terrain type, if it is cared about. Don't return a true, since there are more checks. - switch( spTemplate->getSpecialPowerType() ) - { - case SPECIAL_PARADROP_AMERICA: - case INFA_SPECIAL_PARADROP_AMERICA: - case SPECIAL_CRATE_DROP: - case SPECIAL_TANK_PARADROP: - { - if( TheTerrainLogic->isUnderwater( loc->x, loc->y ) ) - return FALSE; - } - } - - // Second check is shroudedness, if it is cared about - switch( spTemplate->getSpecialPowerType() ) - { - case SPECIAL_DAISY_CUTTER: - case AIRF_SPECIAL_DAISY_CUTTER: - case SPECIAL_PARADROP_AMERICA: - case SPECIAL_TANK_PARADROP: - case INFA_SPECIAL_PARADROP_AMERICA: - case SPECIAL_CARPET_BOMB: - case SPECIAL_CHINA_CARPET_BOMB: - case SPECIAL_LEAFLET_DROP: - case EARLY_SPECIAL_LEAFLET_DROP: - case EARLY_SPECIAL_CHINA_CARPET_BOMB: - case AIRF_SPECIAL_CARPET_BOMB: - case SUPR_SPECIAL_CRUISE_MISSILE: - case SPECIAL_CLUSTER_MINES: - case NUKE_SPECIAL_CLUSTER_MINES: - case SPECIAL_EMP_PULSE: - case SPECIAL_CRATE_DROP: - case SPECIAL_NAPALM_STRIKE: - case SPECIAL_BLACK_MARKET_NUKE: - case SPECIAL_ANTHRAX_BOMB: - case SPECIAL_TERROR_CELL: - case SPECIAL_AMBUSH: - case SPECIAL_NEUTRON_MISSILE: - case NUKE_SPECIAL_NEUTRON_MISSILE: - case SUPW_SPECIAL_NEUTRON_MISSILE: - case SPECIAL_SCUD_STORM: -#ifdef ALLOW_DEMORALIZE - case SPECIAL_DEMORALIZE: -#endif - case SPECIAL_A10_THUNDERBOLT_STRIKE: - case AIRF_SPECIAL_A10_THUNDERBOLT_STRIKE: - case SPECIAL_SPECTRE_GUNSHIP: - case AIRF_SPECIAL_SPECTRE_GUNSHIP: - case SPECIAL_REPAIR_VEHICLES: - case EARLY_SPECIAL_REPAIR_VEHICLES: - case SPECIAL_GPS_SCRAMBLER: - case SLTH_SPECIAL_GPS_SCRAMBLER: - case SPECIAL_ARTILLERY_BARRAGE: - case SPECIAL_FRENZY: - case EARLY_SPECIAL_FRENZY: - case SPECIAL_PARTICLE_UPLINK_CANNON: - case SUPW_SPECIAL_PARTICLE_UPLINK_CANNON: - case LAZR_SPECIAL_PARTICLE_UPLINK_CANNON: - case SPECIAL_CLEANUP_AREA: - case SPECIAL_BATTLESHIP_BOMBARDMENT: - //Don't allow "damaging" special powers in shrouded areas, but Fogged are okay. - return ThePartitionManager->getShroudStatusForPlayer( obj->getControllingPlayer()->getPlayerIndex(), loc ) != CELLSHROUD_SHROUDED; - - case SPECIAL_SPY_SATELLITE: - case SPECIAL_RADAR_VAN_SCAN: - case SPECIAL_SPY_DRONE: - case SPECIAL_HELIX_NAPALM_BOMB: -#if RTS_GENERALS && RETAIL_COMPATIBLE_CRC - //These specials can be used anywhere! - return TRUE; -#else - //These specials can be used anywhere! - return isPointOnMap( loc ); -#endif - case SPECIAL_LAUNCH_BAIKONUR_ROCKET: - return TRUE; - - //These special powers require object targets! - case SPECIAL_MISSILE_DEFENDER_LASER_GUIDED_MISSILES: - case SPECIAL_HACKER_DISABLE_BUILDING: - case SPECIAL_TANKHUNTER_TNT_ATTACK: - case SPECIAL_BOOBY_TRAP: - case SPECIAL_CASH_HACK: - case SPECIAL_DEFECTOR: - case SPECIAL_BLACKLOTUS_CAPTURE_BUILDING: - case SPECIAL_BLACKLOTUS_DISABLE_VEHICLE_HACK: - case SPECIAL_BLACKLOTUS_STEAL_CASH_HACK: - case SPECIAL_INFANTRY_CAPTURE_BUILDING: - case SPECIAL_DETONATE_DIRTY_NUKE: - case SPECIAL_DISGUISE_AS_VEHICLE: - case SPECIAL_REMOTE_CHARGES: - case SPECIAL_TIMED_CHARGES: - case SPECIAL_CASH_BOUNTY: - case SPECIAL_CHANGE_BATTLE_PLANS: - return false; - } - - // TheSuperHackers @fix stephanmeesters 04/04/2026 Some special powers can spawn a building. - // To avoid cheating, verify that it is legal to place this building. - switch( spTemplate->getSpecialPowerType() ) - { - case SPECIAL_SNEAK_ATTACK: - { -#if RETAIL_COMPATIBLE_CRC - return ThePartitionManager->getShroudStatusForPlayer( obj->getControllingPlayer()->getPlayerIndex(), loc ) != CELLSHROUD_SHROUDED; -#else - const ThingTemplate* referenceThing = mod->getReferenceThingTemplate(); - if (!referenceThing) - return FALSE; - - const Real angle = referenceThing->getPlacementViewAngle(); - - return TheBuildAssistant->isLocationLegalToBuild( - loc, referenceThing, angle, - BuildAssistant::USE_QUICK_PATHFIND | - BuildAssistant::TERRAIN_RESTRICTIONS | - BuildAssistant::CLEAR_PATH | - BuildAssistant::NO_OBJECT_OVERLAP | - BuildAssistant::SHROUD_REVEALED | - BuildAssistant::IGNORE_STEALTHED, - obj, nullptr) == LBC_OK; -#endif - } - } - } - return false; -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -Bool ActionManager::canDoSpecialPowerAtObject( const Object *obj, const Object *target, CommandSourceType commandSource, const SpecialPowerTemplate *spTemplate, UnsignedInt commandOptions, Bool checkSourceRequirements ) -{ - if (checkSourceRequirements) - { - //First check, if our object can do this special power. - if( !obj->hasSpecialPower( spTemplate->getSpecialPowerType() ) ) - { - return false; - } - } - - if( target->isEffectivelyDead() ) - { - return FALSE; - } - - Relationship r = obj->getRelationship(target); - - SpecialPowerModuleInterface *mod = obj->getSpecialPowerModule( spTemplate ); - if( mod ) - { - if (checkSourceRequirements) - { - if( mod->getPercentReady() < 1.0f ) - { - //Not fully ready - return false; - } - } - - // if the target is in the shroud, we can't do anything - if (isObjectShroudedForAction(obj, target, commandSource)) - return FALSE; - - switch( spTemplate->getSpecialPowerType() ) - { - case SPECIAL_CASH_BOUNTY: - return false; - - case SPECIAL_BATTLESHIP_BOMBARDMENT: - if( obj->getRelationship( target ) != ALLIES ) - { - return TRUE; - } - return FALSE; - - case SPECIAL_TANKHUNTER_TNT_ATTACK: - if( target->isKindOf( KINDOF_STRUCTURE ) || (target->isKindOf( KINDOF_VEHICLE ) && !target->isKindOf(KINDOF_AIRCRAFT)) ) - { - return true; - } - break; - - case SPECIAL_BOOBY_TRAP: - { - // We can booby trap any building that is allied or neutral - if( target->isKindOf(KINDOF_STRUCTURE) && (r == NEUTRAL || r == ALLIES) ) - { - return TRUE; - } - return FALSE; - } - - case SPECIAL_MISSILE_DEFENDER_LASER_GUIDED_MISSILES: - //Can only use laser guided missiles on vehicles! - if( target->isKindOf( KINDOF_VEHICLE ) && r == ENEMIES ) - { - return true; - } - break; - - case SPECIAL_HACKER_DISABLE_BUILDING: - //Can only disable buildings... - if( target->isKindOf( KINDOF_STRUCTURE ) && r == ENEMIES ) - { - //Make sure the building is considered hackable (temp: using capturable) - if( !target->isKindOf( KINDOF_CAPTURABLE ) || target->isKindOf( KINDOF_REBUILD_HOLE ) ) - { - return FALSE; - } - return true; - } - break; - - case SPECIAL_INFANTRY_CAPTURE_BUILDING: - case SPECIAL_BLACKLOTUS_CAPTURE_BUILDING: - return canCaptureBuilding( obj, target, commandSource ); - - case SPECIAL_BLACKLOTUS_DISABLE_VEHICLE_HACK: - return canDisableVehicleViaHacking( obj, target, commandSource, false ); - - case SPECIAL_BLACKLOTUS_STEAL_CASH_HACK: - return canStealCashViaHacking( obj, target, commandSource ); - - case SPECIAL_CASH_HACK: - //Can only disable enemy supply centers. - if( target->isKindOf( KINDOF_STRUCTURE ) && r == ENEMIES ) - { - //Make sure the building is considered hackable (temp: using capturable) - if( !target->isKindOf( KINDOF_CAPTURABLE ) || target->isKindOf( KINDOF_REBUILD_HOLE ) ) - { - return FALSE; - } - - //Can't cash hack a building that's under construction. - if( target->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) ) - { - return FALSE; - } - - if (target->isKindOf( KINDOF_CASH_GENERATOR ) ) - { - return true; - } - } - break; - - case SPECIAL_DISGUISE_AS_VEHICLE: - if( target->isKindOf( KINDOF_VEHICLE ) && - !target->isKindOf( KINDOF_AIRCRAFT ) && - !target->isKindOf( KINDOF_BOAT ) && - !target->isKindOf( KINDOF_CLIFF_JUMPER ) ) - { - //Don't allow it to disguise as another bomb truck -- that's just plain dumb. - //if( target->getTemplate() != obj->getTemplate() ) - { - //Don't allow it to disguise as a train -- they don't have KINDOF_TRAIN yet, but - //if added, please change this code so it'll be faster! - static const NameKeyType key = NAMEKEY( "RailroadBehavior" ); - RailroadBehavior *rBehavior = (RailroadBehavior*)target->findUpdateModule( key ); - if( !rBehavior ) - { - return true; - } - } - } - break; - - case SPECIAL_DEFECTOR: - //buildings do not defect - if( ! target->isKindOf( KINDOF_STRUCTURE ) ) - { - // only attacking type things will defect (no dozers, supply trucks, workers...) -// srj sez: I don't know why this is commented out, but it should remain thus, because -// it is not necessarily the case that dozers, workers, etc. cannot attack; they may -// "attack" Mines to disarm them... -// if ( target->isKindOf( KINDOF_CAN_ATTACK ) ) - { - //neutral or same-team units are worthless defectors - if( r == ENEMIES ) - { - return canMakeObjectDefector( obj, target, commandSource ); - } - } - } - break; - - //These special powers require locations, not objects! - case SPECIAL_DAISY_CUTTER: - case AIRF_SPECIAL_DAISY_CUTTER: - case SPECIAL_PARADROP_AMERICA: - case SPECIAL_TANK_PARADROP: - case INFA_SPECIAL_PARADROP_AMERICA: - case SPECIAL_CARPET_BOMB: - case SPECIAL_CHINA_CARPET_BOMB: - case SPECIAL_LEAFLET_DROP: - case EARLY_SPECIAL_LEAFLET_DROP: - case EARLY_SPECIAL_CHINA_CARPET_BOMB: - case AIRF_SPECIAL_CARPET_BOMB: - case SUPR_SPECIAL_CRUISE_MISSILE: - case SPECIAL_CLUSTER_MINES: - case NUKE_SPECIAL_CLUSTER_MINES: - case SPECIAL_EMP_PULSE: - case SPECIAL_CRATE_DROP: - case SPECIAL_NAPALM_STRIKE: - case SPECIAL_TERROR_CELL: - case SPECIAL_AMBUSH: - case SPECIAL_NEUTRON_MISSILE: - case NUKE_SPECIAL_NEUTRON_MISSILE: - case SUPW_SPECIAL_NEUTRON_MISSILE: - case SPECIAL_DETONATE_DIRTY_NUKE: - case SPECIAL_BLACK_MARKET_NUKE: - case SPECIAL_ANTHRAX_BOMB: - case SPECIAL_SPY_SATELLITE: - case SPECIAL_SPY_DRONE: - case SPECIAL_RADAR_VAN_SCAN: - case SPECIAL_SCUD_STORM: - case SPECIAL_A10_THUNDERBOLT_STRIKE: - case AIRF_SPECIAL_A10_THUNDERBOLT_STRIKE: - case SPECIAL_SPECTRE_GUNSHIP: - case AIRF_SPECIAL_SPECTRE_GUNSHIP: - case SPECIAL_ARTILLERY_BARRAGE: - case SPECIAL_FRENZY: - case EARLY_SPECIAL_FRENZY: - case SPECIAL_REPAIR_VEHICLES: - case EARLY_SPECIAL_REPAIR_VEHICLES: - case SPECIAL_GPS_SCRAMBLER: - case SLTH_SPECIAL_GPS_SCRAMBLER: - case SPECIAL_PARTICLE_UPLINK_CANNON: - case SPECIAL_CHANGE_BATTLE_PLANS: - case SPECIAL_CLEANUP_AREA: - case SPECIAL_LAUNCH_BAIKONUR_ROCKET: - case SPECIAL_SNEAK_ATTACK: - return false; - - case SPECIAL_REMOTE_CHARGES: - case SPECIAL_TIMED_CHARGES: - case SPECIAL_HELIX_NAPALM_BOMB: - { - if( target->isEffectivelyDead() || - target->isKindOf( KINDOF_BRIDGE ) || - target->isKindOf( KINDOF_BRIDGE_TOWER ) ) - return FALSE; - - if( target->isKindOf( KINDOF_STRUCTURE ) || target->isKindOf( KINDOF_VEHICLE ) ) - { - SpecialAbilityUpdate *spUpdate = obj->findSpecialAbilityUpdate( spTemplate->getSpecialPowerType() ); - if( spUpdate ) - { - //Make sure we have enough equipment to place an additional charge. - if( spUpdate->getSpecialObjectCount() < spUpdate->getSpecialObjectMax() ) - { - //Also restrict the unit from placing more than one charge on the same building. - //We accomplish this by having the stickybomb update store the target as the producer ID. - if( spUpdate->findSpecialObjectWithProducerID( target ) ) - { - return false; - } - - //HERE'S THE TOUGH CASE... - //We also don't want to allow a unit that can place timed charges on a building to be able to place - //remote charges (or vice-versa). So we're going to look for the other special ability update and - //reject if the other one has it planted... - if( spTemplate->getSpecialPowerType() == SPECIAL_REMOTE_CHARGES ) - { - spUpdate = obj->findSpecialAbilityUpdate( SPECIAL_TIMED_CHARGES ); - } - else if( spTemplate->getSpecialPowerType() == SPECIAL_TIMED_CHARGES ) - { - spUpdate = obj->findSpecialAbilityUpdate( SPECIAL_REMOTE_CHARGES ); - } - - //If we have a valid pointer at this point, we found the other special. Make sure it - //isn't planted on the same target. - if( spUpdate && spUpdate->findSpecialObjectWithProducerID( target ) ) - { - return false; - } - - return true; - } - } - } - break; - } - } - } - return false; -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -Bool ActionManager::canDoSpecialPower( const Object *obj, const SpecialPowerTemplate *spTemplate, CommandSourceType commandSource, UnsignedInt commandOptions, Bool checkSourceRequirements ) -{ - if (checkSourceRequirements) - { - //First check, if our object can do this special power. - if( !obj->hasSpecialPower( spTemplate->getSpecialPowerType() ) ) - { - return false; - } - } - - SpecialPowerModuleInterface *mod = obj->getSpecialPowerModule( spTemplate ); - if( mod ) - { - if (checkSourceRequirements) - { - if( mod->getPercentReady() < 1.0f ) - { - //Not fully ready - return false; - } - } - - switch( spTemplate->getSpecialPowerType() ) - { - case SPECIAL_MISSILE_DEFENDER_LASER_GUIDED_MISSILES: - case SPECIAL_TANKHUNTER_TNT_ATTACK: - case SPECIAL_BOOBY_TRAP: - case SPECIAL_DAISY_CUTTER: - case AIRF_SPECIAL_DAISY_CUTTER: - case SPECIAL_PARADROP_AMERICA: - case SPECIAL_TANK_PARADROP: - case INFA_SPECIAL_PARADROP_AMERICA: - case SPECIAL_CARPET_BOMB: - case SPECIAL_CHINA_CARPET_BOMB: - case SPECIAL_LEAFLET_DROP: - case EARLY_SPECIAL_LEAFLET_DROP: - case EARLY_SPECIAL_CHINA_CARPET_BOMB: - case AIRF_SPECIAL_CARPET_BOMB: - case SUPR_SPECIAL_CRUISE_MISSILE: - case SPECIAL_CLUSTER_MINES: - case NUKE_SPECIAL_CLUSTER_MINES: - case SPECIAL_NAPALM_STRIKE: - case SPECIAL_TERROR_CELL: - case SPECIAL_NEUTRON_MISSILE: - case NUKE_SPECIAL_NEUTRON_MISSILE: - case SUPW_SPECIAL_NEUTRON_MISSILE: - case SPECIAL_BLACK_MARKET_NUKE: - case SPECIAL_ANTHRAX_BOMB: - case SPECIAL_SPY_SATELLITE: - case SPECIAL_SPY_DRONE: - case SPECIAL_RADAR_VAN_SCAN: - case SPECIAL_TIMED_CHARGES: - case SPECIAL_SCUD_STORM: - case SPECIAL_A10_THUNDERBOLT_STRIKE: - case AIRF_SPECIAL_A10_THUNDERBOLT_STRIKE: - case SPECIAL_SPECTRE_GUNSHIP: - case AIRF_SPECIAL_SPECTRE_GUNSHIP: - case SPECIAL_ARTILLERY_BARRAGE: - case SPECIAL_FRENZY: - case EARLY_SPECIAL_FRENZY: - case SPECIAL_DISGUISE_AS_VEHICLE: - case SPECIAL_REPAIR_VEHICLES: - case EARLY_SPECIAL_REPAIR_VEHICLES: - case SPECIAL_GPS_SCRAMBLER: - case SLTH_SPECIAL_GPS_SCRAMBLER: - case SPECIAL_PARTICLE_UPLINK_CANNON: - case SPECIAL_CASH_BOUNTY: - case SPECIAL_CLEANUP_AREA: - case SPECIAL_HELIX_NAPALM_BOMB: - case SPECIAL_SNEAK_ATTACK: - case SPECIAL_EMP_PULSE: - case SPECIAL_CASH_HACK: - //These all require object or location targets. - return false; - - case SPECIAL_REMOTE_CHARGES: - case SPECIAL_CIA_INTELLIGENCE: - case SPECIAL_COMMUNICATIONS_DOWNLOAD: - case SPECIAL_DETONATE_DIRTY_NUKE: - case SPECIAL_CHANGE_BATTLE_PLANS: - case SPECIAL_LAUNCH_BAIKONUR_ROCKET: - //Detonate's any existing charges - return true; - } - } - return false; -} - -//------------------------------------------------------------------------------------------------ -Bool ActionManager::canFireWeaponAtLocation( const Object *obj, const Coord3D *loc, CommandSourceType commandSource, const WeaponSlotType slot, const Object *objectInWay ) -{ - //Sanity check - if( obj == nullptr || loc == nullptr ) - { - return false; - } - - //Make sure we have the right weapon. - Weapon *weapon = obj->getWeaponInWeaponSlot( slot ); - if( !weapon ) - { - return false; - } - - return true; -} - -//------------------------------------------------------------------------------------------------ -Bool ActionManager::canFireWeaponAtObject( const Object *obj, const Object *target, CommandSourceType commandSource, const WeaponSlotType slot ) -{ - //Sanity check - if( obj == nullptr || target == nullptr ) - { - return FALSE; - } - - //Make sure we have the right weapon. - Weapon *weapon = obj->getWeaponInWeaponSlot( slot ); - if( !weapon ) - { - return FALSE; - } - - Bool sniper = FALSE; - if( weapon->getDamageType() == DAMAGE_KILLPILOT ) - { - if( !canSnipeVehicle( obj, target, commandSource ) ) - { - return FALSE; - } - sniper = TRUE; - } - - CanAttackResult result; - if( sniper ) - result = obj->getAbleToAttackSpecificObject( ATTACK_NEW_TARGET, target, commandSource, slot ); - else - result = obj->getAbleToAttackSpecificObject( ATTACK_NEW_TARGET, target, commandSource ); - - if( result == ATTACKRESULT_POSSIBLE || result == ATTACKRESULT_POSSIBLE_AFTER_MOVING ) - { - return weapon->estimateWeaponDamage( obj, target ) != 0.0f; - } - return FALSE; -} - -//------------------------------------------------------------------------------------------------ -Bool ActionManager::canFireWeapon( const Object *obj, const WeaponSlotType slot, CommandSourceType commandSource ) -{ - //Sanity check - if( obj == nullptr ) - { - return false; - } - - //Make sure we have the right weapon. - Weapon *weapon = obj->getWeaponInWeaponSlot( slot ); - if( !weapon ) - { - return false; - } - - return true; - -} - -//------------------------------------------------------------------------------------------------ -Bool ActionManager::canGarrison( const Object *obj, const Object *target, CommandSourceType commandSource ) -{ - if (!(obj && target)) - return false; - - // The object was not an infantry, or is disallowed from being allowed to garrison stuff. - if (obj->isKindOf(KINDOF_INFANTRY) == false || obj->isKindOf(KINDOF_NO_GARRISON)) - return false; - - if (target->isKindOf(KINDOF_STRUCTURE) == false) - return false; - - ContainModuleInterface *objCMI = obj->getContain(); - if (!objCMI) - return false; - - ContainModuleInterface *cmi = target->getContain(); - if (cmi == nullptr) - return false; - - if (cmi->isGarrisonable() == false) - return false; - - if (obj->getControllingPlayer() == target->getControllingPlayer()) - { - return cmi->isValidContainerFor(obj, true); - } - - if (obj->getControllingPlayer()->getRelationship(target->getTeam()) == NEUTRAL) - { - // needs to be empty if its not already ours. - return (cmi->getContainCount() == 0 && cmi->isValidContainerFor(obj, true)); - } - - return false; -} - -//------------------------------------------------------------------------------------------------ -Bool ActionManager::canPlayerGarrison( const Player *player, const Object *target, CommandSourceType commandSource ) -{ - if (!(player && target)) - return false; - - if (target->isEffectivelyDead()) { - return false; - } - - if (target->isKindOf(KINDOF_STRUCTURE) == false) - return false; - - ContainModuleInterface *cmi = target->getContain(); - if (cmi == nullptr) - return false; - - if (cmi->isGarrisonable() == false) - return false; - - if (player == target->getControllingPlayer()) - { - return true; - } - - if (player->getRelationship(target->getTeam()) == NEUTRAL) - { - // needs to be empty if its not already ours. - return cmi->getContainCount() == 0; - } - - return false; -} - -//------------------------------------------------------------------------------------------------ -Bool ActionManager::canOverrideSpecialPowerDestination( const Object *obj, const Coord3D *loc, SpecialPowerType spType, CommandSourceType commandSource ) -{ - SpecialPowerUpdateInterface* spuInterface = obj->findSpecialPowerWithOverridableDestinationActive( spType ); - if( spuInterface ) - { - //But so long as it's not in the black areas of the map. - return ThePartitionManager->getShroudStatusForPlayer( obj->getControllingPlayer()->getPlayerIndex(), loc ) != CELLSHROUD_SHROUDED; - } - return false; -} diff --git a/Generals/Code/GameEngine/Source/Common/RTS/Energy.cpp b/Generals/Code/GameEngine/Source/Common/RTS/Energy.cpp deleted file mode 100644 index 32b5952aa4c..00000000000 --- a/Generals/Code/GameEngine/Source/Common/RTS/Energy.cpp +++ /dev/null @@ -1,313 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: Energy.cpp ///////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: RTS3 -// -// File name: Energy.cpp -// -// Created: Steven Johnson, October 2001 -// -// Desc: @todo -// -//----------------------------------------------------------------------------- - -#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine - -#include "Common/Energy.h" -#include "Common/Player.h" -#include "Common/PlayerList.h" -#include "Common/ThingTemplate.h" -#include "Common/Xfer.h" - -#include "GameLogic/GameLogic.h" -#include "GameLogic/Object.h" - - -//----------------------------------------------------------------------------- -Energy::Energy() -{ - m_energyProduction = 0; - m_energyConsumption = 0; - m_owner = nullptr; - m_powerSabotagedTillFrame = 0; -} - -//----------------------------------------------------------------------------- -Int Energy::getProduction() const -{ - if( TheGameLogic->getFrame() < m_powerSabotagedTillFrame ) - { - //Power sabotaged, therefore no power. - return 0; - } - return m_energyProduction; -} - -//----------------------------------------------------------------------------- -Real Energy::getEnergySupplyRatio() const -{ - DEBUG_ASSERTCRASH(m_energyProduction >= 0 && m_energyConsumption >= 0, ("neg Energy numbers")); - - if( TheGameLogic->getFrame() < m_powerSabotagedTillFrame ) - { - //Power sabotaged, therefore no power, no ratio. - return 0.0f; - } - - if (m_energyConsumption == 0) - return (Real)m_energyProduction; - - return (Real)m_energyProduction / (Real)m_energyConsumption; -} - -//------------------------------------------------------------------------------------------------- -Bool Energy::hasSufficientPower() const -{ - if( TheGameLogic->getFrame() < m_powerSabotagedTillFrame ) - { - //Power sabotaged, therefore no power. - return FALSE; - } - return m_energyProduction >= m_energyConsumption; -} - -//------------------------------------------------------------------------------------------------- -void Energy::adjustPower(Int powerDelta, Bool adding) -{ - if (powerDelta == 0) { - return; - } - - if (powerDelta > 0) { - if (adding) { - addProduction(powerDelta); - } else { - addProduction(-powerDelta); - } - } else { - // Seems a little odd, however, consumption is reversed. Negative power is positive consumption. - if (adding) { - addConsumption(-powerDelta); - } else { - addConsumption(powerDelta); - } - } -} - -//------------------------------------------------------------------------------------------------- -/** new 'obj' will now add/subtract from this energy construct */ -//------------------------------------------------------------------------------------------------- -void Energy::objectEnteringInfluence( Object *obj ) -{ - - // sanity - if( obj == nullptr ) - return; - - // get the amount of energy this object produces or consumes - Int energy = obj->getTemplate()->getEnergyProduction(); - - // adjust energy - if( energy < 0 ) - addConsumption( -energy ); - else if( energy > 0 ) - addProduction( energy ); - - // sanity - DEBUG_ASSERTCRASH( m_energyProduction >= 0 && m_energyConsumption >= 0, - ("Energy - Negative Energy numbers, Produce=%d Consume=%d\n", - m_energyProduction, m_energyConsumption) ); - -} - -//------------------------------------------------------------------------------------------------- -/** 'obj' will now no longer add/subtrack from this energy construct */ -//------------------------------------------------------------------------------------------------- -void Energy::objectLeavingInfluence( Object *obj ) -{ - - // sanity - if( obj == nullptr ) - return; - - // get the amount of energy this object produces or consumes - Int energy = obj->getTemplate()->getEnergyProduction(); - - // adjust energy - if( energy < 0 ) - addConsumption( energy ); - else if( energy > 0 ) - addProduction( -energy ); - - // sanity - DEBUG_ASSERTCRASH( m_energyProduction >= 0 && m_energyConsumption >= 0, - ("Energy - Negative Energy numbers, Produce=%d Consume=%d\n", - m_energyProduction, m_energyConsumption) ); - -} - -//------------------------------------------------------------------------------------------------- -/** Adds an energy bonus to the player's pool of energy when the "Control Rods" upgrade - is made to the American Cold Fusion Plant */ -//------------------------------------------------------------------------------------------------- -void Energy::addPowerBonus( Object *obj ) -{ - - // sanity - if( obj == nullptr ) - return; - - DEBUG_ASSERTCRASH(!obj->isDisabled(), ("power bonus should not be added to disabled power plant")); - - addProduction(obj->getTemplate()->getEnergyBonus()); - - // sanity - DEBUG_ASSERTCRASH( m_energyProduction >= 0 && m_energyConsumption >= 0, - ("Energy - Negative Energy numbers, Produce=%d Consume=%d\n", - m_energyProduction, m_energyConsumption) ); - -} - -// ------------------------------------------------------------------------------------------------ -/** Removed an energy bonus */ -// ------------------------------------------------------------------------------------------------ -void Energy::removePowerBonus( Object *obj ) -{ - - // sanity - if( obj == nullptr ) - return; - - // TheSuperHackers @bugfix Caball009 14/11/2025 Don't remove power bonus for disabled power plants. -#if !RETAIL_COMPATIBLE_CRC - if ( obj->isDisabled() ) - return; -#endif - - addProduction( -obj->getTemplate()->getEnergyBonus() ); - - // sanity - DEBUG_ASSERTCRASH( m_energyProduction >= 0 && m_energyConsumption >= 0, - ("Energy - Negative Energy numbers, Produce=%d Consume=%d\n", - m_energyProduction, m_energyConsumption) ); - -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -// Private functions -// ------------------------------------------------------------------------------------------------ -void Energy::addProduction(Int amt) -{ - m_energyProduction += amt; - - if( m_owner == nullptr ) - return; - - // A repeated Brownout signal does nothing bad, and we need to handle more than just edge cases. - // Like low power, now even more low power, refresh disable. - m_owner->onPowerBrownOutChange( !hasSufficientPower() ); -} - -// ------------------------------------------------------------------------------------------------ -void Energy::addConsumption(Int amt) -{ - m_energyConsumption += amt; - - if( m_owner == nullptr ) - return; - - m_owner->onPowerBrownOutChange( !hasSufficientPower() ); -} - -// ------------------------------------------------------------------------------------------------ -/** CRC */ -// ------------------------------------------------------------------------------------------------ -void Energy::crc( Xfer *xfer ) -{ - -} - -// ------------------------------------------------------------------------------------------------ -/** Xfer method - * Version Info: - * 1: Initial version - * 2: Stop saving production and consumption - * 3: Added m_powerSabotagedTillFrame (Added in Zero Hour) */ -// ------------------------------------------------------------------------------------------------ -void Energy::xfer( Xfer *xfer ) -{ - - // version -#if RTS_GENERALS && RETAIL_COMPATIBLE_XFER_SAVE - XferVersion currentVersion = 2; -#else - XferVersion currentVersion = 3; -#endif - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - // It is actually incorrect to save these, as they are reconstructed when the buildings are loaded - // I need to version though so old games will load wrong rather than crashing - - // production - if( version < 2 ) - xfer->xferInt( &m_energyProduction ); - - // consumption - if( version < 2 ) - xfer->xferInt( &m_energyConsumption ); - - // owning player index - Int owningPlayerIndex; - if( xfer->getXferMode() == XFER_SAVE ) - owningPlayerIndex = m_owner->getPlayerIndex(); - xfer->xferInt( &owningPlayerIndex ); - m_owner = ThePlayerList->getNthPlayer( owningPlayerIndex ); - - //Sabotage - if( version >= 3 ) - { - xfer->xferUnsignedInt( &m_powerSabotagedTillFrame ); - } - -} - -// ------------------------------------------------------------------------------------------------ -/** Load post process */ -// ------------------------------------------------------------------------------------------------ -void Energy::loadPostProcess() -{ - -} diff --git a/Generals/Code/GameEngine/Source/Common/RTS/Handicap.cpp b/Generals/Code/GameEngine/Source/Common/RTS/Handicap.cpp deleted file mode 100644 index a9eda01d4ac..00000000000 --- a/Generals/Code/GameEngine/Source/Common/RTS/Handicap.cpp +++ /dev/null @@ -1,128 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: Handicap.cpp ///////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: RTS3 -// -// File name: Handicap.cpp -// -// Created: Steven Johnson, October 2001 -// -// Desc: @todo -// -//----------------------------------------------------------------------------- - -#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine - -#include "Common/Handicap.h" -#include "Common/Player.h" -#include "Common/Dict.h" -#include "Common/ThingTemplate.h" - -//----------------------------------------------------------------------------- -Handicap::Handicap() -{ - init(); -} - -//----------------------------------------------------------------------------- -void Handicap::init() -{ - for (Int i = 0; i < HANDICAP_TYPE_COUNT; ++i) - for (Int j = 0; j < THING_TYPE_COUNT; ++j) - m_handicaps[i][j] = 1.0f; -} - -//----------------------------------------------------------------------------- -void Handicap::readFromDict(const Dict* d) -{ - // this isn't very efficient, but is only called at load times, - // so it probably doesn't really matter. - - const char* htNames[] = - { - "BUILDCOST", - "BUILDTIME", -// "FIREPOWER", -// "ARMOR", -// "GROUNDSPEED", -// "AIRSPEED", -// "INCOME" - }; - static_assert(ARRAY_SIZE(htNames) == HANDICAP_TYPE_COUNT, "Incorrect array size"); - - const char* ttNames[] = - { - "GENERIC", - "BUILDINGS", - }; - static_assert(ARRAY_SIZE(ttNames) == THING_TYPE_COUNT, "Incorrect array size"); - -// no, you should NOT call init() here. -//init(); - - AsciiString c; - for (Int i = 0; i < HANDICAP_TYPE_COUNT; ++i) - { - for (Int j = 0; j < THING_TYPE_COUNT; ++j) - { - c.clear(); - c.set("HANDICAP_"); - c.concat(htNames[i]); - c.concat("_"); - c.concat(ttNames[j]); - NameKeyType k = TheNameKeyGenerator->nameToKey(c); - Bool exists; - Real r = d->getReal(k, &exists); - if (exists) - m_handicaps[i][j] = r; - } - } -} - -//----------------------------------------------------------------------------- -/*static*/ Handicap::ThingType Handicap::getBestThingType(const ThingTemplate *tmpl) -{ - /// if this ends up being too slow, cache the information in the object - if (tmpl->isKindOf(KINDOF_STRUCTURE)) - return BUILDINGS; - - return GENERIC; -} - -//----------------------------------------------------------------------------- -Real Handicap::getHandicap(HandicapType ht, const ThingTemplate *tmpl) const -{ - ThingType tt = getBestThingType(tmpl); - return m_handicaps[ht][tt]; -} diff --git a/Generals/Code/GameEngine/Source/Common/RTS/MissionStats.cpp b/Generals/Code/GameEngine/Source/Common/RTS/MissionStats.cpp deleted file mode 100644 index 16047cfefd2..00000000000 --- a/Generals/Code/GameEngine/Source/Common/RTS/MissionStats.cpp +++ /dev/null @@ -1,113 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: MissionStats.cpp ///////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: RTS3 -// -// File name: MissionStats.cpp -// -// Created: Steven Johnson, October 2001 -// -// Desc: @todo -// -//----------------------------------------------------------------------------- - -#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine - -#include "Common/MissionStats.h" -#include "Common/Player.h" -#include "Common/Xfer.h" - -//----------------------------------------------------------------------------- -MissionStats::MissionStats() -{ - init(); -} - -//----------------------------------------------------------------------------- -void MissionStats::init() -{ - Int i; - - for (i = 0; i < MAX_PLAYER_COUNT; ++i) - { - m_unitsKilled[i] = 0; - m_buildingsKilled[i] = 0; - } - m_unitsLost = 0; - m_buildingsLost = 0; - //m_whoLastHurtMe = PLAYER_NONE; -} - -// ------------------------------------------------------------------------------------------------ -/** CRC */ -// ------------------------------------------------------------------------------------------------ -void MissionStats::crc( Xfer *xfer ) -{ - -} - -// ------------------------------------------------------------------------------------------------ -/** Xfer method - * Version Info; - * 1: Initial version */ -// ------------------------------------------------------------------------------------------------ -void MissionStats::xfer( Xfer *xfer ) -{ - - // version - XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - // units killed - xfer->xferUser( m_unitsKilled, sizeof( Int ) * MAX_PLAYER_COUNT ); - - // units lost - xfer->xferInt( &m_unitsLost ); - - // buildings killed - xfer->xferUser( m_buildingsKilled, sizeof( Int ) * MAX_PLAYER_COUNT ); - - // buildings lost - xfer->xferInt( &m_buildingsLost ); - -} - -// ------------------------------------------------------------------------------------------------ -/** Load post process */ -// ------------------------------------------------------------------------------------------------ -void MissionStats::loadPostProcess() -{ - -} diff --git a/Generals/Code/GameEngine/Source/Common/RTS/Money.cpp b/Generals/Code/GameEngine/Source/Common/RTS/Money.cpp deleted file mode 100644 index d321f3193f4..00000000000 --- a/Generals/Code/GameEngine/Source/Common/RTS/Money.cpp +++ /dev/null @@ -1,214 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: Money.cpp ///////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: RTS3 -// -// File name: Money.cpp -// -// Created: Steven Johnson, October 2001 -// -// Desc: @todo -// -//----------------------------------------------------------------------------- - -#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine -#include "Common/Money.h" - -#include "Common/AudioSettings.h" -#include "Common/GameAudio.h" -#include "Common/MiscAudio.h" -#include "Common/Player.h" -#include "Common/PlayerList.h" -#include "Common/Xfer.h" -#include "GameLogic/GameLogic.h" - -// ------------------------------------------------------------------------------------------------ -UnsignedInt Money::withdraw(UnsignedInt amountToWithdraw, Bool playSound) -{ -#if defined(RTS_DEBUG) - Player* player = ThePlayerList->getNthPlayer(m_playerIndex); - if (player != nullptr && player->buildsForFree()) - return 0; -#endif - - if (amountToWithdraw > m_money) - amountToWithdraw = m_money; - - if (amountToWithdraw == 0) - return amountToWithdraw; - - if (playSound) - { - triggerAudioEvent(TheAudio->getMiscAudio()->m_moneyWithdrawSound); - } - - m_money -= amountToWithdraw; - - return amountToWithdraw; -} - -// ------------------------------------------------------------------------------------------------ -void Money::deposit(UnsignedInt amountToDeposit, Bool playSound, Bool trackIncome) -{ - if (amountToDeposit == 0) - return; - - if (playSound) - { - triggerAudioEvent(TheAudio->getMiscAudio()->m_moneyDepositSound); - } - - if (trackIncome) - { - m_incomeBuckets[m_currentBucket] += amountToDeposit; - m_cashPerMinute += amountToDeposit; - } - - m_money += amountToDeposit; - - if( amountToDeposit > 0 ) - { - Player *player = ThePlayerList->getNthPlayer( m_playerIndex ); - if( player ) - { - player->getAcademyStats()->recordIncome(); - } - } -} - -// ------------------------------------------------------------------------------------------------ -void Money::setStartingCash(UnsignedInt amount) -{ - m_money = amount; - std::fill(m_incomeBuckets, m_incomeBuckets + ARRAY_SIZE(m_incomeBuckets), 0u); - m_currentBucket = 0u; - m_cashPerMinute = 0u; -} - -// ------------------------------------------------------------------------------------------------ -void Money::updateIncomeBucket() -{ - UnsignedInt frame = TheGameLogic->getFrame(); - UnsignedInt nextBucket = (frame / LOGICFRAMES_PER_SECOND) % ARRAY_SIZE(m_incomeBuckets); - if (nextBucket != m_currentBucket) - { - m_cashPerMinute -= m_incomeBuckets[nextBucket]; - m_currentBucket = nextBucket; - m_incomeBuckets[m_currentBucket] = 0u; - } -} - -// ------------------------------------------------------------------------------------------------ -UnsignedInt Money::getCashPerMinute() const -{ - return m_cashPerMinute; -} - -void Money::triggerAudioEvent(const AudioEventRTS& audioEvent) -{ - Real volume = TheAudio->getAudioSettings()->m_preferredMoneyTransactionVolume; - volume *= audioEvent.getVolume(); - if (volume <= 0.0f) - return; - - //@todo: Do we do this frequently enough that it is a performance hit? - AudioEventRTS event = audioEvent; - event.setPlayerIndex(m_playerIndex); - event.setVolume(volume); - TheAudio->addAudioEvent(&event); -} - -// ------------------------------------------------------------------------------------------------ -/** CRC */ -// ------------------------------------------------------------------------------------------------ -void Money::crc( Xfer *xfer ) -{ - -} - -// ------------------------------------------------------------------------------------------------ -/** Xfer method - * Version Info: - * 1: Initial version - * 2: TheSuperHackers @tweak Serialize income tracking - */ -// ------------------------------------------------------------------------------------------------ -void Money::xfer( Xfer *xfer ) -{ - - // version -#if RETAIL_COMPATIBLE_XFER_SAVE - XferVersion currentVersion = 1; -#else - XferVersion currentVersion = 2; -#endif - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - // money value - xfer->xferUnsignedInt( &m_money ); - - if (version <= 1) - { - setStartingCash(m_money); - } - else - { - xfer->xferUser(m_incomeBuckets, sizeof(m_incomeBuckets)); - xfer->xferUnsignedInt(&m_currentBucket); - - m_cashPerMinute = std::accumulate(m_incomeBuckets, m_incomeBuckets + ARRAY_SIZE(m_incomeBuckets), 0u); - } -} - -// ------------------------------------------------------------------------------------------------ -/** Load post process */ -// ------------------------------------------------------------------------------------------------ -void Money::loadPostProcess() -{ - -} - - -// ------------------------------------------------------------------------------------------------ -/** Parse a money amount for the ini file. E.g. DefaultStartingMoney = 10000 */ -// ------------------------------------------------------------------------------------------------ -void Money::parseMoneyAmount( INI *ini, void *instance, void *store, const void* userData ) -{ - // Someday, maybe, have multiple fields like Gold:10000 Wood:1000 Tiberian:10 - Money * money = (Money *)store; - UnsignedInt moneyAmount; - INI::parseUnsignedInt( ini, instance, &moneyAmount, userData ); - money->setStartingCash(moneyAmount); -} diff --git a/Generals/Code/GameEngine/Source/Common/RTS/Player.cpp b/Generals/Code/GameEngine/Source/Common/RTS/Player.cpp deleted file mode 100644 index 58c1fc52a1f..00000000000 --- a/Generals/Code/GameEngine/Source/Common/RTS/Player.cpp +++ /dev/null @@ -1,4707 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: Player.cpp ///////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: RTS3 -// -// File name: Player.cpp -// -// Created: Steven Johnson, October 2001 -// -// Desc: @todo -// -//----------------------------------------------------------------------------- - -#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine - -#define DEFINE_SCIENCE_AVAILABILITY_NAMES - -#include "Common/ActionManager.h" -#include "Common/BuildAssistant.h" -#include "Common/CRCDebug.h" -#include "Common/DisabledTypes.h" -#include "Common/GameState.h" -#include "Common/GlobalData.h" -#include "Common/MessageStream.h" -#include "Common/MiscAudio.h" -#include "Common/PerfTimer.h" -#include "Common/Player.h" -#include "Common/PlayerList.h" -#include "Common/PlayerTemplate.h" -#include "Common/ProductionPrerequisite.h" -#include "Common/Radar.h" -#include "Common/ResourceGatheringManager.h" -#include "Common/Team.h" -#include "Common/ThingFactory.h" -#include "Common/ThingTemplate.h" -#include "Common/TunnelTracker.h" -#include "Common/Upgrade.h" -#include "Common/WellKnownKeys.h" -#include "Common/Xfer.h" -#include "Common/BitFlagsIO.h" -#include "Common/SpecialPower.h" - -#include "GameClient/ControlBar.h" -#include "GameClient/Drawable.h" -#include "GameClient/Eva.h" -#include "GameClient/GameClient.h" -#include "GameClient/GameText.h" - -#include "GameLogic/AI.h" -#include "GameLogic/AIPathfind.h" -#include "GameLogic/AISkirmishPlayer.h" -#include "GameLogic/ExperienceTracker.h" -#include "GameLogic/Object.h" -#include "GameLogic/Scripts.h" -#include "GameLogic/PartitionManager.h" -#include "GameLogic/SidesList.h" -#include "GameLogic/Squad.h" -#include "GameLogic/RankInfo.h" -#include "GameLogic/ScriptEngine.h" -#include "GameLogic/Weapon.h" -#include "GameLogic/Module/AIUpdate.h" -#include "GameLogic/Module/ContainModule.h" -#include "GameLogic/Module/AutoDepositUpdate.h" -#include "GameLogic/Module/StealthUpdate.h" -#include "GameLogic/Module/SpecialPowerModule.h" -#include "GameLogic/Module/SupplyTruckAIUpdate.h" -#include "GameLogic/Module/BattlePlanUpdate.h" -#include "GameLogic/Module/ProductionUpdate.h" -#include "GameLogic/VictoryConditions.h" - -#include "GameNetwork/GameInfo.h" - - -//Grey for neutral. -#define NEUTRAL_PLAYER_COLOR 0xffffffff - -// ------------------------------------------------------------------------------------------------ -class ClosestKindOfData -{ -public: - - ClosestKindOfData(); - - //In - KindOfMaskType m_setKindOf; - KindOfMaskType m_clearKindOf; - Object *m_source; - - //Out - Object *m_closest; - Real m_closestDistSq; - -}; - -// ------------------------------------------------------------------------------------------------ -ClosestKindOfData::ClosestKindOfData() -{ - m_setKindOf.clear(); - m_clearKindOf.clear(); - m_source = nullptr; - m_closest = nullptr; - m_closestDistSq = FLT_MAX; -} - -// ------------------------------------------------------------------------------------------------ -static void findClosestKindOf( Object *obj, void *userData ) -{ - ClosestKindOfData *closestData = (ClosestKindOfData *)userData; - - if( ! obj->isKindOfMulti( closestData->m_setKindOf, closestData->m_clearKindOf ) ) - return; // Do nothing to the magic running total pointer man. - - // is this the closest one so far - Real distSq = ThePartitionManager->getDistanceSquared( closestData->m_source, obj, FROM_CENTER_2D ); - if( distSq < closestData->m_closestDistSq ) - { - closestData->m_closest = obj; - closestData->m_closestDistSq = distSq; - } -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////////////////////////// - -#ifdef DEBUG_CRC -#define CRCDUMPBATTLEPLANBONUSES(x,y,z) dumpBattlePlanBonuses(x, #x, y, z, __FILE__, __LINE__, FALSE) -#define DUMPBATTLEPLANBONUSES(x,y,z) dumpBattlePlanBonuses(x, #x, y, z, __FILE__, __LINE__, TRUE) -AsciiString kindofMaskAsAsciiString(KindOfMaskType m) -{ - AsciiString s; - const char* const* kindofNames = KindOfMaskType::getBitNames(); - for (Int i=KINDOF_FIRST; igetPlayerIndex():-1, (p)?((Player *)p)->getPlayerDisplayName().str():L"", (o)?o->getID():-1, (o)?o->getTemplate()->getName().str():"", - b->m_armorScalar, AS_INT(b->m_armorScalar), - b->m_bombardment, b->m_holdTheLine, b->m_searchAndDestroy, - b->m_sightRangeScalar, AS_INT(b->m_sightRangeScalar), - kindofMaskAsAsciiString(b->m_validKindOf).str(), - kindofMaskAsAsciiString(b->m_invalidKindOf).str())); - if (!doDebugLog) - return; - DEBUG_LOG(("dumpBattlePlanBonuses() %s:%d %s\n Player %d(%ls) object %d(%s) armor:%g/%8.8X bombardment:%d, holdTheLine:%d, searchAndDestroy:%d sight:%g/%8.8X, valid:%s invalid:%s", - fname.str(), line, name.str(), - (p)?p->getPlayerIndex():-1, (p)?((Player *)p)->getPlayerDisplayName().str():L"", (o)?o->getID():-1, (o)?o->getTemplate()->getName().str():"", - b->m_armorScalar, AS_INT(b->m_armorScalar), - b->m_bombardment, b->m_holdTheLine, b->m_searchAndDestroy, - b->m_sightRangeScalar, AS_INT(b->m_sightRangeScalar), - kindofMaskAsAsciiString(b->m_validKindOf).str(), - kindofMaskAsAsciiString(b->m_invalidKindOf).str())); -} -#else -#define DUMPBATTLEPLANBONUSES(x,y,z) -#define CRCDUMPBATTLEPLANBONUSES(x,y,z) -#endif // DEBUG_CRC - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -PlayerRelationMap::PlayerRelationMap() -{ - -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -PlayerRelationMap::~PlayerRelationMap() -{ - - // make sure the data is cleared - m_map.clear(); - -} - -// ------------------------------------------------------------------------------------------------ -/** CRC */ -// ------------------------------------------------------------------------------------------------ -void PlayerRelationMap::crc( Xfer *xfer ) -{ - -} - -// ------------------------------------------------------------------------------------------------ -/** Xfer method - * Version Info: - * 1: Initial version - */ -// ------------------------------------------------------------------------------------------------ -void PlayerRelationMap::xfer( Xfer *xfer ) -{ - - // version - XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - // player relation count - PlayerRelationMapType::iterator playerRelationIt; - UnsignedShort playerRelationCount = m_map.size(); - xfer->xferUnsignedShort( &playerRelationCount ); - - // player relations - Int playerIndex; - Relationship r; - if( xfer->getXferMode() == XFER_SAVE ) - { - - // go through all player relations - for( playerRelationIt = m_map.begin(); playerRelationIt != m_map.end(); ++playerRelationIt ) - { - - // write player index - playerIndex = (*playerRelationIt).first; - xfer->xferInt( &playerIndex ); - - // write relationship - r = (*playerRelationIt).second; - xfer->xferUser( &r, sizeof( Relationship ) ); - - } - - } - else - { - - for( UnsignedShort i = 0; i < playerRelationCount; ++i ) - { - - // read player index - xfer->xferInt( &playerIndex ); - - // read relationship - xfer->xferUser( &r, sizeof( Relationship ) ); - - // assign relationship - m_map[ playerIndex ] = r; - - } - - } - -} - -// ------------------------------------------------------------------------------------------------ -/** Load post process */ -// ------------------------------------------------------------------------------------------------ -void PlayerRelationMap::loadPostProcess() -{ - -} - -//============================================================================= -Player::Player( Int playerIndex ) -{ - m_isPreorder = FALSE; - m_isPlayerDead = FALSE; - - m_playerIndex = playerIndex; - - // allocate new relation map pools - m_playerRelations = newInstance(PlayerRelationMap); - m_teamRelations = newInstance(TeamRelationMap); - - m_upgradeList = nullptr; - m_pBuildList = nullptr; - m_ai = nullptr; - m_resourceGatheringManager = nullptr; - m_defaultTeam = nullptr; - m_radarCount = 0; - m_disableProofRadarCount = 0; - m_radarDisabled = FALSE; - m_bombardBattlePlans = 0; - m_holdTheLineBattlePlans = 0; - m_searchAndDestroyBattlePlans = 0; - m_tunnelSystem = nullptr; - m_playerTemplate = nullptr; -#if RTS_GENERALS - m_visionSpiedMask = PLAYERMASK_NONE; -#endif - m_battlePlanBonuses = nullptr; - m_skillPointsModifier = 1.0f; - m_canBuildUnits = TRUE; - m_canBuildBase = TRUE; - m_cashBountyPercent = 0.0f; - m_color = 0; - m_currentSelection = nullptr; - m_rankLevel = 0; - m_sciencePurchasePoints = 0; - m_side = nullptr; - m_baseSide = nullptr; - m_skillPoints = 0; - Int i; - m_upgradeList = nullptr; - for(i = 0; i < NUM_HOTKEY_SQUADS; i++) - { - m_squads[i] = nullptr; - } - for (i = 0; i < MAX_PLAYER_COUNT; ++i) - { - m_attackedBy[i] = false; -#if RTS_GENERALS - m_visionSpiedBy[i] = 0; -#endif - } - m_attackedFrame = 0; - - m_unitsShouldHunt = FALSE; - init( nullptr ); - -} - -//============================================================================= -void Player::init(const PlayerTemplate* pt) -{ - - DEBUG_ASSERTCRASH(m_playerTeamPrototypes.empty(), ("Player::m_playerTeamPrototypes is not empty at game start!")); - m_skillPointsModifier = 1.0f; - m_attackedFrame = 0; - - m_isPreorder = FALSE; - m_isPlayerDead = FALSE; - - m_radarCount = 0; - m_disableProofRadarCount = 0; - m_radarDisabled = FALSE; - - m_bombardBattlePlans = 0; - m_holdTheLineBattlePlans = 0; - m_searchAndDestroyBattlePlans = 0; - - deleteInstance(m_battlePlanBonuses); - m_battlePlanBonuses = nullptr; - - deleteUpgradeList(); - - m_energy.init(this); - m_stats.init(); - - deleteInstance(m_pBuildList); - m_pBuildList = nullptr; - - m_defaultTeam = nullptr; - - deleteInstance(m_ai); - m_ai = nullptr; - - deleteInstance(m_resourceGatheringManager); - m_resourceGatheringManager = nullptr; - - for (Int i = 0; i < NUM_HOTKEY_SQUADS; ++i) { - deleteInstance(m_squads[i]); - m_squads[i] = newInstance(Squad); - } - - deleteInstance(m_currentSelection); - m_currentSelection = newInstance(Squad); - - deleteInstance(m_tunnelSystem); - m_tunnelSystem = nullptr; - - m_canBuildBase = true; - m_canBuildUnits = true; - m_observer = false; - m_cashBountyPercent = 0.0f; - m_listInScoreScreen = TRUE; - - m_unitsShouldHunt = FALSE; - -#if defined(RTS_DEBUG) - m_DEMO_ignorePrereqs = FALSE; - m_DEMO_freeBuild = FALSE; -#endif - -#if defined(RTS_DEBUG) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) - m_DEMO_instantBuild = FALSE; -#endif - - if (pt) - { - m_side = pt->getSide(); - m_baseSide = pt->getBaseSide(); - m_productionCostChanges = pt->getProductionCostChanges(); - m_productionTimeChanges = pt->getProductionTimeChanges(); - m_productionVeterancyLevels = pt->getProductionVeterancyLevels(); - m_color = pt->getPreferredColor()->getAsInt() | 0xff000000; - m_nightColor = m_color; - - m_money = *pt->getMoney(); - m_money.setPlayerIndex(getPlayerIndex()); - - m_handicap = *pt->getHandicap(); - - if( m_money.countMoney() == 0 ) - { - // TheSuperHackers @bugfix Now correctly deposits the money and fixes its audio and academy issues. - // Note that copying the entire Money class instead would also copy the player index inside of it. - if ( TheGameInfo ) - { - m_money.deposit( TheGameInfo->getStartingCash().countMoney(), FALSE, FALSE ); - } - else - { - m_money.deposit( TheGlobalData->m_defaultStartingCash.countMoney(), FALSE, FALSE ); - } - } - - m_playerDisplayName.clear(); - m_playerName.clear(); - m_playerNameKey = NAMEKEY_INVALID; - m_playerType = PLAYER_COMPUTER; - m_observer = pt->isObserver(); - m_isPlayerDead = m_observer; // observers are dead - - } - else - { - // no player template? must be the neutral player! - m_side = ""; - m_baseSide = ""; - m_productionCostChanges.clear(); - m_productionTimeChanges.clear(); - m_productionVeterancyLevels.clear(); - m_color = NEUTRAL_PLAYER_COLOR; - m_nightColor = NEUTRAL_PLAYER_COLOR; - m_money.init(); - m_handicap.init(); - - m_playerDisplayName = UnicodeString::TheEmptyString; - m_playerName = AsciiString::TheEmptyString; - m_playerNameKey = NAMEKEY(AsciiString::TheEmptyString); - m_playerType = PLAYER_COMPUTER; - - // neutral is always "allied" with self -- this is the only thing ever allied with neutral! - setPlayerRelationship(this, ALLIES); - - } - // reset each player - m_scoreKeeper.reset(m_playerIndex); - m_playerTemplate = pt; - - // reset rank info - resetRank(); - m_sciencesDisabled.clear(); - m_sciencesHidden.clear(); - m_specialPowerReadyTimerList.clear(); - - KindOfPercentProductionChangeListIt it = m_kindOfPercentProductionChangeList.begin(); - while(it != m_kindOfPercentProductionChangeList.end()) - { - KindOfPercentProductionChange *tof = *it; - it = m_kindOfPercentProductionChangeList.erase( it ); - deleteInstance(tof); - } - - getAcademyStats()->init( this ); - - //Always off at the beginning of a game! Only GameLogic::update has - //the power to turn it on. Don't want to cause desyncs! - m_logicalRetaliationModeEnabled = FALSE; -} - -//============================================================================= -Player::~Player() -{ - m_defaultTeam = nullptr; - m_playerTemplate = nullptr; - - for( PlayerTeamList::iterator it = m_playerTeamPrototypes.begin(); - it != m_playerTeamPrototypes.end(); ++it) - { - (*it)->friend_setOwningPlayer(nullptr); - } - m_playerTeamPrototypes.clear(); // empty, but don't free the contents - - // delete the relation maps (the destructor clears the actual map if any data is present) - deleteInstance(m_teamRelations); - m_teamRelations = nullptr; - - deleteInstance(m_playerRelations); - m_playerRelations = nullptr; - - for (Int i = 0; i < NUM_HOTKEY_SQUADS; ++i) { - deleteInstance(m_squads[i]); - m_squads[i] = nullptr; - } - - deleteInstance(m_currentSelection); - m_currentSelection = nullptr; - - deleteInstance(m_battlePlanBonuses); - m_battlePlanBonuses = nullptr; -} - -//============================================================================= -//DECLARE_PERF_TIMER(Player_getRelationship) -Relationship Player::getRelationship(const Team *that) const -{ - //USE_PERF_TIMER(Player_getRelationship) - if (that) - { - // do we have an override for that particular team? if so, return it. - if (!m_teamRelations->m_map.empty()) - { - TeamRelationMapType::const_iterator it = m_teamRelations->m_map.find(that->getID()); - if (it != m_teamRelations->m_map.end()) - { - return (*it).second; - } - } - - // hummm... well, do we have something for that team's player? - if (!m_playerRelations->m_map.empty()) - { - const Player* thatPlayer = that->getControllingPlayer(); - if (thatPlayer != nullptr) - { - PlayerRelationMapType::const_iterator it = m_playerRelations->m_map.find(thatPlayer->getPlayerIndex()); - if (it != m_playerRelations->m_map.end()) - { - return (*it).second; - } - } - } - } - return NEUTRAL; -} - -//============================================================================= -void Player::setPlayerRelationship(const Player *that, Relationship r) -{ - if (that != nullptr) - { - // note that this creates the entry if it doesn't exist. - m_playerRelations->m_map[that->getPlayerIndex()] = r; - } -} - -// ------------------------------------------------------------------------ -Bool Player::removePlayerRelationship(const Player *that) -{ - if (!m_playerRelations->m_map.empty()) - { - if (that == nullptr) - { - m_playerRelations->m_map.clear(); - return true; - } - else - { - PlayerRelationMapType::iterator it = m_playerRelations->m_map.find(that->getPlayerIndex()); - if (it != m_playerRelations->m_map.end()) - { - m_playerRelations->m_map.erase(it); - return true; - } - } - } - return false; -} - -//============================================================================= -void Player::setTeamRelationship(const Team *that, Relationship r) -{ - if (that != nullptr) - { - // note that this creates the entry if it doesn't exist. - m_teamRelations->m_map[that->getID()] = r; - } -} - -// ------------------------------------------------------------------------ -Bool Player::removeTeamRelationship(const Team *that) -{ - if (!m_teamRelations->m_map.empty()) - { - if (that == nullptr) - { - m_teamRelations->m_map.clear(); - return true; - } - else - { - TeamRelationMapType::iterator it = m_teamRelations->m_map.find(that->getID()); - if (it != m_teamRelations->m_map.end()) - { - m_teamRelations->m_map.erase(it); - return true; - } - } - } - return false; -} - -//============================================================================= -void Player::setBuildList(BuildListInfo *pBuildList) -{ - - deleteInstance(m_pBuildList); - m_pBuildList = pBuildList; - -} - -//============================================================================= -void Player::addToBuildList(Object *obj) -{ - BuildListInfo *newInfo = newInstance( BuildListInfo ); - newInfo->setObjectID(obj->getID()); - newInfo->setTemplateName(obj->getTemplate()->getName()); - newInfo->setLocation(*obj->getPosition()); - newInfo->setAngle(obj->getOrientation()); - newInfo->setNumRebuilds(0); // Can't rebuild. - newInfo->setNextBuildList(m_pBuildList); - m_pBuildList = newInfo; -} - -//============================================================================= -void Player::addToPriorityBuildList(AsciiString templateName, Coord3D *pos, Real angle) -{ - BuildListInfo *newInfo = newInstance( BuildListInfo ); - newInfo->setTemplateName(templateName); - newInfo->setLocation(*pos); - newInfo->setAngle(angle); - newInfo->markPriorityBuild(); - newInfo->setNumRebuilds(1); // Build once. - newInfo->setNextBuildList(m_pBuildList); - m_pBuildList = newInfo; -} - -//============================================================================= -void Player::update() -{ - if (m_ai) - m_ai->update(); - - // Allow the teams this player owns to update themselves. - for( PlayerTeamList::iterator it = m_playerTeamPrototypes.begin(); it != m_playerTeamPrototypes.end(); ++it ) - { - for( DLINK_ITERATOR iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance() ) - { - Team *team = iter.cur(); - if( !team ) - { - continue; - } - team->updateGenericScripts(); - } - } - - if( m_energy.getPowerSabotagedTillFrame() != 0 && TheGameLogic->getFrame() > m_energy.getPowerSabotagedTillFrame() ) - { - m_energy.setPowerSabotagedTillFrame( 0 ); //Tells us we're no longer sabotaged for above check. - onPowerBrownOutChange( !m_energy.hasSufficientPower() ); - } - - //Update the academy stats (this only checks applicable things that require a polling method) - getAcademyStats()->update(); - -#if !(RTS_GENERALS && (RETAIL_COMPATIBLE_CRC || RETAIL_COMPATIBLE_NETWORKING)) - //Kris: August 25, 2003 (DAY OF CODE LOCK -- NO NEW FEATURES, REALLY!) - if( ThePlayerList->getLocalPlayer() == this ) - { - UnsignedInt now = TheGameLogic->getFrame(); - //Only check and post the message once every second so we don't spam the message stream to account for lag. - if( now % LOGICFRAMES_PER_SECOND == 0 ) - { - if( TheGlobalData->m_clientRetaliationModeEnabled != isLogicalRetaliationModeEnabled() ) - { - //Post a logical message that will switch the retaliation mode on or off. - GameMessage *msg = TheMessageStream->appendMessage( GameMessage::MSG_ENABLE_RETALIATION_MODE ); - if( msg ) - { -#if RETAIL_COMPATIBLE_CRC - msg->appendIntegerArgument( getPlayerIndex() ); -#endif - msg->appendBooleanArgument( TheGlobalData->m_clientRetaliationModeEnabled ); - } - } - } - } -#endif - -#if !(RETAIL_COMPATIBLE_CRC || PRESERVE_TUNNEL_HEAL_STACKING) - // TheSuperHackers @bugfix Stubbjax 26/09/2025 The Tunnel System now heals - // all units once per frame instead of once per frame per Tunnel Network. - TunnelTracker* tunnelSystem = getTunnelSystem(); - if (tunnelSystem) - tunnelSystem->healObjects(); -#endif - - m_money.updateIncomeBucket(); -} - -//============================================================================= -void Player::newMap() -{ - if (m_ai) - m_ai->newMap(); -} - -//============================================================================= -void Player::setPlayerType(PlayerType t, Bool skirmish) -{ - m_playerType = t; - - deleteInstance(m_ai); - m_ai = nullptr; - - if (t == PLAYER_COMPUTER) - { - if (skirmish || TheAI->getAiData()->m_forceSkirmishAI) { - // create AIPlayer and attach to this Player - m_ai = newInstance(AISkirmishPlayer)( this ); - } else { - // create AIPlayer and attach to this Player - m_ai = newInstance(AIPlayer)( this ); - } - } -} - -//============================================================================= -// This is called from PlayerList->newGame() -// -void Player::setDefaultTeam() { - AsciiString tname; - tname.set("team"); - tname.concat(m_playerName); - Team *dt = TheTeamFactory->findTeam(tname); - DEBUG_ASSERTCRASH(dt, ("no team")); - if (dt) { - m_defaultTeam = dt; - dt->setActive(); - } -} - -//============================================================================= -void Player::deletePlayerAI() -{ - deleteInstance(m_ai); - m_ai = nullptr; -} - -//============================================================================= -// This is called from PlayerList->newGame() -// -void Player::initFromDict(const Dict* d) -{ - AsciiString tmplname = d->getAsciiString(TheKey_playerFaction); - const PlayerTemplate* pt = ThePlayerTemplateStore->findPlayerTemplate(NAMEKEY(tmplname)); - DEBUG_ASSERTCRASH(pt != nullptr, ("PlayerTemplate %s not found -- this is an obsolete map (please open and resave in WB)",tmplname.str())); - - init(pt); - - m_playerDisplayName = d->getUnicodeString(TheKey_playerDisplayName); - AsciiString pname = d->getAsciiString(TheKey_playerName); - m_playerName = pname; - m_playerNameKey = NAMEKEY(pname); - - Bool exists; - Bool skirmish = false; - Bool forceHuman = false; - if (d->getBool(TheKey_playerIsSkirmish, &exists)) - { - - // srj sez: check to ensure the map actually has a skirmish player... ordinarily it should, but - // poorly-formed user maps might not, which would be bad, and could crash us later. so if it doesn't - // actually have a skirmish player defined for this side, declare it nonskirmish... the player won't - // really work, but it's better than crashing. - for (Int spIdx = 0; spIdx < TheSidesList->getNumSkirmishSides(); ++spIdx) - { - AsciiString spTemplateName = TheSidesList->getSkirmishSideInfo(spIdx)->getDict()->getAsciiString(TheKey_playerFaction); - const PlayerTemplate* spt = ThePlayerTemplateStore->findPlayerTemplate(NAMEKEY(spTemplateName)); - if (spt && spt->getSide() == getSide()) - { - skirmish = true; - break; - } - } - - DEBUG_ASSERTCRASH(skirmish, ("Could not find skirmish player for side %s... quietly making into nonskirmish.", getSide().str())); - if (!skirmish) - forceHuman = true; - - } - - if (d->getBool(TheKey_playerIsHuman) || forceHuman) - { - setPlayerType(PLAYER_HUMAN, false); - if (d->getBool(TheKey_playerIsPreorder, &exists)) - { - m_isPreorder = TRUE; - } - if (TheSidesList->getNumSkirmishSides()>0) { - // Human player gets scripts from CIVILIAN player. - AsciiString mySide = "Civilian"; - Int i; - Bool found = false; - AsciiString qualTemplatePlayerName; - for (i=0; igetNumSkirmishSides(); i++) { - AsciiString templateName = TheSidesList->getSkirmishSideInfo(i)->getDict()->getAsciiString(TheKey_playerFaction); - pt = ThePlayerTemplateStore->findPlayerTemplate(NAMEKEY(templateName)); - if (pt && pt->getSide() == mySide) { - qualTemplatePlayerName.format("%s%d", TheSidesList->getSkirmishSideInfo(i)->getDict()->getAsciiString(TheKey_playerName).str(), m_mpStartIndex); - found = true; - break; - } - } - if (found && TheSidesList->getSkirmishSideInfo(i)->getScriptList()) { - AsciiString qualifier; - qualifier.format("%d", m_mpStartIndex); - - ScriptList *scripts = TheSidesList->getSkirmishSideInfo(i)->getScriptList()->duplicateAndQualify( - qualifier, qualTemplatePlayerName, pname); - - deleteInstance(TheSidesList->getSideInfo(getPlayerIndex())->getScriptList()); - TheSidesList->getSideInfo(getPlayerIndex())->setScriptList(scripts); - - deleteInstance(TheSidesList->getSkirmishSideInfo(i)->getScriptList()); - TheSidesList->getSkirmishSideInfo(i)->setScriptList(nullptr); - } - - } - skirmish = false; - } - else - { - setPlayerType(PLAYER_COMPUTER, skirmish); - } - m_mpStartIndex = d->getInt(TheKey_multiplayerStartIndex, &exists); - if (skirmish) { - // Copy and qualify scripts, and teams. - - AsciiString mySide = getSide(); - Int i, skirmishNdx; - Bool found = false; - AsciiString qualTemplatePlayerName; - for (skirmishNdx=0; skirmishNdxgetNumSkirmishSides(); skirmishNdx++) { - AsciiString templateName = TheSidesList->getSkirmishSideInfo(skirmishNdx)->getDict()->getAsciiString(TheKey_playerFaction); - pt = ThePlayerTemplateStore->findPlayerTemplate(NAMEKEY(templateName)); - if (pt && pt->getSide() == mySide) { - qualTemplatePlayerName.format("%s%d", TheSidesList->getSkirmishSideInfo(skirmishNdx)->getDict()->getAsciiString(TheKey_playerName).str(), m_mpStartIndex); - found = true; - break; - } - } - Int diffInt = d->getInt(TheKey_skirmishDifficulty, &exists); - GameDifficulty difficulty = TheScriptEngine->getGlobalDifficulty(); - if (exists) - { - difficulty = (GameDifficulty) diffInt; - } - if (m_ai) - { - m_ai->setAIDifficulty(difficulty); - } - - if (!found) - { - DEBUG_CRASH(("Could not find skirmish player for side %s", mySide.str())); - } else { - m_playerName = qualTemplatePlayerName; - AsciiString qualifier; - qualifier.format("%d", m_mpStartIndex); - ScriptList *scripts = TheSidesList->getSkirmishSideInfo(skirmishNdx)->getScriptList()->duplicateAndQualify( - qualifier, qualTemplatePlayerName, pname); - - deleteInstance(TheSidesList->getSideInfo(getPlayerIndex())->getScriptList()); - TheSidesList->getSideInfo(getPlayerIndex())->setScriptList(scripts); - - for (i=0; igetNumTeams(); i++) { - if (TheSidesList->getTeamInfo(i)->getDict()->getAsciiString(TheKey_teamOwner) == pname) - { - // Remove any teams in this player. - TheSidesList->removeTeam(i); - i--; - } - } - // Now add teams. - - AsciiString originalPlayerName = TheSidesList->getSkirmishSideInfo(skirmishNdx)->getDict()->getAsciiString(TheKey_playerName); - for (i=0; igetNumSkirmishTeams(); i++) { - if (TheSidesList->getSkirmishTeamInfo(i)->getDict()->getAsciiString(TheKey_teamOwner) == originalPlayerName) - { - Dict teamDict(*TheSidesList->getSkirmishTeamInfo(i)->getDict()); - AsciiString teamName = teamDict.getAsciiString(TheKey_teamName); - AsciiString newName; - newName.format("%s%d", teamDict.getAsciiString(TheKey_teamName).str(), m_mpStartIndex); - - if (TheSidesList->findTeamInfo(newName)) continue; - teamDict.setAsciiString(TheKey_teamOwner, pname); - teamDict.setAsciiString(TheKey_teamName, newName); - // qualify scripts. - - NameKeyType nameKeys[] = - { - TheKey_teamOnCreateScript, - TheKey_teamOnIdleScript, - TheKey_teamOnUnitDestroyedScript, - TheKey_teamOnDestroyedScript, - TheKey_teamEnemySightedScript, - TheKey_teamAllClearScript, - TheKey_teamProductionCondition - }; - - Int j; - const Int numKeys = sizeof(nameKeys) / sizeof(NameKeyType); - AsciiString tmpStr; - for (j = 0; j < numKeys; ++j) - { - tmpStr = teamDict.getAsciiString(nameKeys[j], &exists); - if (exists && !tmpStr.isEmpty()) - { - newName.format("%s%d", tmpStr.str(), m_mpStartIndex); - teamDict.setAsciiString(nameKeys[j], newName); - } - } - - // Now do the TheKey_teamGenericScriptHookN (where N can be from 0 to 15.) - for (j = 0; j < MAX_GENERIC_SCRIPTS; ++j) { - AsciiString keyName; - keyName.format("%s%d", TheNameKeyGenerator->keyToName(TheKey_teamGenericScriptHook).str(), j); - tmpStr = teamDict.getAsciiString(NAMEKEY(keyName), &exists); - if (exists && !tmpStr.isEmpty()) - { - newName.format("%s%d", tmpStr.str(), m_mpStartIndex); - teamDict.setAsciiString(NAMEKEY(keyName), newName); - } - } - - // Done. Now add the team. - TheSidesList->addTeam(&teamDict); - } - } - } - } - - deleteInstance(m_resourceGatheringManager); - m_resourceGatheringManager = newInstance(ResourceGatheringManager); - - deleteInstance(m_tunnelSystem); - m_tunnelSystem = newInstance(TunnelTracker); - - m_handicap.readFromDict(d); - - /// @todo Ack! the todo in PlayerList::reset() mentioning the need for a Player::reset() really needs to get done. - m_playerRelations->m_map.clear(); // For now, it has been decided to just fix this one. Dear god me must reset. - m_teamRelations->m_map.clear(); // For now, it has been decided to just fix this one. Dear god me must reset. - - Int i; - for ( i = 0; i < MAX_PLAYER_COUNT; ++i ) // For now, it has been decided to just fix this one. Dear god me must reset. - { - m_attackedBy[i] = false; -#if RTS_GENERALS - m_visionSpiedBy[i] = 0; -#endif - } -#if RTS_GENERALS - m_visionSpiedMask = PLAYERMASK_NONE; -#endif - - Int c = d->getInt(TheKey_playerColor, &exists); - if (exists) - { - m_color = c | 0xff000000; - m_nightColor = m_color; - } - - c = d->getInt(TheKey_playerNightColor, &exists); - if (exists) - { - m_nightColor = c | 0xff000000; - } - - Int m = d->getInt(TheKey_playerStartMoney, &exists); - if (exists) - m_money.deposit(m); - - for ( i = 0; i < NUM_HOTKEY_SQUADS; ++i ) { - deleteInstance(m_squads[i]); - m_squads[i] = newInstance( Squad ); - } - - deleteInstance(m_currentSelection); - m_currentSelection = newInstance( Squad ); -} - -//============================================================================= -void Player::becomingTeamMember(Object *obj, Bool yes) -{ - if (!obj) - return; - - // energy production/consumption hooks, note we ignore things that are UNDER_CONSTRUCTION - if( !obj->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) ) - { - obj->friend_adjustPowerForPlayer(yes); - } - - // when we capture a building, we need to see if there's an AutoDepositUpdate hooked to it, - // if so, award the cash bonus - if(this != ThePlayerList->getNeutralPlayer() && yes) - { - NameKeyType key_AutoDepositUpdate = NAMEKEY("AutoDepositUpdate"); - AutoDepositUpdate *adu = (AutoDepositUpdate *)obj->findUpdateModule(key_AutoDepositUpdate); - if (adu != nullptr) { - adu->awardInitialCaptureBonus( this ); - } - } - - if( getNumBattlePlansActive() > 0 && obj->areModulesReady() ) - { - if( yes ) - { - //We are entering a team with active battle plans so add it's bonuses now - applyBattlePlanBonusesForObject( obj ); - } - else - { - //We are leaving a team with active battle plans so remove them now. - removeBattlePlanBonusesForObject( obj ); - } - } - - - if (obj->isKindOf(KINDOF_DOZER) && - obj->getAIUpdateInterface() && - obj->getAIUpdateInterface()->isIdle()) - { - // Need to remove it from the pick a peasant button - if (yes) - TheInGameUI->addIdleWorker(obj); - else - TheInGameUI->removeIdleWorker(obj, getPlayerIndex()); - } -} - -//============================================================================= -void Player::becomingLocalPlayer(Bool yes) -{ - if (yes) - { - // This changes the color of the little dot on the upper right side of the screen indicating - // which team is under control. - if( TheGameClient ) - { - RGBColor rgb; - rgb.setFromInt(m_color); - TheGameClient->setTeamColor(REAL_TO_INT(rgb.red*255), REAL_TO_INT(rgb.green*255), REAL_TO_INT(rgb.blue*255)); - } - - if( ThePartitionManager ) - { - ObjectIterator *iter = ThePartitionManager->iterateAllObjects(); - for( Object* object = iter->first(); object; object = iter->next() ) - { - // Added support for updating the perceptions of garrisoned buildings containing enemy stealth units. - // When changing teams, it is necessary to update this information. - Bool requireRadarRefresh = false; - ContainModuleInterface *contain = object->getContain(); - if( contain ) - { - contain->recalcApparentControllingPlayer(); - requireRadarRefresh = true; - } - - if( object->isKindOf( KINDOF_DISGUISER ) ) - { - //KM -- August 2002: - //Added support for disguised objects, based on relationships, we either show the real color or the disguised color. - Drawable *draw = object->getDrawable(); - if( draw ) - { - - StealthUpdate *update = object->getStealth(); - - if( update && update->isDisguised() ) - { - Player *disguisedPlayer = ThePlayerList->getNthPlayer( update->getDisguisedPlayerIndex() ); - if( getRelationship( object->getTeam() ) != ALLIES && isPlayerActive() ) - { - //Neutrals and enemies will see this disguised unit as the team it's disguised as. - if (TheGlobalData->m_timeOfDay == TIME_OF_DAY_NIGHT) - draw->setIndicatorColor( disguisedPlayer->getPlayerNightColor()); - else - draw->setIndicatorColor( disguisedPlayer->getPlayerColor() ); - } - else - { - //Otherwise, the color will show up as the team it really belongs to. - if (TheGlobalData->m_timeOfDay == TIME_OF_DAY_NIGHT) - draw->setIndicatorColor(object->getNightIndicatorColor()); - else - draw->setIndicatorColor( object->getIndicatorColor() ); - } - requireRadarRefresh = true; - } - } - } - - if (requireRadarRefresh) - { - TheRadar->removeObject( object ); - TheRadar->addObject( object ); - } - } - deleteInstance(iter); - } - - if( TheControlBar ) - TheControlBar->markUIDirty(); - } - else - { - // nothing to do - } -} - -//------------------------------------------------------------------------------------------------- -/** Is this player a skirmish ai player? */ -//------------------------------------------------------------------------------------------------- -Bool Player::isSkirmishAIPlayer() -{ - return m_ai ? m_ai->isSkirmishAI() : false; -} - - -//---------------------------------------------------------------------------------------------------------- -/** - * Find a good spot to fire a superweapon. - */ -Bool Player::computeSuperweaponTarget(const SpecialPowerTemplate *power, Coord3D *retPos, Int playerNdx, Real weaponRadius) -{ - if (m_ai) { - return m_ai->computeSuperweaponTarget(power, retPos, playerNdx, weaponRadius); - } - - return FALSE; -} - -//------------------------------------------------------------------------------------------------- -/** Get this player's current enemy. NOTE - Can be nullptr. */ -//------------------------------------------------------------------------------------------------- -Player *Player::getCurrentEnemy() -{ - return m_ai?m_ai->getAiEnemy():nullptr; -} - -//------------------------------------------------------------------------------------------------- -// PlayerObjectFindInfo is used to find a player's object. For example, we iterate through -// to find a player's command center, or a specific building capable of firing the specified -// special power. -// -// if he has none, return null. -// if he has multiple, return one arbitrarily. -//------------------------------------------------------------------------------------------------- - -//------------------------------------------------------------------------------------------------- -// Iterator data struct -//------------------------------------------------------------------------------------------------- -struct PlayerObjectFindInfo -{ - Player* player; - Object* obj; - SpecialPowerType spType; - const ThingTemplate *thing; - UnsignedInt lowestReadyFrame; - UnsignedInt highestPercentage; - UnsignedInt numReady; -}; - -//------------------------------------------------------------------------------------------------- -// Iterator function -// Find the first available command center that is naturally ours (not captured from enemy). -//------------------------------------------------------------------------------------------------- -static void doFindCommandCenter(Object* obj, void* userData) -{ - PlayerObjectFindInfo* info = (PlayerObjectFindInfo*)userData; - - if (info->obj == nullptr && - obj->isKindOf(KINDOF_COMMANDCENTER) && - obj->getTemplate()->getDefaultOwningSide() == info->player->getSide() && - !obj->testStatus(OBJECT_STATUS_UNDER_CONSTRUCTION) && - !obj->testStatus(OBJECT_STATUS_SOLD)) - { - info->obj = obj; - } -} - -//------------------------------------------------------------------------------------------------- -// Iterator function -// Find first object capable of firing specified special power right now. -//------------------------------------------------------------------------------------------------- -static void doFindSpecialPowerSourceObject( Object *obj, void *userData ) -{ - PlayerObjectFindInfo* info = (PlayerObjectFindInfo*)userData; - - if( info->lowestReadyFrame == 0 ) - { - //We already found the best case scenario, so no need to iterate any more. - return; - } - if( !obj->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION ) && - !obj->testStatus( OBJECT_STATUS_SOLD ) && - !obj->isEffectivelyDead() ) - { - if( info->spType == SPECIAL_INVALID && obj->hasAnySpecialPower() ) - { - //We just care about find an object that has *any* shortcut capable special power. - //Iterate through the special power modules and look for one. - SpecialPowerModuleInterface *spmInterface = obj->findAnyShortcutSpecialPowerModuleInterface(); - if( spmInterface && !spmInterface->isScriptOnly() ) - { - info->obj = obj; - info->lowestReadyFrame = 0; - return; - } - } - else if( obj->hasSpecialPower( info->spType ) ) - { - SpecialPowerModuleInterface *spmInterface = obj->findSpecialPowerModuleInterface( info->spType ); - if( spmInterface && !spmInterface->isScriptOnly() ) - { - UnsignedInt readyFrame = spmInterface->getReadyFrame(); - -#if defined(RTS_DEBUG) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) - // Everything is ready if timers are debug off'd - if( ! TheGlobalData->m_specialPowerUsesDelay ) - readyFrame = 0; -#endif - // A disabled guy should only be considered as a last resort. We need it to be counted - // so that a disabled button can appear on the shortcut. - if( obj->isDisabled() ) - readyFrame = UINT_MAX - 10; - - if( readyFrame < TheGameLogic->getFrame()) - { - //This special power is ready now and matches, so simply return the - //first one. - info->obj = obj; - info->lowestReadyFrame = 0; - return; - } - else if( readyFrame < info->lowestReadyFrame ) - { - //This special power isn't ready, but it is going to be ready sooner than any others - //we checked (or it's the first one we checked). - info->obj = obj; - info->lowestReadyFrame = readyFrame; - return; - } - } - } - } -} - -//------------------------------------------------------------------------------------------------- -// Iterator function -// Count number of specified special powers that are ready to fire now. -//------------------------------------------------------------------------------------------------- -static void doCountSpecialPowersReady( Object *obj, void *userData ) -{ - PlayerObjectFindInfo* info = (PlayerObjectFindInfo*)userData; - - if( !obj->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION ) && - !obj->testStatus( OBJECT_STATUS_SOLD ) && - !obj->isEffectivelyDead() ) - { - if( obj->hasSpecialPower( info->spType ) ) - { - SpecialPowerModuleInterface *spmInterface = obj->findSpecialPowerModuleInterface( info->spType ); - if( spmInterface && !spmInterface->isScriptOnly() ) - { - - if( spmInterface->getSpecialPowerTemplate()->isSharedNSync() && info->numReady == 1 ) - { - //Shared powers don't stack after the first one is counted. - return; - } - - UnsignedInt readyFrame = spmInterface->getReadyFrame(); - -#if defined(RTS_DEBUG) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE) - // Everything is ready if timers are debug off'd - if( ! TheGlobalData->m_specialPowerUsesDelay ) - readyFrame = 0; -#endif - - // A disabled guy should only be considered as a last resort. We do not want him counted here - // so that Disabled guys do not go in to the number on the shortcut button. - if( obj->isDisabled() ) - readyFrame = UINT_MAX - 10; - - if( readyFrame < TheGameLogic->getFrame()) - { - //This special power is ready now and matches, so simply return the - //first one. - info->numReady++; - } - } - } - } -} - -//------------------------------------------------------------------------------------------------- -static void doFindMostReadyWeaponForThing( Object *obj, void *userData ) -{ - PlayerObjectFindInfo* info = (PlayerObjectFindInfo*)userData; - - if( info->highestPercentage >= 100 ) - { - //We already found the best case scenario, so no need to iterate any more. - return; - } - - if( info->thing && info->thing->isEquivalentTo( obj->getTemplate() ) ) - { - if( !obj->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION ) && - !obj->testStatus( OBJECT_STATUS_SOLD ) && - !obj->isEffectivelyDead() ) - { - if( obj->hasAnyWeapon() ) - { - UnsignedInt percentage = obj->getMostPercentReadyToFireAnyWeapon(); - if( percentage > info->highestPercentage ) - { - //This weapon is more ready than any others we've checked. - info->obj = obj; - info->highestPercentage = percentage; - return; - } - } - } - } -} - -//------------------------------------------------------------------------------------------------- -static void doFindMostReadySpecialPowerForThing( Object *obj, void *userData ) -{ - PlayerObjectFindInfo* info = (PlayerObjectFindInfo*)userData; - - if( info->highestPercentage >= 100 ) - { - //We already found the best case scenario, so no need to iterate any more. - return; - } - - if( info->thing && info->thing->isEquivalentTo( obj->getTemplate() ) ) - { - if( !obj->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION ) && - !obj->testStatus( OBJECT_STATUS_SOLD ) && - !obj->isEffectivelyDead() ) - { - // search the modules for the one with the matching template - for( BehaviorModule** m = obj->getBehaviorModules(); *m; ++m ) - { - SpecialPowerModuleInterface* sp = (*m)->getSpecialPower(); - if (!sp) - continue; - - UnsignedInt percentage = sp->getPercentReady(); - if( percentage > info->highestPercentage ) - { - //This weapon is more ready than any others we've checked. - info->obj = obj; - info->highestPercentage = percentage; - } - } - } - } -} - -//------------------------------------------------------------------------------------------------- -static void doFindExistingObjectWithThingTemplate( Object *obj, void *userData ) -{ - PlayerObjectFindInfo* info = (PlayerObjectFindInfo*)userData; - - if( info->obj ) - { - //We already found a matching obj, so return - return; - } - - if( info->thing && info->thing->isEquivalentTo( obj->getTemplate() ) ) - { - if( !obj->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION ) && - !obj->testStatus( OBJECT_STATUS_SOLD ) && - !obj->isEffectivelyDead() ) - { - //We found one. - info->obj = obj; - } - } -} - -//------------------------------------------------------------------------------------------------- -Object* Player::findNaturalCommandCenter() -{ - PlayerObjectFindInfo info; - info.player = this; - info.obj = nullptr; - iterateObjects(doFindCommandCenter, &info); - return info.obj; -} - -//------------------------------------------------------------------------------------------------- -Object* Player::findMostReadyShortcutSpecialPowerOfType( SpecialPowerType spType ) -{ - PlayerObjectFindInfo info; - info.player = this; - info.obj = nullptr; - info.spType = spType; - info.lowestReadyFrame = 0xffffffff; - iterateObjects( doFindSpecialPowerSourceObject, &info ); - return info.obj; -} - -//------------------------------------------------------------------------------------------------- -Object* Player::findMostReadyShortcutWeaponForThing( const ThingTemplate *thing, UnsignedInt &mostReadyPercentage ) -{ - PlayerObjectFindInfo info; - info.player = this; - info.obj = nullptr; - info.thing = thing; - info.highestPercentage = 0; - iterateObjects( doFindMostReadyWeaponForThing, &info ); - mostReadyPercentage = info.highestPercentage; - return info.obj; -} - -//------------------------------------------------------------------------------------------------- -Object* Player::findMostReadyShortcutSpecialPowerForThing( const ThingTemplate *thing, UnsignedInt &mostReadyPercentage ) -{ - PlayerObjectFindInfo info; - info.player = this; - info.obj = nullptr; - info.thing = thing; - info.highestPercentage = 0; - iterateObjects( doFindMostReadySpecialPowerForThing, &info ); - mostReadyPercentage = info.highestPercentage; - return info.obj; -} - -//------------------------------------------------------------------------------------------------- -Object* Player::findAnyExistingObjectWithThingTemplate( const ThingTemplate *thing ) -{ - PlayerObjectFindInfo info; - info.player = this; - info.obj = nullptr; - info.thing = thing; - iterateObjects( doFindExistingObjectWithThingTemplate, &info ); - return info.obj; -} - -//------------------------------------------------------------------------------------------------- -// Finds a short-cut firing special power of any type arbitrarily. -//------------------------------------------------------------------------------------------------- -Bool Player::hasAnyShortcutSpecialPower() -{ - PlayerObjectFindInfo info; - info.player = this; - info.obj = nullptr; - info.spType = SPECIAL_INVALID; //Invalid dictates that we don't care about the type. - info.lowestReadyFrame = 0xffffffff; - iterateObjects( doFindSpecialPowerSourceObject, &info ); - return info.obj; -} - -//------------------------------------------------------------------------------------------------- -Int Player::countReadyShortcutSpecialPowersOfType( SpecialPowerType spType ) -{ - PlayerObjectFindInfo info; - info.spType = spType; - info.numReady = 0; - iterateObjects( doCountSpecialPowersReady, &info ); - return info.numReady; -} - -//------------------------------------------------------------------------------------------------- -/** Difficulty level for this player */ -//------------------------------------------------------------------------------------------------- -GameDifficulty Player::getPlayerDifficulty() const -{ - if (m_ai) - { - return m_ai->getAIDifficulty(); - } - return TheScriptEngine->getGlobalDifficulty(); -} - -//------------------------------------------------------------------------------------------------- -/** Do any bridges need repair, and if so repair them. */ -//------------------------------------------------------------------------------------------------- -Bool Player::checkBridges(Object *unit, Waypoint *way) -{ - return m_ai?m_ai->checkBridges(unit, way):false; -} - -//------------------------------------------------------------------------------------------------- -/** Do any bridges need repair, and if so repair them. */ -//------------------------------------------------------------------------------------------------- -Bool Player::getAiBaseCenter(Coord3D *pos) -{ - return m_ai?m_ai->getBaseCenter(pos):false; -} - -//------------------------------------------------------------------------------------------------- -/** Repair bridge or structure. */ -//------------------------------------------------------------------------------------------------- -void Player::repairStructure(ObjectID structureID) -{ - if (m_ai) - { - m_ai->repairStructure(structureID); - } -} - -//------------------------------------------------------------------------------------------------- -/** A unit was just created and is ready to control */ -//------------------------------------------------------------------------------------------------- -void Player::onUnitCreated( Object *factory, Object *unit ) -{ - // When a a unit is completed, it becomes "real" as far as scripting is - // concerned. jba. - TheScriptEngine->notifyOfObjectCreationOrDestruction(); - - // increment our scorekeeper - m_scoreKeeper.addObjectBuilt(unit); - - // ai notification callback - if( m_ai ) - m_ai->onUnitProduced( factory, unit ); -} - - -//------------------------------------------------------------------------------------------------- -/** Is the nearest supply source safe? */ -//------------------------------------------------------------------------------------------------- -Bool Player::isSupplySourceSafe( Int minSupplies ) -{ - // ai query - if( m_ai ) - return m_ai->isSupplySourceSafe( minSupplies ); - return true; -} - -//------------------------------------------------------------------------------------------------- -/** Is a supply source attacked? */ -//------------------------------------------------------------------------------------------------- -Bool Player::isSupplySourceAttacked() -{ - // ai query - if( m_ai ) - return m_ai->isSupplySourceAttacked(); - return false; -} - -//------------------------------------------------------------------------------------------------- -/** Set delay between team production */ -//------------------------------------------------------------------------------------------------- -void Player::setTeamDelaySeconds(Int delay ) -{ - // ai action - if( m_ai ) - m_ai->setTeamDelaySeconds( delay ); -} - -//------------------------------------------------------------------------------------------------- -/** Guard supply center */ -//------------------------------------------------------------------------------------------------- -void Player::guardSupplyCenter( Team *team, Int minSupplies ) -{ - // ai action - if( m_ai ) - m_ai->guardSupplyCenter( team, minSupplies ); -} - -//------------------------------------------------------------------------------------------------- -/** A team is about to be destroyed */ -//------------------------------------------------------------------------------------------------- -void Player::preTeamDestroy( const Team *team ) -{ - // ai notification callback - if( m_ai ) - m_ai->aiPreTeamDestroy( team ); - - // TheSuperHackers @bugfix Mauller/Xezon 03/05/2025 Clear the default team to prevent dangling pointer usage - if( m_defaultTeam == team ) - m_defaultTeam = nullptr; -} - -//------------------------------------------------------------------------------------------------- -/// a structure was just created, but is under construction -//------------------------------------------------------------------------------------------------- -void Player::onStructureCreated( Object *builder, Object *structure ) -{ - -} - -//------------------------------------------------------------------------------------------------- -/// a structure that was under construction has become completed -//------------------------------------------------------------------------------------------------- -void Player::onStructureConstructionComplete( Object *builder, Object *structure, Bool isRebuild ) -{ - // When a a structure is completed, it becomes "real" as far as scripting is - // concerned. jba. - TheScriptEngine->notifyOfObjectCreationOrDestruction(); - - // Update the pathfind footprint. Sometimes when rubble has to be removed - // to build, the initial footprint while building is goofy. jba. - TheAI->pathfinder()->removeObjectFromPathfindMap(structure); - TheAI->pathfinder()->addObjectToPathfindMap(structure); - - // increment our scorekeeper - if (isRebuild == FALSE) { - m_scoreKeeper.addObjectBuilt(structure); - m_scoreKeeper.addMoneySpent(structure->getTemplate()->calcCostToBuild(this)); - } - - structure->friend_adjustPowerForPlayer(TRUE); - - // ai notification callback - if( m_ai ) - m_ai->onStructureProduced( builder, structure ); - - // the GUI needs to re-evaluate the information being displayed to the user now - if( TheControlBar ) - TheControlBar->markUIDirty(); - - // This object may require us to play some EVA sounds. - Player *localPlayer = ThePlayerList->getLocalPlayer(); -#if RTS_GENERALS - if (localPlayer == structure->getControllingPlayer() || localPlayer->getRelationship(structure->getTeam()) != ENEMIES) - return; - - // We need to play some EVA sounds. - if (structure->hasSpecialPower(SPECIAL_PARTICLE_UPLINK_CANNON)) - TheEva->setShouldPlay(EVA_SuperweaponDetected_ParticleCannon); - - if (structure->hasSpecialPower(SPECIAL_NEUTRON_MISSILE)) - TheEva->setShouldPlay(EVA_SuperweaponDetected_Nuke); - - if (structure->hasSpecialPower(SPECIAL_SCUD_STORM)) - TheEva->setShouldPlay(EVA_SuperweaponDetected_ScudStorm); -#else - - if( structure->hasSpecialPower( SPECIAL_PARTICLE_UPLINK_CANNON ) || - structure->hasSpecialPower( SUPW_SPECIAL_PARTICLE_UPLINK_CANNON ) || - structure->hasSpecialPower( LAZR_SPECIAL_PARTICLE_UPLINK_CANNON ) ) - { - if ( localPlayer == structure->getControllingPlayer() ) - { - TheEva->setShouldPlay(EVA_SuperweaponDetected_Own_ParticleCannon); - } - else if ( localPlayer->getRelationship(structure->getTeam()) != ENEMIES ) - { - // Note: treating NEUTRAL as ally. Is this correct? - TheEva->setShouldPlay(EVA_SuperweaponDetected_Ally_ParticleCannon); - } - else - { - TheEva->setShouldPlay(EVA_SuperweaponDetected_Enemy_ParticleCannon); - } - } - - if( structure->hasSpecialPower( SPECIAL_NEUTRON_MISSILE ) || - structure->hasSpecialPower( NUKE_SPECIAL_NEUTRON_MISSILE ) || - structure->hasSpecialPower( SUPW_SPECIAL_NEUTRON_MISSILE ) ) - { - if ( localPlayer == structure->getControllingPlayer() ) - { - TheEva->setShouldPlay(EVA_SuperweaponDetected_Own_Nuke); - } - else if ( localPlayer->getRelationship(structure->getTeam()) != ENEMIES ) - { - // Note: treating NEUTRAL as ally. Is this correct? - TheEva->setShouldPlay(EVA_SuperweaponDetected_Ally_Nuke); - } - else - { - TheEva->setShouldPlay(EVA_SuperweaponDetected_Enemy_Nuke); - } - } - - if (structure->hasSpecialPower(SPECIAL_SCUD_STORM)) - { - if ( localPlayer == structure->getControllingPlayer() ) - { - TheEva->setShouldPlay(EVA_SuperweaponDetected_Own_ScudStorm); - } - else if ( localPlayer->getRelationship(structure->getTeam()) != ENEMIES ) - { - // Note: treating NEUTRAL as ally. Is this correct? - TheEva->setShouldPlay(EVA_SuperweaponDetected_Ally_ScudStorm); - } - else - { - TheEva->setShouldPlay(EVA_SuperweaponDetected_Enemy_ScudStorm); - } - } -#endif -} - -//============================================================================= -void Player::onStructureUndone(Object *structure) -{ - m_scoreKeeper.removeObjectBuilt(structure); -} - -//============================================================================= -void Player::addTeamToList(TeamPrototype* team) -{ - for( PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin(); - it != m_playerTeamPrototypes.end(); ++it ) - { - if (team == *it) - return; // already present - } - - m_playerTeamPrototypes.push_back(team); -} - -//============================================================================= -void Player::removeTeamFromList(TeamPrototype* team) -{ - for (PlayerTeamList::iterator it = m_playerTeamPrototypes.begin(); - it != m_playerTeamPrototypes.end(); ++it) - { - if (team == *it) - { - m_playerTeamPrototypes.erase(it); - return; - } - } -} - -//============================================================================= -void Player::healAllObjects() -{ - for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin(); - it != m_playerTeamPrototypes.end(); ++it) - { - (*it)->healAllObjects(); - } -} - -//============================================================================= -void Player::iterateObjects( ObjectIterateFunc func, void *userData ) const -{ - for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin(); - it != m_playerTeamPrototypes.end(); ++it) - { - (*it)->iterateObjects( func, userData ); - } -} - -//============================================================================= -void Player::countObjectsByThingTemplate(Int numTmplates, const ThingTemplate* const * things, Bool ignoreDead, Int *counts, Bool ignoreUnderConstruction ) const -{ - Int i; - - for (i = 0; i < numTmplates; ++i) - counts[i] = 0; - - for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin(); - it != m_playerTeamPrototypes.end(); - ++it) - { - (*it)->countObjectsByThingTemplate(numTmplates, things, ignoreDead, counts, ignoreUnderConstruction); - } -} - -//============================================================================= -Int Player::countBuildings() -{ - int retVal = 0; - - for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin(); - it != m_playerTeamPrototypes.end(); ++it) - { - retVal += (*it)->countBuildings(); - } - return retVal; -} - -//============================================================================= -Int Player::countObjects(KindOfMaskType setMask, KindOfMaskType clearMask) -{ - int retVal = 0; - - for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin(); - it != m_playerTeamPrototypes.end(); ++it) - { - retVal += (*it)->countObjects(setMask, clearMask); - } - return retVal; -} - -//============================================================================= -Object *Player::findClosestByKindOf( Object *queryObject, KindOfMaskType setMask, KindOfMaskType clearMask ) -{ - if( queryObject == nullptr ) - return nullptr; - - ClosestKindOfData data; - data.m_setKindOf = setMask; - data.m_clearKindOf = clearMask; - data.m_source = queryObject; - - // Magic presto! data ends up with the answer in it! - iterateObjects( findClosestKindOf, &data ); - - return data.m_closest; -} - -//============================================================================= -Bool Player::hasAnyBuildings() const -{ - for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin(); - it != m_playerTeamPrototypes.end(); ++it) - { - if ((*it)->hasAnyBuildings()) { - return true; - } - } - return false; -} - -//============================================================================= -Bool Player::hasAnyBuildings(KindOfMaskType kindOf) const -{ - for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin(); - it != m_playerTeamPrototypes.end(); ++it) - { - if ((*it)->hasAnyBuildings(kindOf)) { - return true; - } - } - return false; -} - -//============================================================================= -Bool Player::hasAnyUnits() const -{ - for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin(); - it != m_playerTeamPrototypes.end(); ++it) - { - if ((*it)->hasAnyUnits()) { - return true; - } - } - return false; -} - -//============================================================================= -Bool Player::hasAnyObjects() const -{ - for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin(); - it != m_playerTeamPrototypes.end(); ++it) - { - if ((*it)->hasAnyObjects()) { - return true; - } - } - return false; -} - -//============================================================================= -Bool Player::hasAnyBuildFacility() const -{ - for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin(); - it != m_playerTeamPrototypes.end(); ++it) - { - if ((*it)->hasAnyBuildFacility()) - return true; - } - return false; -} - -//============================================================================= -void Player::updateTeamStates() -{ - for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin(); - it != m_playerTeamPrototypes.end(); ++it) - { - (*it)->updateState(); - } -} - -//============================================================================= -Bool Player::isLocalPlayer() const -{ - return this == ThePlayerList->getLocalPlayer(); -} - -//============================================================================= -void Player::setListInScoreScreen(Bool listInScoreScreen) -{ - m_listInScoreScreen = listInScoreScreen; -} - -//============================================================================= -Bool Player::getListInScoreScreen() -{ - return m_listInScoreScreen; -} - -//============================================================================= -UnsignedInt Player::getSupplyBoxValue() -{ - /// @todo This would be the hookup for difficulty level modifiers and special economy buildings - return TheGlobalData->m_baseValuePerSupplyBox; -} - -//============================================================================= -Real Player::getProductionCostChangePercent( AsciiString buildTemplateName ) const -{ - ProductionChangeMap::const_iterator it = m_productionCostChanges.find(NAMEKEY(buildTemplateName)); - if (it != m_productionCostChanges.end()) - { - return (*it).second; - } - - return 0.0f; -} - -//============================================================================= -Real Player::getProductionTimeChangePercent( AsciiString buildTemplateName ) const -{ - ProductionChangeMap::const_iterator it = m_productionTimeChanges.find(NAMEKEY(buildTemplateName)); - if (it != m_productionTimeChanges.end()) - { - return (*it).second; - } - - return 0.0f; -} - -//============================================================================= -VeterancyLevel Player::getProductionVeterancyLevel( AsciiString buildTemplateName ) const -{ - NameKeyType templateNameKey = NAMEKEY(buildTemplateName); - ProductionVeterancyMap::const_iterator it = m_productionVeterancyLevels.find(templateNameKey); - if (it != m_productionVeterancyLevels.end()) - { - return (*it).second; - } - - return LEVEL_FIRST; -} - -//============================================================================= -void Player::friend_setSkillset(Int skillSet) -{ - if (m_ai) { - m_ai->selectSkillset(skillSet); - } -} - -//============================================================================= -void Player::setUnitsShouldHunt(Bool unitsShouldHunt, CommandSourceType source) -{ - m_unitsShouldHunt = unitsShouldHunt; - - Coord3D pos; - ThePartitionManager->getMostValuableLocation(getPlayerIndex(), ALLOW_ENEMIES, VOT_CashValue, &pos); - for (PlayerTeamList::iterator it = m_playerTeamPrototypes.begin(); - it != m_playerTeamPrototypes.end(); ++it) { - for (DLINK_ITERATOR iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance()) { - Team *team = iter.cur(); - if (!team) { - continue; - } - - for (DLINK_ITERATOR iterObj = team->iterate_TeamMemberList(); !iterObj.done(); iterObj.advance()) { - Object *obj = iterObj.cur(); - if (!obj) { - continue; - } - - KindOfMaskType disqualifyingKindofs; - disqualifyingKindofs.set(KINDOF_DOZER); - disqualifyingKindofs.set(KINDOF_HARVESTER); - disqualifyingKindofs.set(KINDOF_IGNORES_SELECT_ALL); - - if (obj->isAnyKindOf( disqualifyingKindofs )) { - continue; // Harvesters, dozers etc. - } - - obj->leaveGroup(); - AIUpdateInterface *ai = obj->getAIUpdateInterface(); - if (ai) { - if (unitsShouldHunt) { - ai->aiHunt(source); - } else { - ai->aiIdle(source); - } - } - } - } - } -} - -//============================================================================= -void Player::killPlayer() -{ - PlayerTeamList::iterator it = m_playerTeamPrototypes.begin(); - for (; it != m_playerTeamPrototypes.end(); ++it) { - for (DLINK_ITERATOR iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance()) { - Team *team = iter.cur(); - if (!team) { - continue; - } - team->evacuateTeam(); // force containers on team to dump contents - } - } - - m_isPlayerDead = TRUE; // this is so OCLs don't ever again spawn useful units for us. - - for (it = m_playerTeamPrototypes.begin(); it != m_playerTeamPrototypes.end(); ++it) { - for (DLINK_ITERATOR iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance()) { - Team *team = iter.cur(); - if (!team) { - continue; - } - team->killTeam(); - } - } - if (TheGameLogic->isInSinglePlayerGame()) { - if (getPlayerType()==PLAYER_COMPUTER) { - // This is an AI player in a solo mission - leave him alive so he can be used later. jba. - m_isPlayerDead = FALSE; // this is so we can later spawn useful units for us. - return; - } - } - if (isLocalPlayer() && !TheGameLogic->isInShellGame()) - { - // TheSuperHackers @bugfix helmutbuhler 29/03/2025 - // Avoid multiplayer mismatch on surrender in team games when owning a base structure that has - // been cleared of infantry before, by disabling this bugged logic. - // - // Note that becomingLocalPlayer calls recalcApparentControllingPlayer on all objects with a - // contain, which does two things: - // 1. Reset the teams of all objects with empty contains - // 2. Update m_hideGarrisonedStateFromNonallies - // - // Likely, the original intent was to reveal hidden garrisoned buildings for the new observer. - // But this does not appear to work anyway, so this call is useless. - // - // There is another bug: The Contain modules keep track of the object's team before any units - // got inside. And that team does not get updated when the player is killed and the units - // transfer to another team. That means resetting the team sets it to neutral, and when this - // is done only for the local player, then a mismatch occurs. - // - // When fixing disguises for observers or fixing the team bug in the Contain classes, then this - // code can be used again. -#if 0 - becomingLocalPlayer(TRUE); // recalc disguises, etc -#endif - - if (TheControlBar ) - { - if (isPlayerActive()) - { - TheControlBar->setControlBarSchemeByPlayer(this); - } - else - { - TheControlBar->setControlBarSchemeByPlayerTemplate(ThePlayerTemplateStore->findPlayerTemplate(NAMEKEY("FactionObserver"))); - } - } - - } - - m_money.withdraw(m_money.countMoney()); // force $$$ to 0 on death -} - -//============================================================================= -void Player::setObjectsEnabled(AsciiString templateTypeToAffect, Bool enable) -{ - for (PlayerTeamList::iterator it = m_playerTeamPrototypes.begin(); - it != m_playerTeamPrototypes.end(); ++it) { - for (DLINK_ITERATOR iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance()) { - Team *team = iter.cur(); - if (!team) { - continue; - } - - for (DLINK_ITERATOR iterObj = team->iterate_TeamMemberList(); !iterObj.done(); iterObj.advance()) { - Object *obj = iterObj.cur(); - if (!obj) { - continue; - } - - if (obj->getTemplate()->getName().compare(templateTypeToAffect) == 0) - { - obj->setScriptStatus( OBJECT_STATUS_SCRIPT_DISABLED, !enable ); - } - } - } - } -} - -//============================================================================= -static void cancelUpgradeInProduction(Object* obj, void* userData) -{ - const UpgradeTemplate* upgradeTemplate = static_cast(userData); - ProductionUpdateInterface* pui = ProductionUpdate::getProductionUpdateInterfaceFromObject(obj); - - if (pui && pui->isUpgradeInQueue(upgradeTemplate)) - { - pui->cancelUpgrade(upgradeTemplate); - } -} - -//============================================================================= -void Player::transferAssetsFromThat(Player *that) -{ - Team *defaultTeam = getDefaultTeam(); - if (!defaultTeam) { - return; - } - -#if !RETAIL_COMPATIBLE_CRC - // TheSuperHackers @bugfix Stubbjax 03/02/2026 Cancel any in-progress player upgrades 'that' - // player currently has in progress that 'this' player already has in progress or completed. - std::vector upgradesToCancel; - for (Upgrade* upgrade = that->m_upgradeList; upgrade; upgrade = upgrade->friend_getNext()) - { - const UpgradeTemplate* upgradeTemplate = upgrade->getTemplate(); - - if (upgrade->getStatus() == UPGRADE_STATUS_IN_PRODUCTION && - upgradeTemplate->getUpgradeType() == UPGRADE_TYPE_PLAYER && - (hasUpgradeComplete(upgradeTemplate) || hasUpgradeInProduction(upgradeTemplate))) - { - upgradesToCancel.push_back(upgradeTemplate); - } - } - - for (std::vector::iterator cancelIt = upgradesToCancel.begin(); cancelIt != upgradesToCancel.end(); ++cancelIt) - { - const UpgradeTemplate* upgradeTemplate = *cancelIt; - that->iterateObjects(cancelUpgradeInProduction, const_cast(upgradeTemplate)); - } - - // TheSuperHackers @bugfix Stubbjax 03/02/2026 Ensure the in-progress upgrade mask is copied from 'that' - // player to 'this' player to prevent duplicate player upgrades being purchased. - m_upgradesInProgress.set(that->m_upgradesInProgress); -#endif - - std::list objsToTransfer; - - // let's not transfer beacons - const ThingTemplate *beaconTemplate = TheThingFactory->findTemplate( that->getPlayerTemplate()->getBeaconTemplate() ); - - // transfer all his units. - for (PlayerTeamList::iterator it = that->m_playerTeamPrototypes.begin(); - it != that->m_playerTeamPrototypes.end(); ++it) - { - for (DLINK_ITERATOR iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance()) - { - Team *team = iter.cur(); - if (!team) - { - continue; - } - - for (DLINK_ITERATOR iterObj = team->iterate_TeamMemberList(); !iterObj.done(); iterObj.advance()) - { - Object *obj = iterObj.cur(); - if (!obj || obj->getTemplate()->isEquivalentTo(beaconTemplate)) // don't transfer nullptr objs or beacons - { - continue; - } - objsToTransfer.push_back(obj); - } - } - } - - for (std::list::iterator itObjs = objsToTransfer.begin(); itObjs != objsToTransfer.end(); ++itObjs) { - (*itObjs)->setTeam(defaultTeam); - } - - // transfer all his money - UnsignedInt allMoney = that->getMoney()->countMoney(); - that->getMoney()->withdraw(allMoney); - getMoney()->deposit(allMoney, TRUE, FALSE); -} - -//============================================================================= -void Player::garrisonAllUnits(CommandSourceType source) -{ - PartitionFilterAcceptByKindOf f1(MAKE_KINDOF_MASK(KINDOF_STRUCTURE), KINDOFMASK_NONE); - PartitionFilter *filters[] = { &f1, nullptr }; - - Coord3D pos = {50.0, 50.0, 50.0}; -/// @todo srj -- we should really use iterateAllObjects() here instead, but I have no time to -// test such a change... make someday - ObjectIterator *iterBuilding = ThePartitionManager->iterateObjectsInRange(&pos, 1e9f, FROM_CENTER_3D, filters, ITER_SORTED_NEAR_TO_FAR); - MemoryPoolObjectHolder hold(iterBuilding); - - for (PlayerTeamList::iterator it = m_playerTeamPrototypes.begin(); - it != m_playerTeamPrototypes.end(); ++it) { - for (DLINK_ITERATOR iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance()) { - Team *team = iter.cur(); - if (!team) { - continue; - } - - for (DLINK_ITERATOR iterObj = team->iterate_TeamMemberList(); !iterObj.done(); iterObj.advance()) { - Object *obj = iterObj.cur(); - if (!obj) { - continue; - } - - AIUpdateInterface *ai = obj->getAIUpdateInterface(); - if (!ai) { - continue; - } - - for (Object *theBuilding = iterBuilding->first(); theBuilding; theBuilding = iterBuilding->next()) - { - ContainModuleInterface *contain = theBuilding->getContain(); - if (contain) - { - PlayerMaskType player = contain->getPlayerWhoEntered(); - if (!((player == 0) || (player == obj->getControllingPlayer()->getPlayerMask()))) { - continue; - } - } - if( !TheActionManager->canEnterObject( obj, theBuilding, source, CHECK_CAPACITY ) ) - { - continue; - } - - ai->aiEnter(theBuilding, source); - } - } - } - } -} - -//============================================================================= -void Player::ungarrisonAllUnits(CommandSourceType source) -{ - for (PlayerTeamList::iterator it = m_playerTeamPrototypes.begin(); - it != m_playerTeamPrototypes.end(); ++it) { - for (DLINK_ITERATOR iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance()) { - Team *team = iter.cur(); - if (!team) { - continue; - } - - for (DLINK_ITERATOR iterObj = team->iterate_TeamMemberList(); !iterObj.done(); iterObj.advance()) { - Object *obj = iterObj.cur(); - if (!obj) { - continue; - } - - AIUpdateInterface *ai = obj->getAIUpdateInterface(); - if (!ai) { - continue; - } - - // Tell everything that has stuff in it to kick them all out. You can't tell the people to get - // out of what they are in, because they may not know, or they may be two transports deep, and their - // transport may not know where they are. - // And check for building so you don't unload transports in the ungarrison command - if( obj->isKindOf( KINDOF_STRUCTURE ) ) - ai->aiEvacuate( FALSE, source); - } - } - } -} - - -//============================================================================= -void Player::setUnitsShouldIdleOrResume(Bool idle) -{ - for (PlayerTeamList::iterator it = m_playerTeamPrototypes.begin(); - it != m_playerTeamPrototypes.end(); ++it) - { - for (DLINK_ITERATOR iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance()) - { - Team *team = iter.cur(); - if (!team) - continue; - - for (DLINK_ITERATOR iterObj = team->iterate_TeamMemberList(); !iterObj.done(); iterObj.advance()) - { - Object *obj = iterObj.cur(); - if (!obj) - continue; - - if (obj->isKindOf(KINDOF_STRUCTURE)) - continue; - - AIUpdateInterface *ai = obj->getAIUpdateInterface(); - if (!ai) - continue; - - if (idle) - { - // force it to move to its position to make it stop. - ai->aiMoveToPosition(obj->getPosition(), CMD_FROM_SCRIPT); - } - else - { - // Here is the special bit for this exit style, force wanting on SupplyTruck types - if (ai->isIdle()) - { - SupplyTruckAIInterface* supplyTruckAI = ai->getSupplyTruckAIInterface(); - if( supplyTruckAI ) - supplyTruckAI->setForceWantingState(true); - } - } - } - } - } -} - -//------------------------------------------------------------------------------- -void sellBuildings( Object *obj, void *userData ) -{ - if( obj->isFactionStructure() || obj->isKindOf( KINDOF_COMMANDCENTER ) || obj->isKindOf( KINDOF_FS_POWER ) ) - { - TheBuildAssistant->sellObject( obj ); - } -} - -//============================================================================= -void Player::sellEverythingUnderTheSun() -{ -#if RTS_GENERALS && RETAIL_COMPATIBLE_CRC - for (PlayerTeamList::iterator it = m_playerTeamPrototypes.begin(); - it != m_playerTeamPrototypes.end(); ++it) { - for (DLINK_ITERATOR iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance()) { - Team *team = iter.cur(); - if (!team) { - continue; - } - - for (DLINK_ITERATOR iterObj = team->iterate_TeamMemberList(); !iterObj.done(); iterObj.advance()) { - Object *obj = iterObj.cur(); - if (!obj) { - continue; - } - - // sell the object - TheBuildAssistant->sellObject( obj ); - } - } - } -#else - iterateObjects( sellBuildings, nullptr ); -#endif -} - - -//============================================================================= -Bool Player::allowedToBuild(const ThingTemplate *tmplate) const -{ - if (!m_canBuildBase && tmplate->isKindOf(KINDOF_STRUCTURE)) { - return false; - } - - if (!m_canBuildUnits && !tmplate->isKindOf(KINDOF_STRUCTURE)) { - return false; - } - - return true; -} - -//============================================================================= -void Player::buildSpecificTeam( TeamPrototype *teamProto) -{ - if (m_ai) - { - // Do a priority build. - m_ai->buildSpecificAITeam(teamProto, true); - } -} - -//============================================================================= -void Player::buildBaseDefense(Bool flank) -{ - if (m_ai) - { - // Do a priority build. - m_ai->buildAIBaseDefense(flank); - } -} - -//============================================================================= -void Player::buildBaseDefenseStructure(const AsciiString &thingName, Bool flank) -{ - if (m_ai) - { - // Do a priority build. - m_ai->buildAIBaseDefenseStructure(thingName, flank); - } -} - -//============================================================================= -void Player::buildSpecificBuilding(const AsciiString &thingName) -{ - if (m_ai) - { - // Do a priority build. - m_ai->buildSpecificAIBuilding(thingName); - } -} - -//============================================================================= -void Player::buildBySupplies(Int minimumCash, const AsciiString &thingName) -{ - if (m_ai) - { - m_ai->buildBySupplies(minimumCash, thingName); - } -} - -//============================================================================= -void Player::buildSpecificBuildingNearestTeam( const AsciiString &thingName, const Team *team ) -{ - if( m_ai ) - { - m_ai->buildSpecificBuildingNearestTeam( thingName, team ); - } -} - -//============================================================================= -void Player::buildUpgrade( const AsciiString &upgrade) -{ - if (m_ai) - { - m_ai->buildUpgrade(upgrade); - } -} - -//============================================================================= -void Player::recruitSpecificTeam( TeamPrototype *teamProto, Real recruitRadius) -{ - if (m_ai) - { - // Do a priority build. - m_ai->recruitSpecificAITeam(teamProto, recruitRadius); - } -} - - -//============================================================================= -// Calculates the closest construction zone location based on a template. Gets plassed to aiPlayer -//============================================================================= -Bool Player::calcClosestConstructionZoneLocation( const ThingTemplate *constructTemplate, Coord3D *location ) -{ - if( m_ai ) - { - return m_ai->calcClosestConstructionZoneLocation( constructTemplate, location ); - } - - return FALSE; -} - -//============================================================================= -void Player::doBountyForKill(const Object* killer, const Object* victim) -{ - if (!killer || !victim) - return; - - // srj sez: per dustin, no experience (et al) for killing things under construction. - if (victim->testStatus(OBJECT_STATUS_UNDER_CONSTRUCTION)) - return; - - Int costToBuild = victim->getTemplate()->calcCostToBuild(victim->getControllingPlayer()); -#if RETAIL_COMPATIBLE_CRC - Int bounty = REAL_TO_INT_CEIL(costToBuild * m_cashBountyPercent); -#else - // TheSuperHackers @bugfix Stubbjax 20/02/2026 Subtract epsilon to ensure bounty is rounded up correctly. - Int bounty = WWMath::Ceil((costToBuild * m_cashBountyPercent) - WWMATH_EPSILON); -#endif - - if( bounty ) - { - - getMoney()->deposit( bounty ); - m_scoreKeeper.addMoneyEarned( bounty ); - - //Display cash income floating over the recipient. - UnicodeString moneyString; - moneyString.format( TheGameText->fetch( "GUI:AddCash" ), bounty ); - Coord3D pos; - pos.zero(); - pos.add( *killer->getPosition() ); - pos.z += 10.0f; //add a little z to make it show up above the unit. - TheInGameUI->addFloatingText( moneyString, &pos, GameMakeColor( 255, 255, 0, 255 ) ); - } -} - -//============================================================================= -Bool Player::hasPrereqsForScience(ScienceType t) const -{ - return TheScienceStore->playerHasPrereqsForScience(this, t); -} - -//============================================================================= -/// returns TRUE if the player gained/lost levels as a result. -Bool Player::addSkillPoints(Int delta) -{ - delta = REAL_TO_INT_CEIL(m_skillPointsModifier * INT_TO_REAL(delta)); - - if( delta == 0 ) - return false; - - Int levelCap = min( TheGameLogic->getRankLevelLimit(), TheRankInfoStore->getRankLevelCount() ); - Int pointCap = TheRankInfoStore->getRankInfo(levelCap)->m_skillPointsNeeded; // Cap at lowest point of cap level, not highest. - - Bool levelGained = FALSE; - m_skillPoints = min( pointCap, (m_skillPoints + delta) ); - while( m_skillPoints >= m_levelUp ) - { - // LevelUp gets increased as a side effect of setRankLevel, and this won't infinitely loop, - // because when there are no more levels to be gained, m_levelUp is set to INT_MAX. - setRankLevel( m_rankLevel + 1 ); - levelGained = TRUE; - } - - return levelGained; -} - -//============================================================================= -/// returns TRUE if the player gained/lost levels as a result. -Bool Player::addSkillPointsForKill(const Object* killer, const Object* victim) -{ - if (!killer || !victim) - return false; - - // srj sez: per dustin, no experience (et al) for killing things under construction. - if (victim->testStatus(OBJECT_STATUS_UNDER_CONSTRUCTION)) - return false; - - Int victimLevel = victim->getVeterancyLevel(); - Int skillValue = victim->getTemplate()->getSkillPointValue(victimLevel); - - return addSkillPoints(skillValue); -} - -//============================================================================= -void Player::resetSciences() -{ - m_sciences.clear(); - - if (getPlayerTemplate()) - m_sciences = getPlayerTemplate()->getIntrinsicSciences(); - - for (Int i = 1; i <= m_rankLevel; ++i) - { - const RankInfo* rank = TheRankInfoStore->getRankInfo(i); - if (rank) - { - for (ScienceVec::const_iterator it = rank->m_sciencesGranted.begin(); it != rank->m_sciencesGranted.end(); ++it) - { - addScience(*it); - } - } - } - - for (ScienceVec::const_iterator it = m_sciences.begin(); it != m_sciences.end(); ++it) - TheScriptEngine->notifyOfAcquiredScience(getPlayerIndex(), *it); -} - -//============================================================================= -/// returns TRUE if sciences were gained/lost. -Bool Player::addScience(ScienceType science) -{ - if (hasScience(science)) - return false; - - //DEBUG_LOG(("Adding Science %s",TheScienceStore->getInternalNameForScience(science).str())); - - m_sciences.push_back(science); - - // 'wake up' any special powers controlled by, well, stuff - for (PlayerTeamList::iterator it = m_playerTeamPrototypes.begin(); - it != m_playerTeamPrototypes.end(); ++it) - { - for (DLINK_ITERATOR iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance()) - { - Team *team = iter.cur(); - if (!team) - continue; - - for (DLINK_ITERATOR iterObj = team->iterate_TeamMemberList(); !iterObj.done(); iterObj.advance()) - { - Object *obj = iterObj.cur(); - if (!obj) - continue; - - for (BehaviorModule** m = obj->getBehaviorModules(); *m; ++m) - { - SpecialPowerModuleInterface* sp = (*m)->getSpecialPower(); - if (!sp) - continue; - - if (sp->getRequiredScience() == science) - { - // Turn on the power, and set it to be instantly ready, because that is cool. - sp->onSpecialPowerCreation(); - sp->setReadyFrame( TheGameLogic->getFrame() ); - } - } - } - } - - TheControlBar->markUIDirty();// Refresh the UI to show new cameos, etc - - } - - // notify the script engine - TheScriptEngine->notifyOfAcquiredScience(getPlayerIndex(), science); - - return true; -} - -//============================================================================= -void Player::addSciencePurchasePoints(Int delta) -{ - //DEBUG_LOG(("Adding SciencePurchasePoints %d -> %d",m_sciencePurchasePoints,m_sciencePurchasePoints+delta)); - Int oldSPP = m_sciencePurchasePoints; - m_sciencePurchasePoints += delta; - if (m_sciencePurchasePoints < 0) - m_sciencePurchasePoints = 0; - - if (oldSPP != m_sciencePurchasePoints && TheControlBar != nullptr) - TheControlBar->onPlayerSciencePurchasePointsChanged(this); - -} - -//============================================================================= -Bool Player::attemptToPurchaseScience(ScienceType science) -{ - if (!isCapableOfPurchasingScience(science)) - { - DEBUG_CRASH(("isCapableOfPurchasingScience: need other prereqs/points to purchase, request is ignored!")); - return false; - } - - Int cost = TheScienceStore->getSciencePurchaseCost(science); - addSciencePurchasePoints(-cost); - addScience(science); - - getAcademyStats()->recordGeneralsPointsSpent( cost ); - - if( ThePlayerList->getLocalPlayer() == this ) - { - TheControlBar->markUIDirty(); - } - - return true; -} - -//============================================================================= -Bool Player::grantScience(ScienceType science) -{ - if (!TheScienceStore->isScienceGrantable(science)) - { - DEBUG_CRASH(("Cannot grant science %s, since it is marked as nonGrantable.",TheScienceStore->getInternalNameForScience(science).str())); - return false; // it's not grantable, so tough, can't have it, even via this method. - } - - return addScience(science); -} - -//============================================================================= -Bool Player::isCapableOfPurchasingScience(ScienceType science) const -{ - if (science == SCIENCE_INVALID) - { - return false; - } - - if (hasScience(science)) - { - return false; - } - - if( isScienceDisabled( science ) || isScienceHidden( science ) ) - { - return false; - } - - if (!hasPrereqsForScience(science)) - { - return false; - } - - Int cost = TheScienceStore->getSciencePurchaseCost(science); - // purchase cost of zero means "not purchasable!" - if (cost == 0 || cost > getSciencePurchasePoints()) - { - return false; - } - - return true; -} - -//============================================================================= -void Player::resetRank() -{ - m_rankLevel = 1; - m_skillPoints = 0; - const RankInfo* nextRank = TheRankInfoStore->getRankInfo(m_rankLevel+1); - m_levelUp = nextRank ? nextRank->m_skillPointsNeeded : INT_MAX; - m_levelDown = 0; - m_sciences.clear(); - m_sciencePurchasePoints = getPlayerTemplate() ? getPlayerTemplate()->getIntrinsicSciencePurchasePoints() : 0; - const RankInfo* curRank = TheRankInfoStore->getRankInfo(m_rankLevel); - m_sciencePurchasePoints += curRank ? curRank->m_sciencePurchasePointsGranted : 0; - m_generalName = TheGameText? TheGameText->fetch("SCIENCE:GeneralName"):UnicodeString::TheEmptyString; - resetSciences(); -} - -//============================================================================= -/// returns TRUE if rank level really changed. -Bool Player::setRankLevel(Int newLevel) -{ - if (newLevel < 1) - newLevel = 1; - else if (newLevel > TheRankInfoStore->getRankLevelCount()) - newLevel = TheRankInfoStore->getRankLevelCount(); - - if (newLevel > TheGameLogic->getRankLevelLimit()) - newLevel = TheGameLogic->getRankLevelLimit(); - - if (newLevel == m_rankLevel) - return false; - - //DEBUG_LOG(("Set Rank Level %d -> %d",m_rankLevel,newLevel)); - - Int oldSPP = m_sciencePurchasePoints; - - if (newLevel < m_rankLevel) - { - // when downgrading in rank, you lose everything. oh well... - resetRank(); - } - - for (Int i = m_rankLevel + 1; i <= newLevel; ++i) - { - const RankInfo* rank = TheRankInfoStore->getRankInfo(i); - DEBUG_ASSERTCRASH(rank, ("rank should never be null here")); - if (rank) - { - //addSciencePurchasePoints(rank->m_sciencePurchasePointsGranted); - // do this directly, so we can defer the UI notification till the end - m_sciencePurchasePoints += rank->m_sciencePurchasePointsGranted; - if (m_sciencePurchasePoints < 0) - m_sciencePurchasePoints = 0; - - if (m_skillPoints < rank->m_skillPointsNeeded) - m_skillPoints = rank->m_skillPointsNeeded; - - for (ScienceVec::const_iterator it = rank->m_sciencesGranted.begin(); it != rank->m_sciencesGranted.end(); ++it) - { - addScience(*it); - } - - m_levelDown = rank->m_skillPointsNeeded; - } - } - - const RankInfo* nextRank = TheRankInfoStore->getRankInfo(newLevel + 1); - m_levelUp = nextRank ? nextRank->m_skillPointsNeeded : INT_MAX; - m_rankLevel = newLevel; - - DEBUG_ASSERTCRASH(m_skillPoints >= m_levelDown && m_skillPoints < m_levelUp, ("hmm, wrong")); - //DEBUG_LOG(("Rank %d, Skill %d, down %d, up %d",m_rankLevel,m_skillPoints, m_levelDown, m_levelUp)); - - if (TheControlBar != nullptr) - { - if( m_levelUp ) - { - //Play an EVA sound - if (isLocalPlayer()) - TheEva->setShouldPlay( EVA_GeneralLevelUp ); - } - - // notify of rank-change first - TheControlBar->onPlayerRankChanged(this); - - // then of SPP change, if any - if (oldSPP != m_sciencePurchasePoints) - TheControlBar->onPlayerSciencePurchasePointsChanged(this); - } - - return true; -} - -//============================================================================= -Bool Player::hasScience(ScienceType t) const -{ - return std::find(m_sciences.begin(), m_sciences.end(), t) != m_sciences.end(); -} - -//============================================================================= -Bool Player::isScienceDisabled( ScienceType t ) const -{ - return std::find( m_sciencesDisabled.begin(), m_sciencesDisabled.end(), t ) != m_sciencesDisabled.end(); -} - -//============================================================================= -Bool Player::isScienceHidden( ScienceType t ) const -{ - return std::find( m_sciencesHidden.begin(), m_sciencesHidden.end(), t ) != m_sciencesHidden.end(); -} - -//============================================================================= -void Player::setScienceAvailability( ScienceType science, ScienceAvailabilityType type ) -{ - ScienceType sType; - ScienceVec::iterator it; - Bool found = false; - - //First remove it from disabled sciences if it's there. - for( it = m_sciencesDisabled.begin(); it != m_sciencesDisabled.end(); ++it ) - { - sType = *it; - if( sType == science ) - { - m_sciencesDisabled.erase( it ); - found = true; - break; - } - } - if( !found ) - { - //If still not found, remove it from hidden sciences if it's there. - for( it = m_sciencesHidden.begin(); it != m_sciencesHidden.end(); ++it ) - { - sType = *it; - if( sType == science ) - { - m_sciencesHidden.erase( it ); - found = true; - break; - } - } - } - - //At this point, this science shouldn't be disabled nor hidden! - if( type == SCIENCE_DISABLED ) - { - //Add science to disabled vec. - m_sciencesDisabled.push_back( science ); - } - else if( type == SCIENCE_HIDDEN ) - { - //Add science to hidden vec. - m_sciencesHidden.push_back( science ); - } - else if( type == SCIENCE_AVAILABLE ) - { - //Do nothing, because being available means that the science isn't in one of the hidden or disabled vecs. - } -} - -//============================================================================= -ScienceAvailabilityType Player::getScienceAvailabilityTypeFromString( const AsciiString& name ) -{ - for( Int i = 0; i < SCIENCE_AVAILABILITY_COUNT; i++ ) - { - if( !name.compareNoCase( ScienceAvailabilityNames[ i ] ) ) - { - return (ScienceAvailabilityType)i; - } - } - return SCIENCE_AVAILABILITY_INVALID; -} - -namespace -{ - // ------------------------------------------------------------------------------------------------ - // For countExisting - struct TypeCountData - { - UnsignedInt count; - const ThingTemplate *type; - NameKeyType linkKey; - Bool checkProductionInterface; - }; -} - -// ------------------------------------------------------------------------------------------------ -/** Count all the units of a given type that exist or are in any production queues for a player */ -// ------------------------------------------------------------------------------------------------ -static void countExisting( Object *obj, void *userData ) -{ - // Don't care about dead objects - if ( obj->isEffectivelyDead() ) - return; - - TypeCountData *typeCountData = (TypeCountData *)userData; - - // Compare templates - if ( ( typeCountData->type && typeCountData->type->isEquivalentTo( obj->getTemplate() ) ) || - ( typeCountData->linkKey != NAMEKEY_INVALID && obj->getTemplate() != nullptr && typeCountData->linkKey == obj->getTemplate()->getMaxSimultaneousLinkKey() ) ) - { - typeCountData->count++; - } - - // Also consider objects that have a production update interface - if ( typeCountData->checkProductionInterface ) - { - ProductionUpdateInterface *pui = ProductionUpdate::getProductionUpdateInterfaceFromObject( obj ); - if( pui ) - { - // add the count of this type that are in the queue - typeCountData->count += pui->countUnitTypeInQueue( typeCountData->type ); - } - } -} - -//============================================================================= -// Make sure that building another of this unit/structure/object won't exceed MaxSimultaneousOfType() -Bool Player::canBuildMoreOfType( const ThingTemplate *whatToBuild ) const -{ - // make sure we're not maxed out for this type of unit. - UnsignedInt maxSimultaneousOfType = whatToBuild->getMaxSimultaneousOfType(); - if (maxSimultaneousOfType != 0) - { - - TypeCountData typeCountData; - typeCountData.count = 0; - typeCountData.type = whatToBuild; - typeCountData.linkKey = whatToBuild->getMaxSimultaneousLinkKey(); - // Assumption: Things with a KINDOF_STRUCTURE flag can never be built from - // a factory (ProductionUpdateInterface), because the building can't move - // out of the factory. When we do our Starcraft port and have flying Terran - // buildings, we'll have to change this ;-) - // Remember: To ASSUME makes an ASS out of U and ME. - typeCountData.checkProductionInterface = !whatToBuild->isKindOf( KINDOF_STRUCTURE ); - - iterateObjects( countExisting, &typeCountData ); - if( typeCountData.count >= maxSimultaneousOfType ) - return false; - } - return true; -} - -//============================================================================= -Bool Player::canBuild(const ThingTemplate *tmplate) const -{ - if (!tmplate) - return false; - - if (!allowedToBuild(tmplate)) - return false; - - if (tmplate->getBuildable() == BSTATUS_NO) - return false; - - if (tmplate->getBuildable() == BSTATUS_IGNORE_PREREQUISITES) - return true; - - if (tmplate->getBuildable() == BSTATUS_ONLY_BY_AI && getPlayerType() != PLAYER_COMPUTER) - return false; - - // else BSTATUS tmplate->getBuildable() == BSTATUS_YES - { - - // we must satisfy all of the prereqs - Bool prereqsOK = true; - for (Int i = 0; i < tmplate->getPrereqCount(); i++) - { - const ProductionPrerequisite *pre = tmplate->getNthPrereq(i); - if (pre->isSatisfied(this) == false ) - prereqsOK = false; - } - -#if defined(RTS_DEBUG) - if (ignoresPrereqs()) - prereqsOK = true; -#endif - - if (!prereqsOK) - return false; - - } - -#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) - if ( !canBuildMoreOfType( tmplate ) ) - return false; -#endif - - - return true; -} - -//================================================================================================= -Bool Player::canAffordBuild( const ThingTemplate *whatToBuild ) const -{ - // make sure we have enough money to build this - const Money *money = getMoney(); - if( whatToBuild->calcCostToBuild( this ) <= money->countMoney() ) - { - return true; - } - return false; -} - -//================================================================================================= -void Player::deleteUpgradeList() -{ - Upgrade *next; - - // delete all of the upgrades we have - while( m_upgradeList ) - { - - next = m_upgradeList->friend_getNext(); - deleteInstance(m_upgradeList); - m_upgradeList = next; - - } - - // This doesn't call removeUpgrade, so clear these ourselves. - m_upgradesInProgress.clear(); - m_upgradesCompleted.clear(); - -} - -//================================================================================================= -/** Find an upgrade in our list of upgrades with matching name key */ -//================================================================================================= -Upgrade *Player::findUpgrade( const UpgradeTemplate *upgradeTemplate ) -{ - Upgrade *upgrade; - - for( upgrade = m_upgradeList; upgrade; upgrade = upgrade->friend_getNext() ) - if( upgrade->getTemplate() == upgradeTemplate ) - return upgrade; - - return nullptr; - -} - -//================================================================================================= -/** Does the player have this completed upgrade */ -//================================================================================================= -Bool Player::hasUpgradeComplete( const UpgradeTemplate *upgradeTemplate ) const -{ - const UpgradeMaskType& testMask = upgradeTemplate->getUpgradeMask(); - return hasUpgradeComplete( testMask ); -} - -//================================================================================================= -/** - Does the player have this completed upgrade. This form is exposed so Objects can do quick lookups. -*/ -//================================================================================================= -Bool Player::hasUpgradeComplete( const UpgradeMaskType& testMask ) const -{ - return m_upgradesCompleted.testForAll( testMask ); -} - -//================================================================================================= -/** Does the player have this upgrade In Production*/ -//================================================================================================= -Bool Player::hasUpgradeInProduction( const UpgradeTemplate *upgradeTemplate ) -{ - const UpgradeMaskType& testMask = upgradeTemplate->getUpgradeMask(); - return m_upgradesInProgress.testForAll( testMask ); -} - -//================================================================================================= -/** Give the player an upgrade or change status on an existing upgrade entry */ -//================================================================================================= -Upgrade *Player::addUpgrade( const UpgradeTemplate *upgradeTemplate, UpgradeStatusType status ) -{ - Upgrade *u = findUpgrade( upgradeTemplate ); - - // if no upgrade instance found, make a new one - if( u == nullptr ) - { - - // make new one - u = newInstance(Upgrade)( upgradeTemplate ); - - // tie to list - u->friend_setPrev( nullptr ); - u->friend_setNext( m_upgradeList ); - if( m_upgradeList ) - m_upgradeList->friend_setPrev( u ); - m_upgradeList = u; - - } - - // set the new status for the upgrade - u->setStatus( status ); - - // Update our Bitmasks - const UpgradeMaskType& newMask = upgradeTemplate->getUpgradeMask(); - if( status == UPGRADE_STATUS_IN_PRODUCTION ) - { - m_upgradesInProgress.set( newMask ); - } - else if( status == UPGRADE_STATUS_COMPLETE ) - { - m_upgradesInProgress.clear( newMask ); - m_upgradesCompleted.set( newMask ); - onUpgradeCompleted( upgradeTemplate ); - } - - if( ThePlayerList->getLocalPlayer() == this ) - { - TheControlBar->markUIDirty(); - } - - return u; - -} - -//================================================================================================= -/** - An upgrade just finished, do things like tell all objects to recheck UpgradeModules -*/ -void Player::onUpgradeCompleted( const UpgradeTemplate *upgradeTemplate ) -{ - for (PlayerTeamList::iterator it = m_playerTeamPrototypes.begin(); - it != m_playerTeamPrototypes.end(); ++it) - { - for (DLINK_ITERATOR iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance()) - { - Team *team = iter.cur(); - if( team == nullptr ) - { - continue; - } - for (DLINK_ITERATOR iterObj = team->iterate_TeamMemberList(); !iterObj.done(); iterObj.advance()) - { - Object *obj = iterObj.cur(); - if( obj == nullptr ) - { - continue; - } - // Dear copy-paste monkeys, the meat of this iterate-all-player-objects loop goes twixt the MEAT comments - - obj->updateUpgradeModules(); - - // end MEAT - } - } - } -} - -//================================================================================================= -/** Remove upgrade from a player */ -//================================================================================================= -void Player::removeUpgrade( const UpgradeTemplate *upgradeTemplate ) -{ - Upgrade *upgrade = findUpgrade( upgradeTemplate ); - - if( upgrade ) - { - if( upgrade->friend_getNext() ) - upgrade->friend_getNext()->friend_setPrev( upgrade->friend_getPrev() ); - if( upgrade->friend_getPrev() ) - upgrade->friend_getPrev()->friend_setNext( upgrade->friend_getNext() ); - else - m_upgradeList = upgrade->friend_getNext(); - - // Clear this upgrade's bits from our mind - const UpgradeMaskType& oldMask = upgradeTemplate->getUpgradeMask(); - m_upgradesInProgress.clear( oldMask ); - m_upgradesCompleted.clear( oldMask ); - - if( upgrade->getStatus() == UPGRADE_STATUS_COMPLETE ) - onUpgradeRemoved(); - - deleteInstance(upgrade); - - if( ThePlayerList->getLocalPlayer() == this ) - { - TheControlBar->markUIDirty(); - } - } -} - - -//------------------------------------------------------------------------------------------------- -Bool Player::okToPlayRadarEdgeSound() -{ - return ( - ! TheVictoryConditions->hasSinglePlayerBeenDefeated( this ) && - ! m_isPlayerDead && - ! TheInGameUI->isClientQuiet() && - TheGameLogic->isInGameLogicUpdate() && - TheGameLogic->getFrame() > 0 ); - -} - -//------------------------------------------------------------------------------------------------- -/** The parameter object has just acquired a radar */ -//------------------------------------------------------------------------------------------------- -void Player::addRadar( Bool disableProof ) -{ - Bool hadRadar = hasRadar(); - - // increment count - ++m_radarCount; - - if( disableProof ) - ++m_disableProofRadarCount;// Disable proof is also in the normal refcount - - if( !hadRadar && hasRadar() && okToPlayRadarEdgeSound() ) - { - // This player just got radar, so play the "You have Radar!" sound - AudioEventRTS soundToPlay = TheAudio->getMiscAudio()->m_radarOnlineSound; - soundToPlay.setPlayerIndex(getPlayerIndex()); - TheAudio->addAudioEvent(&soundToPlay); - } -} - -//------------------------------------------------------------------------------------------------- -/** The parameter object has is taking its radar away from the player */ -//------------------------------------------------------------------------------------------------- -void Player::removeRadar( Bool disableProof ) -{ - Bool hadRadar = hasRadar(); - - // decrement count - DEBUG_ASSERTCRASH( m_radarCount > 0, ("removeRadar: An Object is taking its radar away, but the player radar count says they don't have radar!") ); - --m_radarCount; - - if( disableProof ) - --m_disableProofRadarCount;// Disable proof is also in the normal refcount - - if( hadRadar && !hasRadar() && okToPlayRadarEdgeSound() ) - { - // This player just lost radar, so play the "You lost Radar!" sound - AudioEventRTS soundToPlay = TheAudio->getMiscAudio()->m_radarOfflineSound; - soundToPlay.setPlayerIndex(getPlayerIndex()); - TheAudio->addAudioEvent(&soundToPlay); - } -} - -//------------------------------------------------------------------------------------------------- -void Player::disableRadar() -{ - Bool hadRadar = hasRadar(); - m_radarDisabled = TRUE; - - if( hadRadar && - !hasRadar() && okToPlayRadarEdgeSound() ) - { - // This player just lost radar, so play the "You lost Radar!" sound - AudioEventRTS soundToPlay = TheAudio->getMiscAudio()->m_radarOfflineSound; - soundToPlay.setPlayerIndex(getPlayerIndex()); - TheAudio->addAudioEvent(&soundToPlay); - } -} - -//------------------------------------------------------------------------------------------------- -void Player::enableRadar() -{ - Bool hadRadar = hasRadar(); - m_radarDisabled = FALSE; - - if( !hadRadar && hasRadar() && okToPlayRadarEdgeSound() ) - { - // This player just got radar, so play the "You have Radar!" sound - AudioEventRTS soundToPlay = TheAudio->getMiscAudio()->m_radarOnlineSound; - soundToPlay.setPlayerIndex(getPlayerIndex()); - TheAudio->addAudioEvent(&soundToPlay); - } -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -Bool Player::hasRadar() const -{ - if( m_radarDisabled && (m_disableProofRadarCount == 0) ) - return FALSE;// Nope, no matter how many you have, if I say no, you don't have it - - // Otherwise, check if I actually do have it. - return m_radarCount > 0; -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------ -static void doPowerDisable( Object *obj, void *userData ) -{ - Bool disabling = *((Bool*)userData); - if( obj && obj->isKindOf(KINDOF_POWERED) ) - { - if( disabling ) - obj->setDisabled( DISABLED_UNDERPOWERED ); //set disabled has a pauseAllSpecialPowers that prevents double pausing - else - obj->clearDisabled( DISABLED_UNDERPOWERED ); - } -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -void Player::onPowerBrownOutChange( Bool brownOut ) -{ - // Everything that changes due to Player's power supply goes in here. - if( brownOut ) - disableRadar(); - else - enableRadar(); //This doesn't give radar necessarily, it just removes the restriction - - iterateObjects( doPowerDisable, &brownOut );// This function is so cool. -} - - - - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -// SEVERAL OBJECTS (LIKE MULTIPLE COMMAND CENTERS) MAY HAVE MATCHING SETS OF SPECIAL POWERS -// THIS KEEPS THEM IN SYNC SO IT LOOKS LIKE EACH SPECIAL POWER IS SHARED BETWEEN ALL - -void Player::addNewSharedSpecialPowerTimer( const SpecialPowerTemplate *temp, UnsignedInt frame ) -{ - - SpecialPowerReadyTimerType newTimer; - newTimer.m_templateID = temp->getID(); - newTimer.m_readyFrame = frame; - m_specialPowerReadyTimerList.push_back( newTimer ); - -} - -void Player::resetOrStartSpecialPowerReadyFrame( const SpecialPowerTemplate *temp ) -{ - - UnsignedInt lookupID = temp->getID(); - UnsignedInt now = TheGameLogic->getFrame(); - - SpecialPowerReadyTimerType *timer; - SpecialPowerReadyTimerListIterator it; - for( it = m_specialPowerReadyTimerList.begin(); it != m_specialPowerReadyTimerList.end(); ++it ) - { - timer = &(*it); - if ( timer->m_templateID == lookupID ) - { - timer->m_readyFrame = now + temp->getReloadTime(); - return; - } - } - - addNewSharedSpecialPowerTimer( temp, now ); -} - - -void Player::expressSpecialPowerReadyFrame( const SpecialPowerTemplate *temp, UnsignedInt frame ) -{ - SpecialPowerReadyTimerType *timer; - SpecialPowerReadyTimerListIterator it; - for( it = m_specialPowerReadyTimerList.begin(); it != m_specialPowerReadyTimerList.end(); ++it ) - { - timer = &(*it); - if ( timer->m_templateID == temp->getID() ) - { - timer->m_readyFrame = frame; - return; - } - } - - addNewSharedSpecialPowerTimer( temp, frame ); -} - - - - - -//------------------------------------------------------------------------------------------------- -UnsignedInt Player::getOrStartSpecialPowerReadyFrame( const SpecialPowerTemplate *temp) -{ - - UnsignedInt lookupID = temp->getID(); - UnsignedInt now = TheGameLogic->getFrame(); - - SpecialPowerReadyTimerType *timer; - SpecialPowerReadyTimerListIterator it; - - - UnsignedInt count = 0; - UnsignedInt timerID = 0xfacade; - - for( it = m_specialPowerReadyTimerList.begin(); it != m_specialPowerReadyTimerList.end(); ++it ) - { - timer = &(*it); - ++count; - - timerID = timer->m_templateID; - - if ( timerID == lookupID ) - { - return timer->m_readyFrame; - } - } - - addNewSharedSpecialPowerTimer( temp, now ); - return now; - -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -void Player::friend_applyDifficultyBonusesForObject(Object* obj, Bool apply) const -{ - if (TheGameLogic->isInSinglePlayerGame()) - { - Real healthFactor = TheGlobalData->m_soloPlayerHealthBonusForDifficulty[getPlayerType()][getPlayerDifficulty()]; - if (healthFactor != 1.0f) - { - BodyModuleInterface* body = obj->getBodyModule(); - if (apply) - body->setMaxHealth(body->getMaxHealth() * healthFactor, PRESERVE_RATIO); - else - body->setMaxHealth(body->getMaxHealth() / healthFactor, PRESERVE_RATIO); - } - static const WeaponBonusConditionType wbonus[PLAYERTYPE_COUNT][DIFFICULTY_COUNT] = - { - { - WEAPONBONUSCONDITION_SOLO_HUMAN_EASY, - WEAPONBONUSCONDITION_SOLO_HUMAN_NORMAL, - WEAPONBONUSCONDITION_SOLO_HUMAN_HARD - }, - { - WEAPONBONUSCONDITION_SOLO_AI_EASY, - WEAPONBONUSCONDITION_SOLO_AI_NORMAL, - WEAPONBONUSCONDITION_SOLO_AI_HARD - } - }; - if (apply) - obj->setWeaponBonusCondition(wbonus[getPlayerType()][getPlayerDifficulty()]); - else - obj->clearWeaponBonusCondition(wbonus[getPlayerType()][getPlayerDifficulty()]); - } - -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -Bool Player::doesObjectQualifyForBattlePlan( Object *obj ) const -{ - if( m_battlePlanBonuses && obj ) - { - if( obj->isAnyKindOf( m_battlePlanBonuses->m_validKindOf ) ) - { - if( !obj->isAnyKindOf( m_battlePlanBonuses->m_invalidKindOf ) ) - { - return true; - } - } - } - return false; -} - -//------------------------------------------------------------------------------------------------- -void Player::changeBattlePlan( BattlePlanStatus plan, Int delta, const BattlePlanBonusesData *bonus ) -{ - DUMPBATTLEPLANBONUSES(bonus, this, nullptr); - Bool addBonus = false; - Bool removeBonus = false; - switch( plan ) - { - case PLANSTATUS_BOMBARDMENT: - { - m_bombardBattlePlans += delta; - if( m_bombardBattlePlans == 1 && delta == 1 ) - { - addBonus = true; - } - else if( m_bombardBattlePlans == 0 && delta == -1 ) - { - removeBonus = true; - } - break; - } - case PLANSTATUS_HOLDTHELINE: - { - m_holdTheLineBattlePlans += delta; - if( m_holdTheLineBattlePlans == 1 && delta == 1 ) - { - addBonus = true; - } - else if( m_holdTheLineBattlePlans == 0 && delta == -1 ) - { - removeBonus = true; - } - break; - } - case PLANSTATUS_SEARCHANDDESTROY: - { - m_searchAndDestroyBattlePlans += delta; - if( m_searchAndDestroyBattlePlans == 1 && delta == 1 ) - { - addBonus = true; - } - else if( m_searchAndDestroyBattlePlans == 0 && delta == -1 ) - { - removeBonus = true; - } - break; - } - } - if( addBonus ) - { - applyBattlePlanBonusesForPlayerObjects( bonus ); - } - else if( removeBonus ) - { - //First, inverse the bonuses - BattlePlanBonusesData invertedBonus = *bonus; - - invertedBonus.m_armorScalar = 1.0f / __max(bonus->m_armorScalar, 0.01f); - invertedBonus.m_sightRangeScalar = 1.0f / __max(bonus->m_sightRangeScalar, 0.01f); - if (invertedBonus.m_bombardment > 0) - { - invertedBonus.m_bombardment = -1; - } - if (invertedBonus.m_holdTheLine > 0) - { - invertedBonus.m_holdTheLine = -1; - } - if (invertedBonus.m_searchAndDestroy > 0) - { - invertedBonus.m_searchAndDestroy = -1; - } - - applyBattlePlanBonusesForPlayerObjects(&invertedBonus); - } -} - -//------------------------------------------------------------------------------------------------- -Int Player::getBattlePlansActiveSpecific( BattlePlanStatus plan ) const -{ - switch( plan ) - { - case PLANSTATUS_BOMBARDMENT: - { - return m_bombardBattlePlans; - } - case PLANSTATUS_HOLDTHELINE: - { - return m_holdTheLineBattlePlans; - } - case PLANSTATUS_SEARCHANDDESTROY: - { - return m_searchAndDestroyBattlePlans; - } - } - return 0; -} - -//------------------------------------------------------------------------------------------------ -static void localApplyBattlePlanBonusesToObject( Object *obj, void *userData ) -{ - const BattlePlanBonusesData* bonus = static_cast(userData); - Object *objectToValidate = obj; - Object *objectToModify = obj; - - DEBUG_LOG(("localApplyBattlePlanBonusesToObject() - looking at object %d (%s)", - (objectToValidate)?objectToValidate->getID():INVALID_ID, - (objectToValidate)?objectToValidate->getTemplate()->getName().str():"")); - - //First check if the obj is a projectile -- if so split the - //object so that the producer is validated, not the projectile. - Bool isProjectile = obj->isKindOf( KINDOF_PROJECTILE ); - if( isProjectile ) - { - objectToValidate = TheGameLogic->findObjectByID( obj->getProducerID() ); - DEBUG_LOG(("Object is a projectile - looking at object %d (%s) instead", - (objectToValidate)?objectToValidate->getID():INVALID_ID, - (objectToValidate)?objectToValidate->getTemplate()->getName().str():"")); - } - if( objectToValidate && objectToValidate->isAnyKindOf( bonus->m_validKindOf ) ) - { - DEBUG_LOG(("Is valid kindof")); - if( !objectToValidate->isAnyKindOf( bonus->m_invalidKindOf ) ) - { - DEBUG_LOG(("Is not invalid kindof")); - //Quite the trek eh? Now we can apply the bonuses! - if( !isProjectile ) - { - DEBUG_LOG(("Is not projectile. Armor scalar is %g", bonus->m_armorScalar)); - //Really important to not apply certain bonuses like health augmentation to projectiles! - if( bonus->m_armorScalar != 1.0f ) - { - BodyModuleInterface *body = objectToModify->getBodyModule(); - body->applyDamageScalar( bonus->m_armorScalar ); - CRCDEBUG_LOG(("Applying armor scalar of %g (%8.8X) to object %d (%ls) owned by player %d", - bonus->m_armorScalar, AS_INT(bonus->m_armorScalar), objectToModify->getID(), - objectToModify->getTemplate()->getDisplayName().str(), - objectToModify->getControllingPlayer()->getPlayerIndex())); - DEBUG_LOG(("After apply, armor scalar is %g", body->getDamageScalar())); - } - if( bonus->m_sightRangeScalar != 1.0f ) - { - objectToModify->setVisionRange( obj->getVisionRange() * bonus->m_sightRangeScalar ); - objectToModify->setShroudClearingRange( obj->getShroudClearingRange() * bonus->m_sightRangeScalar ); - } - } - - if( bonus->m_bombardment > 0 ) - { - objectToModify->setWeaponBonusCondition( WEAPONBONUSCONDITION_BATTLEPLAN_BOMBARDMENT ); - } - else - { - objectToModify->clearWeaponBonusCondition( WEAPONBONUSCONDITION_BATTLEPLAN_BOMBARDMENT ); - } - if( bonus->m_holdTheLine > 0 ) - { - objectToModify->setWeaponBonusCondition( WEAPONBONUSCONDITION_BATTLEPLAN_HOLDTHELINE ); - } - else - { - objectToModify->clearWeaponBonusCondition( WEAPONBONUSCONDITION_BATTLEPLAN_HOLDTHELINE ); - } - if( bonus->m_searchAndDestroy > 0 ) - { - objectToModify->setWeaponBonusCondition( WEAPONBONUSCONDITION_BATTLEPLAN_SEARCHANDDESTROY ); - } - else - { - objectToModify->clearWeaponBonusCondition( WEAPONBONUSCONDITION_BATTLEPLAN_SEARCHANDDESTROY ); - } - } - } -} - -//------------------------------------------------------------------------------------------------- -//New object or converted object gaining our current battle plan bonuses. -//------------------------------------------------------------------------------------------------- -void Player::applyBattlePlanBonusesForObject( Object *obj ) const -{ - localApplyBattlePlanBonusesToObject( obj, static_cast(m_battlePlanBonuses) ); -} - -//------------------------------------------------------------------------------------------------- -//Object has just left our team, so remove it's bonuses! -//------------------------------------------------------------------------------------------------- -void Player::removeBattlePlanBonusesForObject( Object *obj ) const -{ - //Create inverted bonuses. - BattlePlanBonusesData bonus; - bonus.m_armorScalar = 1.0f / __max( m_battlePlanBonuses->m_armorScalar, 0.01f ); - bonus.m_sightRangeScalar = 1.0f / __max( m_battlePlanBonuses->m_sightRangeScalar, 0.01f ); - bonus.m_bombardment = -ALL_PLANS; //Safe to remove as it clears the weapon bonus flag - bonus.m_searchAndDestroy = -ALL_PLANS; //Safe to remove as it clears the weapon bonus flag - bonus.m_holdTheLine = -ALL_PLANS; //Safe to remove as it clears the weapon bonus flag - bonus.m_validKindOf = m_battlePlanBonuses->m_validKindOf; - bonus.m_invalidKindOf = m_battlePlanBonuses->m_invalidKindOf; - - DUMPBATTLEPLANBONUSES(&bonus, this, obj); - localApplyBattlePlanBonusesToObject( obj, &bonus ); -} - -//------------------------------------------------------------------------------------------------- -//Battle plan bonuses changing, so apply to all of our objects! -//------------------------------------------------------------------------------------------------- -void Player::applyBattlePlanBonusesForPlayerObjects( const BattlePlanBonusesData *bonus ) -{ - DUMPBATTLEPLANBONUSES(bonus, this, nullptr); - - //Only allocate the battle plan bonuses if we actually use it! - if( !m_battlePlanBonuses ) - { - DEBUG_LOG(("Allocating new m_battlePlanBonuses")); - m_battlePlanBonuses = newInstance( BattlePlanBonuses ); - *static_cast(m_battlePlanBonuses) = *bonus; - } - else - { - DEBUG_LOG(("Adding bonus into existing m_battlePlanBonuses")); - DUMPBATTLEPLANBONUSES(m_battlePlanBonuses, this, nullptr); - //Just apply the differences by multiplying the scalars together (kindofs won't change) - //These bonuses are used for new objects that are created or objects that are transferred - //to our team. - m_battlePlanBonuses->m_armorScalar *= bonus->m_armorScalar; - m_battlePlanBonuses->m_sightRangeScalar *= bonus->m_sightRangeScalar; - m_battlePlanBonuses->m_bombardment += bonus->m_bombardment; - m_battlePlanBonuses->m_bombardment = MAX( 0, m_battlePlanBonuses->m_bombardment ); - m_battlePlanBonuses->m_holdTheLine += bonus->m_holdTheLine; - m_battlePlanBonuses->m_holdTheLine = MAX( 0, m_battlePlanBonuses->m_holdTheLine ); - m_battlePlanBonuses->m_searchAndDestroy += bonus->m_searchAndDestroy; - m_battlePlanBonuses->m_searchAndDestroy = MAX( 0, m_battlePlanBonuses->m_searchAndDestroy ); - } - - DUMPBATTLEPLANBONUSES(m_battlePlanBonuses, this, nullptr); -#if RETAIL_COMPATIBLE_CRC - iterateObjects( localApplyBattlePlanBonusesToObject, const_cast(bonus) ); -#else - // TheSuperHackers @bugfix Stubbjax 05/02/2026 Apply all bonuses the player has rather than just the most recent. - BattlePlanBonusesData newBonus = *m_battlePlanBonuses; - newBonus.m_armorScalar = bonus->m_armorScalar; - newBonus.m_sightRangeScalar = bonus->m_sightRangeScalar; - - iterateObjects(localApplyBattlePlanBonusesToObject, &newBonus); -#endif -} - - -//------------------------------------------------------------------------------------------------- -/** Create a hotkey team based on this GameMessage */ -//------------------------------------------------------------------------------------------------- -void Player::processCreateTeamGameMessage(Int hotkeyNum, const GameMessage *msg) { - // GameMessage arguments are the object ID's of the objects that are to be in this team. - - if ((hotkeyNum < 0) || (hotkeyNum >= NUM_HOTKEY_SQUADS)) { - DEBUG_CRASH(("processCreateTeamGameMessage got an invalid hotkey number")); - return; - } - - m_squads[hotkeyNum]->clearSquad(); - - UnsignedByte numArgs = msg->getArgumentCount(); - for (UnsignedByte i = 0; i < numArgs; ++i) { - ObjectID objID = msg->getArgument(i)->objectID; - Object *obj = TheGameLogic->findObjectByID(objID); - if (obj != nullptr) { - // first, remove it from any other hotkey squads it is in. - removeObjectFromHotkeySquad(obj); - m_squads[hotkeyNum]->addObject(obj); - } - } -} - -//------------------------------------------------------------------------------------------------- -/** Select a hotkey team based on this GameMessage */ -//------------------------------------------------------------------------------------------------- -void Player::processSelectTeamGameMessage(Int hotkeyNum) { - if ((hotkeyNum < 0) || (hotkeyNum >= NUM_HOTKEY_SQUADS)) { - DEBUG_CRASH(("processSelectTeamGameMessage got an invalid hotkey number")); - return; - } - - if (m_squads[hotkeyNum] == nullptr) { - return; - } - - m_currentSelection->clearSquad(); - - const VecObjectPtr& objectList = m_squads[hotkeyNum]->getLiveObjects(); - Int numObjs = objectList.size(); - - for (Int i = 0; i < numObjs; ++i) - { - m_currentSelection->addObject(objectList[i]); - } - - if( numObjs > 0 ) - { - getAcademyStats()->recordControlGroupsUsed(); - } - -} - -//------------------------------------------------------------------------------------------------- -/** Select a hotkey team based on this GameMessage */ -//------------------------------------------------------------------------------------------------- -void Player::processAddTeamGameMessage(Int hotkeyNum) { - if ((hotkeyNum < 0) || (hotkeyNum >= NUM_HOTKEY_SQUADS)) { - DEBUG_CRASH(("processAddTeamGameMessage got an invalid hotkey number")); - return; - } - - if (m_squads[hotkeyNum] == nullptr) { - return; - } - - if (m_currentSelection == nullptr) { - m_currentSelection = newInstance( Squad ); - } - - const VecObjectPtr& objectList = m_squads[hotkeyNum]->getLiveObjects(); - Int numObjs = objectList.size(); - - for (Int i = 0; i < numObjs; ++i) { - m_currentSelection->addObject(objectList[i]); - } -} - -//------------------------------------------------------------------------------------------------- -/** Select a hotkey team based on this GameMessage */ -//------------------------------------------------------------------------------------------------- -void Player::getCurrentSelectionAsAIGroup(AIGroup *group) { - if (m_currentSelection != nullptr) { - m_currentSelection->aiGroupFromSquad(group); - } -} - -//------------------------------------------------------------------------------------------------- -/** Select a hotkey team based on this GameMessage */ -//------------------------------------------------------------------------------------------------- -void Player::setCurrentlySelectedAIGroup(AIGroup *group) { - if (m_currentSelection == nullptr) { - m_currentSelection = newInstance( Squad ); - } - - m_currentSelection->clearSquad(); - - if (group != nullptr) { - m_currentSelection->squadFromAIGroup(group, true); - } -} - -//------------------------------------------------------------------------------------------------- -/** Select a hotkey team based on this GameMessage */ -//------------------------------------------------------------------------------------------------- -Squad *Player::getHotkeySquad(Int squadNumber) -{ - if ((squadNumber >= 0) && (squadNumber < NUM_HOTKEY_SQUADS)) { - return m_squads[squadNumber]; - } - return nullptr; -} - -//------------------------------------------------------------------------------------------------- -/** return the hotkey squad that a unit is in, or NO_HOTKEY_SQUAD if it isn't in one */ -//------------------------------------------------------------------------------------------------- -Int Player::getSquadNumberForObject(const Object *objToFind) const -{ - for (Int i = 0; i < NUM_HOTKEY_SQUADS; ++i) { - if (m_squads[i]->isOnSquad(objToFind)) { - return i; - } - } - - return NO_HOTKEY_SQUAD; -} - -//------------------------------------------------------------------------------------------------- -/** Remove an object from any hotkey squads its on. (Should never be more than one, but do them */ -/** all for good measure. */ -//------------------------------------------------------------------------------------------------- -void Player::removeObjectFromHotkeySquad(Object *objToRemove) -{ - for (Int i = 0; i < NUM_HOTKEY_SQUADS; ++i) { - if (!m_squads[i]) { - continue; - } - - m_squads[i]->removeObject(objToRemove); - } -} - -//------------------------------------------------------------------------------------------------- -/** Select a hotkey team based on this GameMessage */ -//------------------------------------------------------------------------------------------------- -void Player::addAIGroupToCurrentSelection(AIGroup *group) { - if (group == nullptr) { - return; - } - - if (m_currentSelection == nullptr) { - m_currentSelection = newInstance( Squad ); - } - - VecObjectID objectIDVec = group->getAllIDs(); - Int numObjs = objectIDVec.size(); - for (Int i = 0; i < numObjs; ++i) { - m_currentSelection->addObjectID(objectIDVec[i]); - } -} - -//------------------------------------------------------------------------------------------------- -/** addTypeOfProductionCostChange adds a production change to the typeof list */ -//------------------------------------------------------------------------------------------------- -void Player::addKindOfProductionCostChange( KindOfMaskType kindOf, Real percent ) -{ - KindOfPercentProductionChangeListIt it = m_kindOfPercentProductionChangeList.begin(); - while(it != m_kindOfPercentProductionChangeList.end()) - { - - KindOfPercentProductionChange *tof = *it; - if( tof->m_percent == percent && tof->m_kindOf == kindOf) - { - tof->m_ref++; - return; - } - ++it; - } - - KindOfPercentProductionChange *newTof = newInstance( KindOfPercentProductionChange ); - newTof->m_kindOf = kindOf; - newTof->m_percent = percent; - newTof->m_ref = 1; - m_kindOfPercentProductionChangeList.push_back(newTof); - -} - -//------------------------------------------------------------------------------------------------- -/** addTypeOfProductionCostChange adds a production change to the typeof list */ -//------------------------------------------------------------------------------------------------- -void Player::removeKindOfProductionCostChange( KindOfMaskType kindOf, Real percent ) -{ - KindOfPercentProductionChangeListIt it = m_kindOfPercentProductionChangeList.begin(); - while(it != m_kindOfPercentProductionChangeList.end()) - { - - KindOfPercentProductionChange* tof = *it; - if( tof->m_percent == percent && tof->m_kindOf == kindOf) - { - tof->m_ref--; - if(tof->m_ref == 0) - { - m_kindOfPercentProductionChangeList.erase( it ); - deleteInstance(tof); - } - return; - } - ++it; - } - DEBUG_CRASH(("removeKindOfProductionCostChange was called with kindOf=%d and percent=%f. We could not find the entry in the list with these variables. CLH.",kindOf, percent)); -} - -//------------------------------------------------------------------------------------------------- -/** getProductionCostChangeBasedOnKindOf gets the cost percentage change based off of Kindof Mask */ -//------------------------------------------------------------------------------------------------- -Real Player::getProductionCostChangeBasedOnKindOf( KindOfMaskType kindOf ) const -{ - Real start = 1.0f; - KindOfPercentProductionChangeListIt it = m_kindOfPercentProductionChangeList.begin(); - while(it != m_kindOfPercentProductionChangeList.end()) - { - - KindOfPercentProductionChange *tof = *it; - if(TEST_KINDOFMASK_MULTI(kindOf, tof->m_kindOf, KINDOFMASK_NONE)) - { - start *= (1 + tof->m_percent); - } - ++it; - } - return (start); -} - -//------------------------------------------------------------------------------------------------- -/** setAttackedBy */ -//------------------------------------------------------------------------------------------------- -void Player::setAttackedBy( Int playerNdx ) -{ - DEBUG_ASSERTCRASH(playerNdx >= 0, ("Player::setAttackedBy Player index is %d", playerNdx)); - m_attackedBy[playerNdx] = true; - m_attackedFrame = TheGameLogic->getFrame(); - -} - -//------------------------------------------------------------------------------------------------- -/** getAttackedBy */ -//------------------------------------------------------------------------------------------------- -Bool Player::getAttackedBy( Int playerNdx ) const -{ - return m_attackedBy[playerNdx]; -} - -#if RTS_GENERALS -// ------------------------------------------------------------------------------------------------ -static void callHandleShroud( Object *obj, void * ) -{ - // I feel I have to disapprove of the naming of this gathering of cell functions. It is called by death, - // alliance change, containment, spy change, and dynamic view range as well as partition cell change. - if( obj ) - obj->handlePartitionCellMaintenance(); -} - -// ------------------------------------------------------------------------------------------------ -void Player::setUnitsVisionSpied( Bool setting, PlayerIndex byWhom ) -{ - Bool needRefresh = FALSE; // If this setting is an edge trigger on the reference count, I need - // to tell all of my guys to handleShroud so they will start/stop looking for the new team. - - if( setting ) - { - m_visionSpiedBy[ byWhom ] = m_visionSpiedBy[ byWhom ] + 1; - if( m_visionSpiedBy[ byWhom ] == 1 ) - needRefresh = TRUE; - } - else - { - m_visionSpiedBy[ byWhom ] = m_visionSpiedBy[ byWhom ] - 1; - if( m_visionSpiedBy[ byWhom ] == 0 ) - needRefresh = TRUE; - } - - if( needRefresh ) - { - PlayerMaskType workingMask = 0; - for (Int i = 0; i < MAX_PLAYER_COUNT; ++i) - { - if( m_visionSpiedBy[i] > 0 ) - BitSet( workingMask, ( 1 << i ) ); - else - BitClear( workingMask, ( 1 << i ) ); - } - - m_visionSpiedMask = workingMask; - - iterateObjects( callHandleShroud, nullptr ); - } -} - -// ------------------------------------------------------------------------------------------------ -PlayerMaskType Player::getVisionSpiedMask() const -{ - return m_visionSpiedMask; -} -#else -// ------------------------------------------------------------------------------------------------ -// Little wrapper function so I can use it in iterateObjects, which is cool. -struct VisionSpiedStruct -{ - Bool setting; - KindOfMaskType whichUnits; - PlayerIndex byWhom; -}; - -static void iterator_setUnitsVisionSpied( Object *obj, void * voidData) -{ - VisionSpiedStruct *data = (VisionSpiedStruct *)voidData; - - // I feel I have to disapprove of the naming of this gathering of cell functions. It is called by death, - // alliance change, containment, spy change, and dynamic view range as well as partition cell change. - if( obj && obj->isAnyKindOf(data->whichUnits) ) - obj->setVisionSpied(data->setting, data->byWhom); -} - -// ------------------------------------------------------------------------------------------------ -void Player::setUnitsVisionSpied( Bool setting, KindOfMaskType whichUnits, PlayerIndex byWhom ) -{ - VisionSpiedStruct data; - data.setting = setting; - data.whichUnits = whichUnits; - data.byWhom = byWhom; - // Being spied is now a property of the unit, not us, since we can spy only a portion of the enemy. - iterateObjects( iterator_setUnitsVisionSpied, &data ); -} -#endif - -// ------------------------------------------------------------------------------------------------ -Bool Player::isPlayerObserver() const -{ - return m_observer; -} - -// ------------------------------------------------------------------------------------------------ -Bool Player::isPlayerDead() const -{ - return m_isPlayerDead; -} - -// ------------------------------------------------------------------------------------------------ -Bool Player::isPlayerActive() const -{ - return !m_observer && !m_isPlayerDead; -} - -// ------------------------------------------------------------------------------------------------ -Bool Player::isPlayableSide() const -{ - - return m_playerTemplate ? m_playerTemplate->isPlayableSide() : FALSE; - -} - -// ------------------------------------------------------------------------------------------------ -/** CRC */ -// ------------------------------------------------------------------------------------------------ -void Player::crc( Xfer *xfer ) -{ - // Player battle plan bonuses - Bool battlePlanBonus = m_battlePlanBonuses != nullptr; - xfer->xferBool( &battlePlanBonus ); - CRCDEBUG_LOG(("Player %d[%ls] %s battle plans", m_playerIndex, m_playerDisplayName.str(), (battlePlanBonus)?"has":"doesn't have")); - if( m_battlePlanBonuses ) - { - CRCDUMPBATTLEPLANBONUSES(m_battlePlanBonuses, this, nullptr); - xfer->xferReal( &m_battlePlanBonuses->m_armorScalar ); - xfer->xferReal( &m_battlePlanBonuses->m_sightRangeScalar ); - xfer->xferInt( &m_battlePlanBonuses->m_bombardment ); - xfer->xferInt( &m_battlePlanBonuses->m_holdTheLine ); - xfer->xferInt( &m_battlePlanBonuses->m_searchAndDestroy ); - m_battlePlanBonuses->m_validKindOf.xfer(xfer); - m_battlePlanBonuses->m_invalidKindOf.xfer(xfer); - } - - xfer->xferInt( &m_skillPoints ); - xfer->xferInt( &m_sciencePurchasePoints ); - -} - -// ------------------------------------------------------------------------------------------------ -/** Xfer Method - * Version Info: - * 1: Initial version - * 2: Player can now have a modifier on his skill points (multiplicative) - * 3: Player can be excluded from the score screen via script. - * 4: Player stores a list of specialpowerreadyframe timers, used by specialpowermodules abroad - * 5: ??? (Profit) - * 6: Store m_unitsShouldHunt, set to true after the script "Tell player to hunt" is called. - * 7: added Preorder flag - * 8: Save m_disabledSciences & m_hiddenSciences. jba. - */ -// ------------------------------------------------------------------------------------------------ -void Player::xfer( Xfer *xfer ) -{ - - // version - const XferVersion currentVersion = 8; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - // money - xfer->xferSnapshot( &m_money ); - - // upgrade list count - Upgrade *upgrade; - UnsignedShort upgradeCount = 0; - for( upgrade = m_upgradeList; upgrade; upgrade = upgrade->friend_getNext() ) - upgradeCount++; - xfer->xferUnsignedShort( &upgradeCount ); - - if (version >= 7) - { - // preorder info - xfer->xferBool( & m_isPreorder ); - } - - if (version >= 8) - { - xfer->xferScienceVec(&m_sciencesDisabled); - xfer->xferScienceVec(&m_sciencesHidden); - } - - // xfer upgrade instances - AsciiString upgradeName; - if( xfer->getXferMode() == XFER_SAVE ) - { - - for( upgrade = m_upgradeList; upgrade; upgrade = upgrade->friend_getNext() ) - { - - // write upgrade name - upgradeName = upgrade->getTemplate()->getUpgradeName(); - xfer->xferAsciiString( &upgradeName ); - - // xfer upgrade data - xfer->xferSnapshot( upgrade ); - - } - - } - else - { - const UpgradeTemplate *upgradeTemplate; - - for( UnsignedShort i = 0; i < upgradeCount; ++i ) - { - - // read name - xfer->xferAsciiString( &upgradeName ); - - // find template for this upgrade - upgradeTemplate = TheUpgradeCenter->findUpgrade( upgradeName ); - - // sanity - if( upgradeTemplate == nullptr ) - { - - DEBUG_CRASH(( "Player::xfer - Unable to find upgrade '%s'", upgradeName.str() )); - throw SC_INVALID_DATA; - - } - - // add upgrade to player, the status is invalid, but that's OK cause we're about to xfer it - upgrade = addUpgrade( upgradeTemplate, UPGRADE_STATUS_INVALID ); - - // xfer upgrade data - xfer->xferSnapshot( upgrade ); - - } - - } - - // radar info - xfer->xferInt( &m_radarCount ); - xfer->xferBool( & m_isPlayerDead ); - xfer->xferInt( &m_disableProofRadarCount ); - xfer->xferBool( & m_radarDisabled ); - - // upgrades in progress - xfer->xferUpgradeMask( &m_upgradesInProgress ); - - // upgrades complete - xfer->xferUpgradeMask( &m_upgradesCompleted ); - - // energy info - xfer->xferSnapshot( &m_energy ); - - // - // team prototypes ... this is only the fact that team prototypes are on this player - // it is not the team prototype data itself - // - UnsignedShort prototypeCount = m_playerTeamPrototypes.size(); - xfer->xferUnsignedShort( &prototypeCount ); - TeamPrototypeID prototypeID; - TeamPrototype *prototype; - if( xfer->getXferMode() == XFER_SAVE ) - { - - PlayerTeamList::iterator it; - for( it = m_playerTeamPrototypes.begin(); it != m_playerTeamPrototypes.end(); ++it ) - { - - prototype = *it; - prototypeID = prototype->getID(); - xfer->xferUser( &prototypeID, sizeof( TeamPrototypeID ) ); - - } - - } - else - { - - // empty the list right now - m_playerTeamPrototypes.clear(); - - // read all the data - for( UnsignedShort i = 0; i < prototypeCount; ++i ) - { - - // read id - xfer->xferUser( &prototypeID, sizeof( TeamPrototypeID ) ); - - // find prototype - prototype = TheTeamFactory->findTeamPrototypeByID( prototypeID ); - - // sanity - if( prototype == nullptr ) - { - - DEBUG_CRASH(( "Player::xfer - Unable to find team prototype by id" )); - throw SC_INVALID_DATA; - - } - - // put in list - m_playerTeamPrototypes.push_back( prototype ); - - } - - } - - // build list info - UnsignedShort buildListInfoCount = 0; - BuildListInfo *buildListInfo; - for( buildListInfo = m_pBuildList; buildListInfo; buildListInfo = buildListInfo->getNext() ) - buildListInfoCount++; - xfer->xferUnsignedShort( &buildListInfoCount ); - if( xfer->getXferMode() == XFER_SAVE ) - { - - // xfer each build list info - for( buildListInfo = m_pBuildList; buildListInfo; buildListInfo = buildListInfo->getNext() ) - xfer->xferSnapshot( buildListInfo ); - - } - else - { - - // - // destroy any build list that we got from loading the bare bones map, note that deleting - // the head of these structures automatically deletes any links attached - // - deleteInstance(m_pBuildList); - m_pBuildList = nullptr; - - // read each build list info - for( UnsignedShort i = 0; i < buildListInfoCount; ++i ) - { - - // allocate new build list - buildListInfo = newInstance( BuildListInfo ); - buildListInfo->setNextBuildList( nullptr ); - - // attach to the *end* of the list in the player - if( m_pBuildList == nullptr ) - m_pBuildList = buildListInfo; - else - { - BuildListInfo *last = m_pBuildList; - - while( last->getNext() != nullptr ) - last = last->getNext(); - - last->setNextBuildList( buildListInfo ); - - } - - // xfer data - xfer->xferSnapshot( buildListInfo ); - - } - - } - - // ai player data - Bool aiPlayerPresent = m_ai ? TRUE : FALSE; - xfer->xferBool( &aiPlayerPresent ); - if( (aiPlayerPresent == TRUE && m_ai == nullptr) || (aiPlayerPresent == FALSE && m_ai != nullptr) ) - { - - DEBUG_CRASH(( "Player::xfer - m_ai present/missing mismatch" )); - throw SC_INVALID_DATA; - - } - if( m_ai ) - xfer->xferSnapshot( m_ai ); - - // resource gathering manager - Bool resourceGatheringManagerPresent = m_resourceGatheringManager ? TRUE : FALSE; - xfer->xferBool( &resourceGatheringManagerPresent ); - if( (resourceGatheringManagerPresent == TRUE && m_resourceGatheringManager == nullptr) || - (resourceGatheringManagerPresent == FALSE && m_resourceGatheringManager != nullptr ) ) - { - - DEBUG_CRASH(( "Player::xfer - m_resourceGatheringManager present/missing mismatch" )); - throw SC_INVALID_DATA; - - } - if( m_resourceGatheringManager ) - xfer->xferSnapshot( m_resourceGatheringManager ); - - // tunnel tracking system - Bool tunnelTrackerPresent = m_tunnelSystem ? TRUE : FALSE; - xfer->xferBool( &tunnelTrackerPresent ); - if( (tunnelTrackerPresent == TRUE && m_tunnelSystem == nullptr) || - (tunnelTrackerPresent == FALSE && m_tunnelSystem != nullptr) ) - { - - DEBUG_CRASH(( "Player::xfer - m_tunnelSystem present/missing mismatch" )); - throw SC_INVALID_DATA; - - } - if( m_tunnelSystem ) - xfer->xferSnapshot( m_tunnelSystem ); - - // default team - TeamID teamID = m_defaultTeam ? m_defaultTeam->getID() : TEAM_ID_INVALID; - xfer->xferUser( &teamID, sizeof( TeamID ) ); - if( xfer->getXferMode() == XFER_LOAD ) - m_defaultTeam = TheTeamFactory->findTeamByID( teamID ); - - // sciences - if (version >= 5) - { - // m_sciences will contain some intrinsic sciences and stuff, which we don't want. - // so nuke 'em for load. - if( xfer->getXferMode() == XFER_LOAD ) - m_sciences.clear(); - xfer->xferScienceVec(&m_sciences); - } - else - { - /* - This code is WRONG WRONG WRONG and must not be used or mimicked; it - is present for backwards "compatibility" only. (srj) - */ - UnsignedShort scienceCount = m_sciences.size(); - xfer->xferUnsignedShort( &scienceCount ); - ScienceType science; - if( xfer->getXferMode() == XFER_SAVE ) - { - ScienceVec::const_iterator it; - for( it = m_sciences.begin(); it != m_sciences.end(); ++it ) - { - - science = *it; - xfer->xferUser( &science, sizeof( ScienceType ) ); - } - } - else - { - for( UnsignedShort i = 0; i < scienceCount; ++i ) - { - xfer->xferUser( &science, sizeof( ScienceType ) ); - m_sciences.push_back( science ); - - } - } - /* - This code is WRONG WRONG WRONG and must not be used or mimicked; it - is present for backwards "compatibility" only. (srj) - */ - } - - // rank level - xfer->xferInt( &m_rankLevel ); - - // skill points - xfer->xferInt( &m_skillPoints ); - - // science purchase points - xfer->xferInt( &m_sciencePurchasePoints ); - - // level up - xfer->xferInt( &m_levelUp ); - - // level down - xfer->xferInt( &m_levelDown ); - - // general name - xfer->xferUnicodeString( &m_generalName ); - - // player relations - xfer->xferSnapshot( m_playerRelations ); - - // team relations - xfer->xferSnapshot( m_teamRelations ); - - // can build units - xfer->xferBool( &m_canBuildUnits ); - - // can build base - xfer->xferBool( &m_canBuildBase ); - - // observer - xfer->xferBool( &m_observer ); - - if (version >= 2) - { - // current skill point modifier value - xfer->xferReal( &m_skillPointsModifier); - } - else - { - m_skillPointsModifier = 1.0f; - } - - if (version >= 3) - { - xfer->xferBool( &m_listInScoreScreen ); - } - else - { - m_listInScoreScreen = TRUE; - } - // attacked by - xfer->xferUser( m_attackedBy, sizeof( Bool ) * MAX_PLAYER_COUNT ); - -#if RTS_GENERALS - // vision spied by - xfer->xferUser( m_visionSpiedBy, sizeof( Int ) * MAX_PLAYER_COUNT ); - - // vision spied by mask - xfer->xferUser( &m_visionSpiedMask, sizeof( PlayerMaskType ) ); -#endif - - // cash bounty percent - xfer->xferReal( &m_cashBountyPercent ); - - // score keeper - xfer->xferSnapshot( &m_scoreKeeper ); - - // size of and data for kindof percent production change list - UnsignedShort percentProductionChangeCount = m_kindOfPercentProductionChangeList.size(); - xfer->xferUnsignedShort( &percentProductionChangeCount ); - KindOfPercentProductionChange *entry; - if( xfer->getXferMode() == XFER_SAVE ) - { - KindOfPercentProductionChangeListIt it; - - // save each item - for( it = m_kindOfPercentProductionChangeList.begin(); - it != m_kindOfPercentProductionChangeList.end(); - ++it ) - { - - // get entry data - entry = *it; - - // kind of mask type - entry->m_kindOf.xfer(xfer); - - // percent - xfer->xferReal( &entry->m_percent ); - - // ref - xfer->xferUnsignedInt( &entry->m_ref ); - - } - - } - else - { - - // sanity, list must be empty right now - if( !m_kindOfPercentProductionChangeList.empty() ) - { - - DEBUG_CRASH(( "Player::xfer - m_kindOfPercentProductionChangeList should be empty but is not" )); - throw SC_INVALID_DATA; - - } - - // read each entry - for( UnsignedInt i = 0; i < percentProductionChangeCount; ++i ) - { - - // allocate new entry - entry = newInstance( KindOfPercentProductionChange ); - - // read data - entry->m_kindOf.xfer(xfer); - xfer->xferReal( &entry->m_percent ); - xfer->xferUnsignedInt( &entry->m_ref ); - - // put at end of list - m_kindOfPercentProductionChangeList.push_back( entry ); - - } - - } - - - - - /////////////////////////////////////////////////////////////////////////// - if ( version < 4 ) - { - m_specialPowerReadyTimerList.clear(); - } - else - { - UnsignedShort timerListSize = m_specialPowerReadyTimerList.size(); - xfer->xferUnsignedShort( &timerListSize );// HANDY LITTLE SHORT TO SIZE MY LIST - if( xfer->getXferMode() == XFER_SAVE ) - { - - SpecialPowerReadyTimerType *timer; - SpecialPowerReadyTimerListIterator it; - for( it = m_specialPowerReadyTimerList.begin(); it != m_specialPowerReadyTimerList.end(); ++it ) - { - timer = &(*it); - xfer->xferUnsignedInt( &timer->m_templateID ); - xfer->xferUnsignedInt( &timer->m_readyFrame ); - } - } - else - { - if( !m_specialPowerReadyTimerList.empty() ) // sanity, list must be empty right now - { - DEBUG_CRASH(( "Player::xfer - m_specialPowerReadyTimerList should be empty but is not" )); - throw SC_INVALID_DATA; - } - - // read each entry - for( UnsignedInt i = 0; i < timerListSize; ++i ) - { - SpecialPowerReadyTimerType timer; - - // read data - xfer->xferUnsignedInt( &timer.m_templateID ); - xfer->xferUnsignedInt( &timer.m_readyFrame ); - - // put at end of list - m_specialPowerReadyTimerList.push_back( timer ); - - } - } - } - /////////////////////////////////////////////////////////////////////////// - - - - - // squads - UnsignedShort squadCount = NUM_HOTKEY_SQUADS; - xfer->xferUnsignedShort( &squadCount ); - if( squadCount != NUM_HOTKEY_SQUADS ) - { - - DEBUG_CRASH(( "Player::xfer - size of m_squadCount array has changed" )); - throw SC_INVALID_DATA; - - } - for( UnsignedShort i = 0; i < squadCount; ++i ) - { - - if( m_squads[ i ] == nullptr ) - { - - DEBUG_CRASH(( "Player::xfer - null squad at index '%d'", i )); - throw SC_INVALID_DATA; - - } - - xfer->xferSnapshot( m_squads[ i ] ); - - } - - // current squad selection - Bool currentSelectionPresent = m_currentSelection ? TRUE : FALSE; - xfer->xferBool( ¤tSelectionPresent ); - if( currentSelectionPresent ) - { - - // allocate squad if needed - if( m_currentSelection == nullptr && xfer->getXferMode() == XFER_LOAD ) - m_currentSelection = newInstance( Squad ); - - // xfer - xfer->xferSnapshot( m_currentSelection ); - - } - - // Player battle plan bonuses - Bool battlePlanBonus = m_battlePlanBonuses != nullptr; - xfer->xferBool( &battlePlanBonus ); //If we're loading, it just replaces the bool - if( xfer->getXferMode() == XFER_LOAD ) - { - deleteInstance(m_battlePlanBonuses); - m_battlePlanBonuses = nullptr; - - if ( battlePlanBonus ) - { - m_battlePlanBonuses = newInstance( BattlePlanBonuses ); - } - } - if( m_battlePlanBonuses ) - { - xfer->xferReal( &m_battlePlanBonuses->m_armorScalar ); - xfer->xferReal( &m_battlePlanBonuses->m_sightRangeScalar ); - xfer->xferInt( &m_battlePlanBonuses->m_bombardment ); - xfer->xferInt( &m_battlePlanBonuses->m_holdTheLine ); - xfer->xferInt( &m_battlePlanBonuses->m_searchAndDestroy ); - m_battlePlanBonuses->m_validKindOf.xfer(xfer); - m_battlePlanBonuses->m_invalidKindOf.xfer(xfer); - } - xfer->xferInt( &m_bombardBattlePlans ); - xfer->xferInt( &m_holdTheLineBattlePlans ); - xfer->xferInt( &m_searchAndDestroyBattlePlans ); - - if (version >= 6) - { - xfer->xferBool(&m_unitsShouldHunt); - } - else - m_unitsShouldHunt = FALSE; - -} - -// ------------------------------------------------------------------------------------------------ -/** Load post process */ -// ------------------------------------------------------------------------------------------------ -void Player::loadPostProcess() -{ - -} - diff --git a/Generals/Code/GameEngine/Source/Common/RTS/PlayerList.cpp b/Generals/Code/GameEngine/Source/Common/RTS/PlayerList.cpp deleted file mode 100644 index 4c0e5efaa3f..00000000000 --- a/Generals/Code/GameEngine/Source/Common/RTS/PlayerList.cpp +++ /dev/null @@ -1,559 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: PlayerList.cpp ///////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: RTS3 -// -// File name: PlayerList.cpp -// -// Created: Steven Johnson, October 2001 -// -// Desc: @todo -// -//----------------------------------------------------------------------------- - -#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine - -#include "Common/Errors.h" -#include "Common/DataChunk.h" -#include "Common/GameState.h" -#include "Common/GlobalData.h" -#include "Common/Player.h" -#include "Common/PlayerList.h" -#include "Common/PlayerTemplate.h" -#include "Common/Team.h" -#include "Common/WellKnownKeys.h" -#include "Common/Xfer.h" -#ifdef RTS_DEBUG -#include "GameLogic/Object.h" -#endif -#include "GameLogic/SidesList.h" -#include "GameNetwork/GameInfo.h" -#include "GameNetwork/NetworkDefs.h" - -//----------------------------------------------------------------------------- -/*extern*/ PlayerList *ThePlayerList = nullptr; - -//----------------------------------------------------------------------------- -PlayerList::PlayerList() : - m_local(nullptr), - m_playerCount(0) -{ - // we only allocate a few of these, so don't bother pooling 'em - for (Int i = 0; i < MAX_PLAYER_COUNT; i++) - m_players[ i ] = NEW Player( i ); - init(); -} - -//----------------------------------------------------------------------------- -PlayerList::~PlayerList() -{ - // the world is happier if we reinit things before destroying them, - // to avoid debug warnings - init(); - - for( Int i = 0; i < MAX_PLAYER_COUNT; ++i ) - delete m_players[ i ]; -} - -//----------------------------------------------------------------------------- -Player *PlayerList::getNthPlayer(Int i) -{ - if( i < 0 || i >= MAX_PLAYER_COUNT ) - { -// DEBUG_CRASH( ("Illegal player index") ); - return nullptr; - } - return m_players[i]; -} - -//----------------------------------------------------------------------------- -Player *PlayerList::findPlayerWithNameKey(NameKeyType key) -{ - for (Int i = 0; i < m_playerCount; i++) - { - if (m_players[i]->getPlayerNameKey() == key) - { - return m_players[i]; - } - } - return nullptr; -} - -//----------------------------------------------------------------------------- -void PlayerList::reset() -{ - // TheSuperHackers @bugfix xezon 20/03/2025 Delete the Player AI before purging the dependent teams in the factory. - for (int i = 0; i < MAX_PLAYER_COUNT; i++) - m_players[i]->deletePlayerAI(); - - TheTeamFactory->clear(); // cleans up energy, among other things - init(); -} - -//----------------------------------------------------------------------------- -void PlayerList::newGame() -{ - Int i; - - DEBUG_ASSERTCRASH(this != nullptr, ("null this")); - - reset(); - - // ok, now create the rest of players we need. - Bool setLocal = false; - for( i = 0; i < TheSidesList->getNumSides(); i++) - { - Dict *d = TheSidesList->getSideInfo(i)->getDict(); - AsciiString pname = d->getAsciiString(TheKey_playerName); - if (pname.isEmpty()) - continue; // it's neutral, which we've already done, so skip it. - - /// @todo The Player class should have a reset() method, instead of directly calling initFromDict() (MSB) - Player* p = m_players[m_playerCount++]; - p->initFromDict(d); - - // Multiplayer override - Bool exists; // throwaway, since we don't care if it exists - if (d->getBool(TheKey_multiplayerIsLocal, &exists)) - { - DEBUG_LOG(("Player %s is multiplayer local", pname.str())); - setLocalPlayer(p); - setLocal = true; - } - - if (!setLocal && !TheNetwork && d->getBool(TheKey_playerIsHuman)) - { - setLocalPlayer(p); - setLocal = true; - } - - // Set the build list. - p->setBuildList(TheSidesList->getSideInfo(i)->getBuildList()); - // Build list is attached to player now, so release it from the side info. - TheSidesList->getSideInfo(i)->releaseBuildList(); - } - - if (!setLocal) - { - DEBUG_ASSERTCRASH(TheNetwork, ("*** Map has no human player... picking first nonneutral player for control")); - for( i = 0; i < TheSidesList->getNumSides(); i++) - { - Player* p = getNthPlayer(i); - if (p != getNeutralPlayer()) - { - p->setPlayerType(PLAYER_HUMAN, false); - setLocalPlayer(p); - setLocal = true; - break; - } - } - } - - // must reset teams *after* creating players. - TheTeamFactory->initFromSides(TheSidesList); - - for( i = 0; i < TheSidesList->getNumSides(); i++) - { - Dict *d = TheSidesList->getSideInfo(i)->getDict(); - Player* p = findPlayerWithNameKey(NAMEKEY(d->getAsciiString(TheKey_playerName))); - - AsciiString tok; - - AsciiString enemies = d->getAsciiString(TheKey_playerEnemies); - while (enemies.nextToken(&tok)) - { - Player *p2 = findPlayerWithNameKey(NAMEKEY(tok)); - if (p2) - { - p->setPlayerRelationship(p2, ENEMIES); - } - else - { - DEBUG_LOG(("unknown enemy %s",tok.str())); - } - } - - AsciiString allies = d->getAsciiString(TheKey_playerAllies); - while (allies.nextToken(&tok)) - { - Player *p2 = findPlayerWithNameKey(NAMEKEY(tok)); - if (p2) - { - p->setPlayerRelationship(p2, ALLIES); - } - else - { - DEBUG_LOG(("unknown ally %s",tok.str())); - } - } - - // finally, make sure self & neutral are correct. - p->setPlayerRelationship(p, ALLIES); - if (p != getNeutralPlayer()) - p->setPlayerRelationship(getNeutralPlayer(), NEUTRAL); - - p->setDefaultTeam(); - } - - if (TheGameInfo) - { - assignSlotIndices(*TheGameInfo); - } -} - -//----------------------------------------------------------------------------- -void PlayerList::init() -{ - m_playerCount = 1; - m_players[0]->init(nullptr); - - for (int i = 1; i < MAX_PLAYER_COUNT; i++) - m_players[i]->init(nullptr); - - std::fill(m_slotIndices, m_slotIndices + ARRAY_SIZE(m_slotIndices), -1); - std::fill(m_slotToPlayerIndices, m_slotToPlayerIndices + ARRAY_SIZE(m_slotToPlayerIndices), -1); - - // call setLocalPlayer so that becomingLocalPlayer() gets called appropriately - setLocalPlayer(m_players[0]); - -} - -//----------------------------------------------------------------------------- -void PlayerList::update() -{ - // update all players - for( Int i = 0; i < MAX_PLAYER_COUNT; i++ ) - { - m_players[i]->update(); - } - -} - -//----------------------------------------------------------------------------- -void PlayerList::newMap() -{ - // update all players - for( Int i = 0; i < MAX_PLAYER_COUNT; i++ ) - { - m_players[i]->newMap(); - } - -} - -// ------------------------------------------------------------------------ -void PlayerList::teamAboutToBeDeleted(Team* team) -{ - for( Int i = 0; i < MAX_PLAYER_COUNT; i++ ) - { - m_players[i]->removeTeamRelationship(team); - } -} - -//============================================================================= -void PlayerList::updateTeamStates() -{ - // Clear team flags for all players. - for( Int i = 0; i < MAX_PLAYER_COUNT; i++ ) - { - m_players[i]->updateTeamStates(); - } -} - -//----------------------------------------------------------------------------- -Team *PlayerList::validateTeam( AsciiString owner ) -{ - // owner could be a player or team. first, check team names. - Team *t = TheTeamFactory->findTeam(owner); - if (!t) - { - DEBUG_CRASH(("no team or player named %s could be found!", owner.str())); - t = getNeutralPlayer()->getDefaultTeam(); - } - return t; -} - -//----------------------------------------------------------------------------- -void PlayerList::setLocalPlayer(Player *player) -{ - // can't set local player to null -- if you try, you get neutral. - if (player == nullptr) - { - DEBUG_CRASH(("local player may not be null")); - player = getNeutralPlayer(); - } - - if (player != m_local) - { - // m_local can be null the very first time we call this. - if (m_local) - m_local->becomingLocalPlayer(false); - m_local = player; - player->becomingLocalPlayer(true); - } - -#ifdef INTENSE_DEBUG - if (player) - { - // did you know? you can use "%ls" to print a doublebyte string, even in a single-byte printf... - DEBUG_LOG(("Switching local players. The new player is named '%ls' (%s) and owns the following objects:", - player->getPlayerDisplayName().str(), - TheNameKeyGenerator->keyToName(player->getPlayerNameKey()).str() - )); - for (Object *obj = player->getFirstOwnedObject(); obj; obj = obj->getNextOwnedObject()) - { - DEBUG_LOG_RAW(("Obj %08lx is of type %s",obj,obj->getTemplate()->getName().str())); - if (!player->canBuild(obj->getTemplate())) - { - DEBUG_LOG_RAW((" (NOT BUILDABLE)")); - } - DEBUG_LOG_RAW(("\n")); - } - } -#endif - -} - -//----------------------------------------------------------------------------- -Player *PlayerList::getPlayerFromMask( PlayerMaskType mask ) -{ - Player *player = nullptr; - Int i; - - for( i = 0; i < MAX_PLAYER_COUNT; i++ ) - { - - player = getNthPlayer( i ); - if( player && player->getPlayerMask() == mask ) - return player; - - } - - DEBUG_CRASH( ("Player does not exist for mask") ); - return nullptr; // mask not found - -} - -//----------------------------------------------------------------------------- -Player *PlayerList::getEachPlayerFromMask( PlayerMaskType& maskToAdjust ) -{ - Player *player = nullptr; - Int i; - - for( i = 0; i < MAX_PLAYER_COUNT; i++ ) - { - - player = getNthPlayer( i ); - if ( player && BitIsSet(player->getPlayerMask(), maskToAdjust )) - { - maskToAdjust &= (~player->getPlayerMask()); - return player; - } - } - - DEBUG_CRASH( ("No players found that contain any matching masks.") ); - maskToAdjust = 0; - return nullptr; // mask not found -} - -//------------------------------------------------------------------------------------------------- -PlayerMaskType PlayerList::getPlayersWithRelationship( Int srcPlayerIndex, UnsignedInt allowedRelationships ) -{ - PlayerMaskType retVal = 0; - - if (allowedRelationships == 0) - return retVal; - - Player *srcPlayer = getNthPlayer(srcPlayerIndex); - if (!srcPlayer) - return retVal; - - if (BitIsSet(allowedRelationships, ALLOW_SAME_PLAYER)) - BitSet(retVal, srcPlayer->getPlayerMask()); - - for ( Int i = 0; i < getPlayerCount(); ++i ) - { - Player *player = getNthPlayer(i); - if (!player) - continue; - - if (player == srcPlayer) - continue; - - switch (srcPlayer->getRelationship(player->getDefaultTeam())) - { - case ENEMIES: - if (BitIsSet(allowedRelationships, ALLOW_ENEMIES)) - BitSet(retVal, player->getPlayerMask()); - break; - case ALLIES: - if (BitIsSet(allowedRelationships, ALLOW_ALLIES)) - BitSet(retVal, player->getPlayerMask()); - break; - case NEUTRAL: - if (BitIsSet(allowedRelationships, ALLOW_NEUTRAL)) - BitSet(retVal, player->getPlayerMask()); - break; - } - } - - return retVal; -} - -// ------------------------------------------------------------------------------------------------ -/** CRC */ -// ------------------------------------------------------------------------------------------------ -void PlayerList::crc( Xfer *xfer ) -{ - xfer->xferInt( &m_playerCount ); - - for( Int i = 0; i < m_playerCount; ++i ) - xfer->xferSnapshot( m_players[ i ] ); -} - -// ------------------------------------------------------------------------------------------------ -/** Xfer Method - * Version Info: - * 1: Initial version */ -// ------------------------------------------------------------------------------------------------ -void PlayerList::xfer( Xfer *xfer ) -{ - - // version - XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - // xfer the player count - Int playerCount = m_playerCount; - xfer->xferInt( &playerCount ); - - // - // sanity, the player count read from the file should match our player count that - // was setup from the bare bones map load since that data can't change during run time - // - if( playerCount != m_playerCount ) - { - - DEBUG_CRASH(( "Invalid player count '%d', should be '%d'", playerCount, m_playerCount )); - throw SC_INVALID_DATA; - - } - - // xfer each of the player data - for( Int i = 0; i < playerCount; ++i ) - xfer->xferSnapshot( m_players[ i ] ); - -} - -// ------------------------------------------------------------------------------------------------ -/** Load post process */ -// ------------------------------------------------------------------------------------------------ -void PlayerList::loadPostProcess() -{ - -} - -//----------------------------------------------------------------------------- -void PlayerList::setSlotIndex(Int playerIndex, Int slotIndex) -{ - if (playerIndex >= 0 && playerIndex < ARRAY_SIZE(m_slotIndices)) - { - const Int oldSlotIndex = m_slotIndices[playerIndex]; - if (oldSlotIndex >= 0 && oldSlotIndex < ARRAY_SIZE(m_slotToPlayerIndices)) - { - m_slotToPlayerIndices[oldSlotIndex] = -1; - } - - m_slotIndices[playerIndex] = slotIndex; - - if (slotIndex >= 0 && slotIndex < ARRAY_SIZE(m_slotToPlayerIndices)) - { - m_slotToPlayerIndices[slotIndex] = playerIndex; - } - } -} - -//----------------------------------------------------------------------------- -Int PlayerList::getSlotIndex(Int playerIndex) const -{ - if (playerIndex >= 0 && playerIndex < ARRAY_SIZE(m_slotIndices)) - { - return m_slotIndices[playerIndex]; - } - - return -1; -} - -//----------------------------------------------------------------------------- -Int PlayerList::getPlayerIndexFromSlotIndex(Int slotIndex) const -{ - if (slotIndex >= 0 && slotIndex < ARRAY_SIZE(m_slotToPlayerIndices)) - { - return m_slotToPlayerIndices[slotIndex]; - } - - return -1; -} - -//----------------------------------------------------------------------------- -Player *PlayerList::getPlayerFromSlotIndex(Int slotIndex) const -{ - const Int playerIndex = getPlayerIndexFromSlotIndex(slotIndex); - if (playerIndex >= 0 && playerIndex < m_playerCount) - { - return m_players[playerIndex]; - } - - return nullptr; -} - -//----------------------------------------------------------------------------- -void PlayerList::assignSlotIndices(const GameInfo& gameInfo) -{ - AsciiString playerName; - - for (Int i = 0; i < MAX_SLOTS; ++i) - { - const GameSlot* slot = gameInfo.getConstSlot(i); - if (!slot || !slot->isOccupied()) - continue; - - playerName.format("player%d", i); - - if (Player* player = findPlayerWithNameKey(TheNameKeyGenerator->nameToKey(playerName))) - { - setSlotIndex(player->getPlayerIndex(), i); - } - } -} diff --git a/Generals/Code/GameEngine/Source/Common/RTS/PlayerTemplate.cpp b/Generals/Code/GameEngine/Source/Common/RTS/PlayerTemplate.cpp deleted file mode 100644 index 2bbe2eb0805..00000000000 --- a/Generals/Code/GameEngine/Source/Common/RTS/PlayerTemplate.cpp +++ /dev/null @@ -1,413 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: PlayerTemplate.cpp ///////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: RTS3 -// -// File name: PlayerTemplate.cpp -// -// Created: Steven Johnson, October 2001 -// -// Desc: @todo -// -//----------------------------------------------------------------------------- - -#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine - -#define DEFINE_VETERANCY_NAMES // for TheVeterancyNames[] - -#include "Common/GameCommon.h" -#include "Common/PlayerTemplate.h" -#include "Common/Player.h" -#include "Common/INI.h" -#include "Common/Science.h" -#include "GameClient/Image.h" - - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// PRIVATE DATA /////////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////////////////////////// - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// PRIVATE FUNCTIONS ////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////////////////////////// - -//------------------------------------------------------------------------------------------------- -/*static*/ const FieldParse* PlayerTemplate::getFieldParse() -{ - static const FieldParse TheFieldParseTable[] = - { - { "Side", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_side ) }, - { "BaseSide", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_baseSide ) }, - { "PlayableSide", INI::parseBool, nullptr, offsetof( PlayerTemplate, m_playableSide ) }, - { "DisplayName", INI::parseAndTranslateLabel, nullptr, offsetof( PlayerTemplate, m_displayName) }, - { "StartMoney", PlayerTemplate::parseStartMoney, nullptr, offsetof( PlayerTemplate, m_money ) }, - { "PreferredColor", INI::parseRGBColor, nullptr, offsetof( PlayerTemplate, m_preferredColor ) }, - { "StartingBuilding", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_startingBuilding ) }, - { "StartingUnit0", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_startingUnits[0] ) }, - { "StartingUnit1", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_startingUnits[1] ) }, - { "StartingUnit2", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_startingUnits[2] ) }, - { "StartingUnit3", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_startingUnits[3] ) }, - { "StartingUnit4", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_startingUnits[4] ) }, - { "StartingUnit5", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_startingUnits[5] ) }, - { "StartingUnit6", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_startingUnits[6] ) }, - { "StartingUnit7", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_startingUnits[7] ) }, - { "StartingUnit8", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_startingUnits[8] ) }, - { "StartingUnit9", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_startingUnits[9] ) }, - { "ProductionCostChange", PlayerTemplate::parseProductionCostChange, nullptr, 0 }, - { "ProductionTimeChange", PlayerTemplate::parseProductionTimeChange, nullptr, 0 }, - { "ProductionVeterancyLevel", PlayerTemplate::parseProductionVeterancyLevel, nullptr, 0 }, - { "IntrinsicSciences", INI::parseScienceVector, nullptr, offsetof( PlayerTemplate, m_intrinsicSciences ) }, - { "PurchaseScienceCommandSetRank1",INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_purchaseScienceCommandSetRank1 ) }, - { "PurchaseScienceCommandSetRank3",INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_purchaseScienceCommandSetRank3 ) }, - { "PurchaseScienceCommandSetRank8",INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_purchaseScienceCommandSetRank8 ) }, - { "SpecialPowerShortcutCommandSet",INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_specialPowerShortcutCommandSet ) }, - { "SpecialPowerShortcutWinName" ,INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_specialPowerShortcutWinName) }, - { "SpecialPowerShortcutButtonCount",INI::parseInt, nullptr, offsetof( PlayerTemplate, m_specialPowerShortcutButtonCount ) }, - { "IsObserver", INI::parseBool, nullptr, offsetof( PlayerTemplate, m_observer ) }, - { "OldFaction", INI::parseBool, nullptr, offsetof( PlayerTemplate, m_oldFaction ) }, - { "IntrinsicSciencePurchasePoints", INI::parseInt, nullptr, offsetof( PlayerTemplate, m_intrinsicSPP ) }, - { "ScoreScreenImage", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_scoreScreenImage ) }, - { "LoadScreenImage", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_loadScreenImage ) }, - { "LoadScreenMusic", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_loadScreenMusic ) }, - { "ScoreScreenMusic", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_scoreScreenMusic ) }, // Added in Zero Hour - - { "HeadWaterMark", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_headWaterMark ) }, - { "FlagWaterMark", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_flagWaterMark ) }, - { "EnabledImage", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_enabledImage ) }, - //{ "DisabledImage", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_disabledImage ) }, - //{ "HiliteImage", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_hiliteImage ) }, - //{ "PushedImage", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_pushedImage ) }, - { "SideIconImage", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_sideIconImage ) }, - { "GeneralImage", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_generalImage ) }, // Added in Zero Hour - - { "BeaconName", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_beaconTemplate ) }, - { "ArmyTooltip", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_tooltip ) }, // Added in Zero Hour - { "Features", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_strGeneralFeatures ) }, // Added in Zero Hour - { "MedallionRegular", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_strMedallionNormal ) }, // Added in Zero Hour - { "MedallionHilite", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_strMedallionHilite ) }, // Added in Zero Hour - { "MedallionSelect", INI::parseAsciiString, nullptr, offsetof( PlayerTemplate, m_strMedallionSelected ) }, // Added in Zero Hour - - { nullptr, nullptr, nullptr, 0 }, - }; - - return TheFieldParseTable; -} - -AsciiString PlayerTemplate::getStartingUnit( Int i ) const -{ - if (i<0 || i>= MAX_MP_STARTING_UNITS) - return AsciiString::TheEmptyString; - - return m_startingUnits[i]; -} - -//------------------------------------------------------------------------------------------------- -// This is is a Template, and a percent change to the cost of producing it. -/*static*/ void PlayerTemplate::parseProductionCostChange( INI* ini, void *instance, void *store, const void* /*userData*/ ) -{ - PlayerTemplate* self = (PlayerTemplate*)instance; - - NameKeyType buildTemplateKey = NAMEKEY(ini->getNextToken()); - Real percentChange = INI::scanPercentToReal(ini->getNextToken()); - - self->m_productionCostChanges[buildTemplateKey] = percentChange; -} - -//------------------------------------------------------------------------------------------------- -/*static*/ void PlayerTemplate::parseProductionTimeChange( INI* ini, void *instance, void *store, const void* /*userData*/ ) -{ - PlayerTemplate* self = (PlayerTemplate*)instance; - - NameKeyType buildTemplateKey = NAMEKEY(ini->getNextToken()); - Real percentChange = INI::scanPercentToReal(ini->getNextToken()); - - self->m_productionTimeChanges[buildTemplateKey] = percentChange; -} - -//------------------------------------------------------------------------------------------------- -/*static*/ void PlayerTemplate::parseProductionVeterancyLevel( INI* ini, void *instance, void *store, const void* /*userData*/ ) -{ - PlayerTemplate* self = (PlayerTemplate*)instance; - - // Format is ThingTemplatename VeterancyName - AsciiString HACK = AsciiString(ini->getNextToken()); - NameKeyType buildTemplateKey = NAMEKEY(HACK.str()); - - VeterancyLevel startLevel = (VeterancyLevel)INI::scanIndexList(ini->getNextToken(), TheVeterancyNames); - self->m_productionVeterancyLevels[buildTemplateKey] = startLevel; -} - -//------------------------------------------------------------------------------------------------- -/** Parse integer money and deposit in the m_money */ -//------------------------------------------------------------------------------------------------- -/*static*/ void PlayerTemplate::parseStartMoney( INI* ini, void *instance, void *store, const void* /*userData*/ ) -{ - Int money = 0; - - // parse the money as a regular "FIELD = " - INI::parseInt( ini, instance, &money, nullptr ); - - // assign the money into the 'Money' (m_money) pointed to at 'store' - Money *theMoney = (Money *)store; - theMoney->init(); - theMoney->setStartingCash(money); - -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// PUBLIC FUNCTIONS /////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -PlayerTemplate::PlayerTemplate() : - m_nameKey(NAMEKEY_INVALID), - m_observer(false), - m_playableSide(false), - m_oldFaction(false), - m_intrinsicSPP(0), - m_specialPowerShortcutButtonCount(0) -{ - m_preferredColor.red = m_preferredColor.green = m_preferredColor.blue = 0.0f; - m_beaconTemplate.clear(); -} - -//----------------------------------------------------------------------------- -const Image *PlayerTemplate::getHeadWaterMarkImage() const -{ - return TheMappedImageCollection->findImageByName(m_headWaterMark); -} - -//----------------------------------------------------------------------------- -const Image *PlayerTemplate::getFlagWaterMarkImage() const -{ - return TheMappedImageCollection->findImageByName(m_flagWaterMark); -} - -//----------------------------------------------------------------------------- -const Image *PlayerTemplate::getSideIconImage() const -{ - return TheMappedImageCollection->findImageByName(m_sideIconImage); -} - -//----------------------------------------------------------------------------- -const Image *PlayerTemplate::getGeneralImage() const -{ - return TheMappedImageCollection->findImageByName(m_generalImage); -} - -//----------------------------------------------------------------------------- -const Image *PlayerTemplate::getEnabledImage() const -{ - return TheMappedImageCollection->findImageByName(m_enabledImage); -} - -//----------------------------------------------------------------------------- -//const Image *PlayerTemplate::getDisabledImage() const -//{ -// return TheMappedImageCollection->findImageByName(m_disabledImage); -//} - -//----------------------------------------------------------------------------- -//const Image *PlayerTemplate::getHiliteImage() const -//{ -// return TheMappedImageCollection->findImageByName(m_hiliteImage); -//} - -//----------------------------------------------------------------------------- -//const Image *PlayerTemplate::getPushedImage() const -//{ -// return TheMappedImageCollection->findImageByName(m_pushedImage); -//} - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- - -/*extern*/ PlayerTemplateStore *ThePlayerTemplateStore = nullptr; - -//----------------------------------------------------------------------------- -PlayerTemplateStore::PlayerTemplateStore() -{ - // nothing -} - -//----------------------------------------------------------------------------- -PlayerTemplateStore::~PlayerTemplateStore() -{ - // nothing -} - -//----------------------------------------------------------------------------- -void PlayerTemplateStore::init() -{ - m_playerTemplates.clear(); -} - -//----------------------------------------------------------------------------- -void PlayerTemplateStore::reset() -{ -// don't reset this list here; we want to retain this info. -// m_playerTemplates.clear(); -} - -//----------------------------------------------------------------------------- -void PlayerTemplateStore::update() -{ - // nothing -} - - -Int PlayerTemplateStore::getTemplateNumByName(AsciiString name) const -{ - for (Int num = 0; num < m_playerTemplates.size(); num++) - { - if (m_playerTemplates[num].getName().compareNoCase(name.str()) == 0) - return num; - } - DEBUG_CRASH(("Template doesn't exist for given name")); - return -1; -} - -//----------------------------------------------------------------------------- -const PlayerTemplate* PlayerTemplateStore::findPlayerTemplate(NameKeyType namekey) const -{ -// begin ugly, hokey code to quietly load old maps... - static NameKeyType a0 = NAMEKEY("FactionAmerica"); - static NameKeyType a1 = NAMEKEY("FactionAmericaChooseAGeneral"); - static NameKeyType a2 = NAMEKEY("FactionAmericaTankCommand"); - static NameKeyType a3 = NAMEKEY("FactionAmericaSpecialForces"); - static NameKeyType a4 = NAMEKEY("FactionAmericaAirForce"); - - static NameKeyType c0 = NAMEKEY("FactionChina"); - static NameKeyType c1 = NAMEKEY("FactionChinaChooseAGeneral"); - static NameKeyType c2 = NAMEKEY("FactionChinaRedArmy"); - static NameKeyType c3 = NAMEKEY("FactionChinaSpecialWeapons"); - static NameKeyType c4 = NAMEKEY("FactionChinaSecretPolice"); - - static NameKeyType g0 = NAMEKEY("FactionGLA"); - static NameKeyType g1 = NAMEKEY("FactionGLAChooseAGeneral"); - static NameKeyType g2 = NAMEKEY("FactionGLATerrorCell"); - static NameKeyType g3 = NAMEKEY("FactionGLABiowarCommand"); - static NameKeyType g4 = NAMEKEY("FactionGLAWarlordCommand"); - - if (namekey == a1 || namekey == a2 || namekey == a3 || namekey == a4) - namekey = a0; - else if (namekey == c1 || namekey == c2 || namekey == c3 || namekey == c4) - namekey = c0; - else if (namekey == g1 || namekey == g2 || namekey == g3 || namekey == g4) - namekey = g0; -// end ugly, hokey code to quietly load old maps... - - #ifdef RTS_DEBUG - AsciiString nn = KEYNAME(namekey); - #endif - for (PlayerTemplateVector::const_iterator it = m_playerTemplates.begin(); it != m_playerTemplates.end(); ++it) - { - #ifdef RTS_DEBUG - AsciiString n = KEYNAME((*it).getNameKey()); - #endif - if ((*it).getNameKey() == namekey) - return &(*it); - } - return nullptr; -} - -//----------------------------------------------------------------------------- -const PlayerTemplate* PlayerTemplateStore::getNthPlayerTemplate(Int i) const -{ - if (i >= 0 && i < m_playerTemplates.size()) - return &m_playerTemplates[i]; - - return nullptr; -} - -//------------------------------------------------------------------------------------------------- -// @todo: PERF_EVALUATE Get a perf timer on this. -// If this function is called frequently, there are some relatively trivial changes we could make to -// have it run a lot faster. -void PlayerTemplateStore::getAllSideStrings(AsciiStringList *outStringList) -{ - if (!outStringList) - return; - - // should outStringList be cleared first? If so, that would go here - AsciiStringList tmpList; - - Int numTemplates = getPlayerTemplateCount(); - for ( Int i = 0; i < numTemplates; ++i ) - { - const PlayerTemplate *pt = getNthPlayerTemplate(i); - // Sanity - if (!pt) - continue; - - if (std::find(tmpList.begin(), tmpList.end(), pt->getSide()) == tmpList.end()) - tmpList.push_back(pt->getSide()); - } - // tmpList is now filled with all unique sides found in the player templates. - - // splice is a constant-time function which takes all elements from tmpList and - // inserts them before outStringList->end(), and also removes them from tmpList - outStringList->splice(outStringList->end(), tmpList); - - // all done -} - -//------------------------------------------------------------------------------------------------- -/*static*/ void PlayerTemplateStore::parsePlayerTemplateDefinition( INI* ini ) -{ - const char* c = ini->getNextToken(); - NameKeyType namekey = NAMEKEY(c); - - PlayerTemplate* pt = const_cast(ThePlayerTemplateStore->findPlayerTemplate(namekey)); - if (pt) - { - ini->initFromINI(pt, pt->getFieldParse() ); - pt->setNameKey(namekey); - } - else - { - PlayerTemplate npt; - ini->initFromINI( &npt, npt.getFieldParse() ); - npt.setNameKey(namekey); - ThePlayerTemplateStore->m_playerTemplates.push_back(npt); - } - -} - -//------------------------------------------------------------------------------------------------- -void INI::parsePlayerTemplateDefinition( INI* ini ) -{ - PlayerTemplateStore::parsePlayerTemplateDefinition(ini); -} - diff --git a/Generals/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp b/Generals/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp deleted file mode 100644 index 446a48c266c..00000000000 --- a/Generals/Code/GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp +++ /dev/null @@ -1,313 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: ProductionPrerequisite.cpp ///////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Westwood Studios Pacific. -// -// Confidential Information -// Copyright (C) 2001 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// Project: RTS3 -// -// File name: ProductionPrerequisite.cpp -// -// Created: Steven Johnson, October 2001 -// -// Desc: @todo -// -//----------------------------------------------------------------------------- - -#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine - -#include "Common/ProductionPrerequisite.h" -#include "Common/Player.h" -#include "Common/ThingFactory.h" -#include "Common/ThingTemplate.h" -#include "GameLogic/Object.h" -#include "GameClient/Drawable.h" -#include "GameClient/GameText.h" - - -//----------------------------------------------------------------------------- -ProductionPrerequisite::ProductionPrerequisite() -{ - init(); -} - -//----------------------------------------------------------------------------- -ProductionPrerequisite::~ProductionPrerequisite() -{ -} - -//----------------------------------------------------------------------------- -void ProductionPrerequisite::init() -{ - m_prereqUnits.clear(); - m_prereqSciences.clear(); - -} - -//============================================================================= -void ProductionPrerequisite::resolveNames() -{ - for (size_t i = 0; i < m_prereqUnits.size(); i++) - { - - // - // note that this will find the template at the "top most" level (not override - // sub-templates), which is what we want ... we conceptually only have one - // template for any given thing, it's only the *data* that is overridden - // - if( m_prereqUnits[ i ].name.isNotEmpty() ) - { - m_prereqUnits[i].unit = TheThingFactory->findTemplate(m_prereqUnits[i].name); // might be null - - /** @todo for now removing this assert until we can completely remove - the GDF stuff, the problem is that some INI files refer to GDF names, and they - aren't yet loaded in the world builder but will all go away later anyway etc */ - DEBUG_ASSERTCRASH(m_prereqUnits[i].unit,("could not find prereq %s",m_prereqUnits[i].name.str())); - - m_prereqUnits[i].name.clear(); // we're done with it - } - - } - -} - -//----------------------------------------------------------------------------- -Int ProductionPrerequisite::calcNumPrereqUnitsOwned(const Player *player, Int counts[MAX_PREREQ]) const -{ - const ThingTemplate *tmpls[MAX_PREREQ]; - Int cnt = m_prereqUnits.size(); - if (cnt > MAX_PREREQ) - cnt = MAX_PREREQ; - for (int i = 0; i < cnt; i++) - tmpls[i] = m_prereqUnits[i].unit; - player->countObjectsByThingTemplate(cnt, tmpls, false, counts); - return cnt; -} - -//----------------------------------------------------------------------------- -Int ProductionPrerequisite::getAllPossibleBuildFacilityTemplates(const ThingTemplate* tmpls[], Int maxtmpls) const -{ - Int count = 0; - for (size_t i = 0; i < m_prereqUnits.size(); i++) - { - if (i > 0 && !(m_prereqUnits[i].flags & UNIT_OR_WITH_PREV)) - break; - if (count >= maxtmpls) - break; - tmpls[count++] = m_prereqUnits[i].unit; - } - return count; -} - -//----------------------------------------------------------------------------- -const ThingTemplate *ProductionPrerequisite::getExistingBuildFacilityTemplate( const Player *player ) const -{ - DEBUG_ASSERTCRASH(player, ("player may not be null")); - if (!m_prereqUnits.empty()) - { - Int ownCount[MAX_PREREQ]; - Int cnt = calcNumPrereqUnitsOwned(player, ownCount); - for (int i = 0; i < cnt; i++) - { - if (i > 0 && !(m_prereqUnits[i].flags & UNIT_OR_WITH_PREV)) - break; - if (ownCount[i]) - return m_prereqUnits[i].unit; - } - } - return nullptr; -} - -//----------------------------------------------------------------------------- -Bool ProductionPrerequisite::isSatisfied(const Player *player) const -{ - Int i; - - if (!player) - return false; - - // gotta have all the prereq sciences. - for (i = 0; i < m_prereqSciences.size(); i++) - { - if (!player->hasScience(m_prereqSciences[i])) - return false; - } - - // the player must have at least one instance of each prereq unit. - Int ownCount[MAX_PREREQ]; - Int cnt = calcNumPrereqUnitsOwned(player, ownCount); - - // fix up the "or" cases. (start at 1!) - for (i = 1; i < cnt; i++) - { - if (m_prereqUnits[i].flags & UNIT_OR_WITH_PREV) - { - ownCount[i] += ownCount[i-1]; // lump 'em together for prereq purposes - ownCount[i-1] = -1; // flag for "ignore me" - } - } - - for (i = 0; i < cnt; i++) - { - if (ownCount[i] == -1) // the magic "ignore me" flag - continue; - if (ownCount[i] == 0) // everything not ignored, is required - return false; - } - - return true; -} - -//------------------------------------------------------------------------------------------------- -/** Add a unit prerequisite, if 'orWithPrevious' is set then this unit is said - * to be an alternate prereq to the previously added unit, otherwise this becomes - * a new 'block' and is required in ADDITION to other entries. - * Return FALSE if no space left to add unit */ -//------------------------------------------------------------------------------------------------- -void ProductionPrerequisite::addUnitPrereq( AsciiString unit, Bool orUnitWithPrevious ) -{ - PrereqUnitRec info; - info.name = unit; - info.flags = orUnitWithPrevious ? UNIT_OR_WITH_PREV : 0; - info.unit = nullptr; - m_prereqUnits.push_back(info); - -} - -//------------------------------------------------------------------------------------------------- -/** Add a unit prerequisite, if 'orWithPrevious' is set then this unit is said - * to be an alternate prereq to the previously added unit, otherwise this becomes - * a new 'block' and is required in ADDITION to other entries. - * Return FALSE if no space left to add unit */ -//------------------------------------------------------------------------------------------------- -void ProductionPrerequisite::addUnitPrereq( const std::vector& units ) -{ - Bool orWithPrevious = false; - for (size_t i = 0; i < units.size(); ++i) - { - addUnitPrereq(units[i], orWithPrevious); - orWithPrevious = true; - } - -} - -//------------------------------------------------------------------------------------------------- -// returns an asciistring which is a list of all the prerequisites -// not satisfied yet -UnicodeString ProductionPrerequisite::getRequiresList(const Player *player) const -{ - - // if player is invalid, return empty string - if (!player) - return UnicodeString::TheEmptyString; - - UnicodeString requiresList = UnicodeString::TheEmptyString; - - // check the prerequired units - Int ownCount[MAX_PREREQ]; - Int cnt = calcNumPrereqUnitsOwned(player, ownCount); - Int i; - - Bool orRequirements[MAX_PREREQ]; - for (i = 0; i < MAX_PREREQ; i++) - { - orRequirements[i] = FALSE; - } - // account for the "or" unit cases, start for loop at 1 - for (i = 1; i < cnt; i++) - { - if (m_prereqUnits[i].flags & UNIT_OR_WITH_PREV) - { - orRequirements[i] = TRUE; // set the flag for this unit to be "ored" with previous - ownCount[i] += ownCount[i-1]; // lump 'em together for prereq purposes - ownCount[i-1] = -1; // flag for "ignore me" - } - } - - // check to see if anything is required - const ThingTemplate *unit; - UnicodeString unitName; - Bool firstRequirement = true; - for (i = 0; i < cnt; i++) - { - // we have an unfulfilled requirement - if (ownCount[i] == 0) { - - if(orRequirements[i]) - { - unit = m_prereqUnits[i-1].unit; - unitName = unit->getDisplayName(); - unitName.concat( L" " ); - unitName.concat(TheGameText->fetch("CONTROLBAR:OrRequirement", nullptr)); - unitName.concat( L" " ); - requiresList.concat(unitName); - } - - // get the requirement and then its name - unit = m_prereqUnits[i].unit; - unitName = unit->getDisplayName(); - - // gets command button, and then modifies unitName - //CommandButton *cmdButton = TheControlBar->findCommandButton(unit->getName()); - //if (cmdButton) - //unitName.translate(TheGameText->fetch(cmdButton->m_textLabel.str())); - - // format name appropriately with 'returns' if necessary - if (firstRequirement) - firstRequirement = false; - else - unitName.concat(L"\n"); - - // add it to the list - requiresList.concat(unitName); - } - } - - Bool hasSciences = TRUE; - // gotta have all the prereq sciences. - for (i = 0; i < m_prereqSciences.size(); i++) - { - if (!player->hasScience(m_prereqSciences[i])) - hasSciences = FALSE; - } - - if (hasSciences == FALSE) { - if (firstRequirement) { - firstRequirement = false; - } else { - unitName.concat(L"\n"); - } - requiresList.concat(TheGameText->fetch("CONTROLBAR:GeneralsPromotion", nullptr)); - } - - // return final list - return requiresList; -} diff --git a/Generals/Code/GameEngine/Source/Common/RTS/ResourceGatheringManager.cpp b/Generals/Code/GameEngine/Source/Common/RTS/ResourceGatheringManager.cpp deleted file mode 100644 index b7433ae5b7f..00000000000 --- a/Generals/Code/GameEngine/Source/Common/RTS/ResourceGatheringManager.cpp +++ /dev/null @@ -1,291 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: ResourceGatheringManager.cpp /////////////////////////////////////////////////////////// -// The part of a Player's brain that keeps track of all Resource type Objects and makes -// gathering type decisions based on them. -// Author: Graham Smallwood, January, 2002 - -#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine - -#include "Common/ResourceGatheringManager.h" - -#include "Common/ActionManager.h" -#include "Common/Xfer.h" -#include "GameLogic/GameLogic.h" -#include "GameLogic/Object.h" -#include "GameLogic/PartitionManager.h" -#include "GameLogic/Module/SupplyTruckAIUpdate.h" -#include "GameLogic/Module/SupplyCenterDockUpdate.h" -#include "GameLogic/Module/SupplyWarehouseDockUpdate.h" -#include "GameLogic/Module/UpdateModule.h" - -ResourceGatheringManager::ResourceGatheringManager() -{ -} - -ResourceGatheringManager::~ResourceGatheringManager() -{ - m_supplyWarehouses.erase( m_supplyWarehouses.begin(), m_supplyWarehouses.end() ); - m_supplyCenters.erase( m_supplyCenters.begin(), m_supplyCenters.end() ); -} - -void ResourceGatheringManager::addSupplyCenter( Object *newCenter ) -{ - if( newCenter == nullptr ) - return; - - m_supplyCenters.push_back( newCenter->getID() ); -} - -void ResourceGatheringManager::removeSupplyCenter( Object *oldCenter ) -{ - if( oldCenter == nullptr ) - return; - - ObjectID targetID = oldCenter->getID(); - - objectIDListIterator iterator = m_supplyCenters.begin(); - while( iterator != m_supplyCenters.end() ) - { - if( targetID == *iterator ) - { - iterator = m_supplyCenters.erase( iterator ); - } - else - iterator++; - } -} - -void ResourceGatheringManager::addSupplyWarehouse( Object *newWarehouse ) -{ - if( newWarehouse == nullptr ) - return; - - m_supplyWarehouses.push_back( newWarehouse->getID() ); -} - -void ResourceGatheringManager::removeSupplyWarehouse( Object *oldWarehouse ) -{ - if( oldWarehouse == nullptr ) - return; - - ObjectID targetID = oldWarehouse->getID(); - - objectIDListIterator iterator = m_supplyWarehouses.begin(); - while( iterator != m_supplyWarehouses.end() ) - { - if( targetID == *iterator ) - { - iterator = m_supplyWarehouses.erase( iterator ); - } - else - iterator++; - } -} - -static Real computeRelativeCost( Object *queryObject, Object *destObject, Real *pureDistanceSquared ) -{ - /** @todo This gets filled with Pathfinding computations, analysis of Boxes remaining, - Threat calculations, paths of other trucks, and other fancy stuff. - */ - - //A good score is a very small number. - - if( queryObject == nullptr || destObject == nullptr ) - return FLT_MAX; - - if( !TheActionManager->canTransferSuppliesAt(queryObject, destObject) ) - return FLT_MAX;// Handles emptiness and alliances - - DockUpdateInterface *dockInterface = destObject->getDockUpdateInterface(); - if( !dockInterface->isClearToApproach( queryObject ) ) - return FLT_MAX; - - // since we don't care about the distance as a distance per se, but rather as - // a goodness-factor, save some time by getting the dist-sqr (srj) - Real distSquared = ThePartitionManager->getDistanceSquared(queryObject, destObject, FROM_CENTER_3D); - - // I need the distance, but I don't want to count on the coincidence that - // the abstract 'cost' this function returns happens to be just the distance, since it could - // become more complicated - if( pureDistanceSquared ) - *pureDistanceSquared = distSquared; - - return distSquared; -} - -Object *ResourceGatheringManager::findBestSupplyWarehouse( Object *queryObject ) -{ - Object *bestWarehouse = nullptr; - Real maxDistanceSquared = 100000; - - if( ( queryObject == nullptr ) || ( queryObject->getAI() == nullptr ) ) - return nullptr; - - SupplyTruckAIInterface *supplyTruckAI = queryObject->getAI()->getSupplyTruckAIInterface(); - if( supplyTruckAI ) - { - // Check for a dock override being set. - ObjectID dockID = supplyTruckAI->getPreferredDockID(); - Object *dock = TheGameLogic->findObjectByID(dockID); - if( dock ) - { - static const NameKeyType key_warehouseUpdate = NAMEKEY("SupplyWarehouseDockUpdate"); - SupplyWarehouseDockUpdate *warehouseModule = (SupplyWarehouseDockUpdate*)dock->findUpdateModule( key_warehouseUpdate ); - //If remotely okay, let User win. - if( warehouseModule && computeRelativeCost( queryObject, dock, nullptr ) != FLT_MAX ) - return dock; - } - // Please note, there is not a separate Warehouse and Center memory by Design. Because - // we lack a UI way to click Warehouse and drag to center to set up a specific path, the - // practical realization has been made that you do not want separate memory. - - // Design wants a harvester to give up and return to base if it is "too far" to the warehouse. - // Note, the "PreferedDock" will override this, and there is no distance max on Centers. - maxDistanceSquared = supplyTruckAI->getWarehouseScanDistance() * supplyTruckAI->getWarehouseScanDistance(); - } - - //Otherwise, search for a good one. - Real bestCost = FLT_MAX; - - objectIDListIterator iterator = m_supplyWarehouses.begin(); - while( iterator != m_supplyWarehouses.end() ) - { - ObjectID currentID = *iterator; - Object *currentWarehouse =TheGameLogic->findObjectByID(currentID); - - if( currentWarehouse == nullptr ) - { - iterator = m_supplyWarehouses.erase( iterator ); - } - else - { - Real distanceSquared; - Real currentCost = computeRelativeCost( queryObject, currentWarehouse, &distanceSquared ); - if( (currentCost < bestCost) && (distanceSquared < maxDistanceSquared) ) - { - bestWarehouse = currentWarehouse; - bestCost = currentCost; - } - - iterator++; - } - } - - return bestWarehouse; -} - -Object *ResourceGatheringManager::findBestSupplyCenter( Object *queryObject ) -{ - Object *bestCenter = nullptr; - - if( ( queryObject == nullptr ) || ( queryObject->getAI() == nullptr ) ) - return nullptr; - - SupplyTruckAIInterface *supplyTruckAI = queryObject->getAI()->getSupplyTruckAIInterface(); - if( supplyTruckAI ) - { - // Check for a dock override being set. - ObjectID dockID = supplyTruckAI->getPreferredDockID(); - Object *dock = TheGameLogic->findObjectByID(dockID); - if( dock ) - { - static const NameKeyType key_centerUpdate = NAMEKEY("SupplyCenterDockUpdate"); - SupplyCenterDockUpdate *centerModule = (SupplyCenterDockUpdate*)dock->findUpdateModule( key_centerUpdate ); - //If remotely okay, let User win. - if( centerModule && computeRelativeCost( queryObject, dock, nullptr ) != FLT_MAX ) - return dock; - } - // Please note, there is not a separate Warehouse and Center memory by Design. Because - // we lack a UI way to click Warehouse and drag to center to set up a specific path, the - // practical realization has been made that you do not want separate memory. - } - - //Otherwise, search for a good one. - Real bestCost = FLT_MAX; - - objectIDListIterator iterator = m_supplyCenters.begin(); - while( iterator != m_supplyCenters.end() ) - { - ObjectID currentID = *iterator; - Object *currentCenter =TheGameLogic->findObjectByID(currentID); - - if( currentCenter == nullptr ) - { - iterator = m_supplyCenters.erase( iterator ); - } - else - { - Real currentCost = computeRelativeCost( queryObject, currentCenter, nullptr ); - if( currentCost < bestCost ) - { - bestCenter = currentCenter; - bestCost = currentCost; - } - - iterator++; - } - } - - return bestCenter; -} - -// ------------------------------------------------------------------------------------------------ -/** CRC */ -// ------------------------------------------------------------------------------------------------ -void ResourceGatheringManager::crc( Xfer *xfer ) -{ - -} - -// ------------------------------------------------------------------------------------------------ -/** Xfer method - * Version Info: - * 1: Initial version */ -// ------------------------------------------------------------------------------------------------ -void ResourceGatheringManager::xfer( Xfer *xfer ) -{ - - // version - XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - // supply warehouses - xfer->xferSTLObjectIDList( &m_supplyWarehouses ); - - // supply centers - xfer->xferSTLObjectIDList( &m_supplyCenters ); - -} - -// ------------------------------------------------------------------------------------------------ -/** Load post process */ -// ------------------------------------------------------------------------------------------------ -void ResourceGatheringManager::loadPostProcess() -{ - -} - diff --git a/Generals/Code/GameEngine/Source/Common/RTS/Science.cpp b/Generals/Code/GameEngine/Source/Common/RTS/Science.cpp deleted file mode 100644 index 6cb201b2467..00000000000 --- a/Generals/Code/GameEngine/Source/Common/RTS/Science.cpp +++ /dev/null @@ -1,376 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: Science.cpp ///////////////////////////////////////////////////////// -// Created: Steven Johnson, October 2001 -// Desc: @todo -//----------------------------------------------------------------------------- - -#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine - -#include "Common/INI.h" -#include "Common/Player.h" -#include "Common/Science.h" - -ScienceStore* TheScienceStore = nullptr; - - -//----------------------------------------------------------------------------- -void ScienceStore::init() -{ - DEBUG_ASSERTCRASH(m_sciences.empty(), ("Hmm")); - m_sciences.clear(); -} - -//----------------------------------------------------------------------------- -ScienceStore::~ScienceStore() -{ - // nope. - //m_sciences.clear(); - - // go through all sciences and delete any overrides - for (ScienceInfoVec::iterator it = m_sciences.begin(); it != m_sciences.end(); /*++it*/) - { - ScienceInfo* si = *it; - ++it; - deleteInstance(si); - } -} - -//----------------------------------------------------------------------------- -void ScienceStore::reset() -{ - // nope. - //m_sciences.clear(); - - // go through all sciences and delete any overrides - for (ScienceInfoVec::iterator it = m_sciences.begin(); it != m_sciences.end(); /*++it*/) - { - ScienceInfo* si = *it; - Overridable* temp = si->deleteOverrides(); - if (!temp) - { - it = m_sciences.erase(it); - } - else - { - ++it; - } - } -} - -//----------------------------------------------------------------------------- -ScienceType ScienceStore::getScienceFromInternalName(const AsciiString& name) const -{ - if (name.isEmpty()) - return SCIENCE_INVALID; - NameKeyType nkt = TheNameKeyGenerator->nameToKey(name); - ScienceType st = (ScienceType)nkt; - return st; -} - -//----------------------------------------------------------------------------- -AsciiString ScienceStore::getInternalNameForScience(ScienceType science) const -{ - if (science == SCIENCE_INVALID) - return AsciiString::TheEmptyString; - NameKeyType nk = (NameKeyType)(science); - return TheNameKeyGenerator->keyToName(nk); -} - -//----------------------------------------------------------------------------- -// return a vector of all the currently-known science names -// NOTE: this is really only for use by WorldBuilder! Please -// do not use it in RTS! -std::vector ScienceStore::friend_getScienceNames() const -{ - std::vector v; - for (ScienceInfoVec::const_iterator it = m_sciences.begin(); it != m_sciences.end(); ++it) - { - const ScienceInfo* si = (const ScienceInfo*)(*it)->getFinalOverride(); - NameKeyType nk = (NameKeyType)(si->m_science); - v.push_back(TheNameKeyGenerator->keyToName(nk)); - } - return v; -} - -//----------------------------------------------------------------------------- -void ScienceInfo::addRootSciences(ScienceVec& v) const -{ - if (m_prereqSciences.empty()) - { - // we're a root. add ourselves. - if (std::find(v.begin(), v.end(), m_science) == v.end()) - v.push_back(m_science); - } - else - { - // we're not a root. add the roots of all our prereqs. - for (ScienceVec::const_iterator it = m_prereqSciences.begin(); it != m_prereqSciences.end(); ++it) - { - const ScienceInfo* si = TheScienceStore->findScienceInfo(*it); - if (si) - si->addRootSciences(v); - } - } -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -const ScienceInfo* ScienceStore::findScienceInfo(ScienceType st) const -{ - for (ScienceInfoVec::const_iterator it = m_sciences.begin(); it != m_sciences.end(); ++it) - { - const ScienceInfo* si = (const ScienceInfo*)(*it)->getFinalOverride(); - if (si->m_science == st) - { - return si; - } - } - return nullptr; -} - -//----------------------------------------------------------------------------- -/*static*/ void ScienceStore::friend_parseScienceDefinition( INI* ini ) -{ - const char* c = ini->getNextToken(); - NameKeyType nkt = NAMEKEY(c); - ScienceType st = (ScienceType)nkt; - - if (TheScienceStore) - { - - static const FieldParse myFieldParse[] = - { - { "PrerequisiteSciences", INI::parseScienceVector, nullptr, offsetof( ScienceInfo, m_prereqSciences ) }, - { "SciencePurchasePointCost", INI::parseInt, nullptr, offsetof( ScienceInfo, m_sciencePurchasePointCost ) }, - { "IsGrantable", INI::parseBool, nullptr, offsetof( ScienceInfo, m_grantable ) }, - { "DisplayName", INI::parseAndTranslateLabel, nullptr, offsetof( ScienceInfo, m_name) }, - { "Description", INI::parseAndTranslateLabel, nullptr, offsetof( ScienceInfo, m_description) }, - { nullptr, nullptr, nullptr, 0 } - }; - - ScienceInfo* info = nullptr; - - // see if the science already exists. (can't use findScienceInfo() since it is const and should remain so.) - for (ScienceInfoVec::iterator it = TheScienceStore->m_sciences.begin(); it != TheScienceStore->m_sciences.end(); ++it) - { - // note that we don't use getFinalOverride here. this is correct and as-desired. - if ((*it)->m_science == st) - { - info = *it; - break; - } - } - - if (ini->getLoadType() == INI_LOAD_CREATE_OVERRIDES) - { - ScienceInfo* newInfo = newInstance(ScienceInfo); - - if (info == nullptr) - { - // only add if it's not overriding an existing one. - info = newInfo; - info->markAsOverride(); // yep, so we will get cleared on reset() - TheScienceStore->m_sciences.push_back(info); - } - else - { - // copy data from final override to 'newInfo' as a set of initial default values - info = (ScienceInfo*)(info->friend_getFinalOverride()); - - *newInfo = *info; - info->setNextOverride(newInfo); - newInfo->markAsOverride(); // must do AFTER the copy - - // use the newly created override for us to set values with etc - info = newInfo; - //TheScienceStore->m_sciences.push_back(info); // NO, BAD, WRONG -- don't add in this case. - } - } - else - { - if (info != nullptr) - { - DEBUG_CRASH(("duplicate science %s!",c)); - throw INI_INVALID_DATA; - } - info = newInstance(ScienceInfo); - TheScienceStore->m_sciences.push_back(info); - } - - ini->initFromINI(info, myFieldParse); - info->m_science = st; - info->addRootSciences(info->m_rootSciences); - } -} - -//----------------------------------------------------------------------------- -Int ScienceStore::getSciencePurchaseCost(ScienceType st) const -{ - const ScienceInfo* si = findScienceInfo(st); - if (si) - { - return si->m_sciencePurchasePointCost; - } - else - { - return 0; - } -} - -//----------------------------------------------------------------------------- -Bool ScienceStore::isScienceGrantable(ScienceType st) const -{ - const ScienceInfo* si = findScienceInfo(st); - if (si) - { - return si->m_grantable; - } - else - { - return false; - } -} - -//----------------------------------------------------------------------------- -Bool ScienceStore::getNameAndDescription(ScienceType st, UnicodeString& name, UnicodeString& description) const -{ - const ScienceInfo* si = findScienceInfo(st); - if (si) - { - name = si->m_name; - description = si->m_description; - return true; - } - else - { - return false; - } -} - -//----------------------------------------------------------------------------- -Bool ScienceStore::playerHasPrereqsForScience(const Player* player, ScienceType st) const -{ - const ScienceInfo* si = findScienceInfo(st); - if (si) - { - for (ScienceVec::const_iterator it2 = si->m_prereqSciences.begin(); it2 != si->m_prereqSciences.end(); ++it2) - { - if (!player->hasScience(*it2)) - { - return false; - } - } - return true; - } - else - { - return false; - } -} - -//----------------------------------------------------------------------------- -Bool ScienceStore::playerHasRootPrereqsForScience(const Player* player, ScienceType st) const -{ - const ScienceInfo* si = findScienceInfo(st); - if (si) - { - for (ScienceVec::const_iterator it2 = si->m_rootSciences.begin(); it2 != si->m_rootSciences.end(); ++it2) - { - if (!player->hasScience(*it2)) - { - return false; - } - } - return true; - } - else - { - return false; - } -} - -//----------------------------------------------------------------------------- -/** return a list of the sciences the given player can purchase now, and a list he might be able to purchase in the future, - but currently lacks prereqs or points for. (either might be an empty list) */ -void ScienceStore::getPurchasableSciences(const Player* player, ScienceVec& purchasable, ScienceVec& potentiallyPurchasable) const -{ - purchasable.clear(); - potentiallyPurchasable.clear(); - for (ScienceInfoVec::const_iterator it = m_sciences.begin(); it != m_sciences.end(); ++it) - { - const ScienceInfo* si = (const ScienceInfo*)(*it)->getFinalOverride(); - - if (si->m_sciencePurchasePointCost == 0) - { - // 0 means "cannot be purchased" - continue; - } - - if (player->hasScience(si->m_science)) - { - continue; - } - - if (playerHasPrereqsForScience(player, si->m_science)) - { - purchasable.push_back(si->m_science); - } - else if (playerHasRootPrereqsForScience(player, si->m_science)) - { - potentiallyPurchasable.push_back(si->m_science); - } - } -} - -//----------------------------------------------------------------------------- -// this is intended ONLY for use by INI::scanScience. -// Don't use it anywhere else. In particular, never, ever, ever -// call this with a hardcoded science name. (srj) -ScienceType ScienceStore::friend_lookupScience(const char* scienceName) const -{ - NameKeyType nkt = NAMEKEY(scienceName); - ScienceType st = (ScienceType)nkt; - if (!isValidScience(st)) - { - DEBUG_CRASH(("Science name %s not known! (Did you define it in Science.ini?)",scienceName)); - throw INI_INVALID_DATA; - } - return st; -} - -//----------------------------------------------------------------------------- -Bool ScienceStore::isValidScience(ScienceType st) const -{ - const ScienceInfo* si = findScienceInfo(st); - return si != nullptr; -} - -//----------------------------------------------------------------------------- -void INI::parseScienceDefinition( INI* ini ) -{ - ScienceStore::friend_parseScienceDefinition(ini); -} - diff --git a/Generals/Code/GameEngine/Source/Common/RTS/ScoreKeeper.cpp b/Generals/Code/GameEngine/Source/Common/RTS/ScoreKeeper.cpp deleted file mode 100644 index 96396f14279..00000000000 --- a/Generals/Code/GameEngine/Source/Common/RTS/ScoreKeeper.cpp +++ /dev/null @@ -1,565 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: ScoreKeeper.cpp ///////////////////////////////////////////////// -//----------------------------------------------------------------------------- -// -// Electronic Arts Pacific. -// -// Confidential Information -// Copyright (C) 2002 - All Rights Reserved -// -//----------------------------------------------------------------------------- -// -// created: Jun 2002 -// -// Filename: ScoreKeeper.cpp -// -// author: Chris Huybregts -// -// purpose: Score Keeper class will be an object attached to each player -// that will maintain accurate counts for the various stats we -// want to show on the score screen. The information in here -// could also be used for the observer screen -// -//----------------------------------------------------------------------------- -/////////////////////////////////////////////////////////////////////////////// - -//----------------------------------------------------------------------------- -// SYSTEM INCLUDES //////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- - -//----------------------------------------------------------------------------- -// USER INCLUDES ////////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- -#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine - -#include "Common/GameState.h" -#include "Common/KindOf.h" -#include "Common/Player.h" -#include "Common/ScoreKeeper.h" -#include "Common/ThingFactory.h" -#include "Common/ThingTemplate.h" -#include "Common/Xfer.h" - -#include "GameLogic/Object.h" -#include "GameLogic/GameLogic.h" - -//----------------------------------------------------------------------------- -// DEFINES //////////////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- - -//----------------------------------------------------------------------------- -// PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- - -ScoreKeeper::ScoreKeeper() -{ - reset(0); -} - -ScoreKeeper::~ScoreKeeper() -{ - -} - -static KindOfMaskType scoringBuildingMask; -static KindOfMaskType scoringBuildingDestroyMask; -static KindOfMaskType scoringBuildingCreateMask; - -void ScoreKeeper::reset( Int playerIdx ) -{ - scoringBuildingMask.set(KINDOF_STRUCTURE); - scoringBuildingMask.set(KINDOF_SCORE); - - scoringBuildingCreateMask.set(KINDOF_STRUCTURE); - scoringBuildingCreateMask.set(KINDOF_SCORE_CREATE); - - scoringBuildingDestroyMask.set(KINDOF_STRUCTURE); - scoringBuildingDestroyMask.set(KINDOF_SCORE_DESTROY); - - m_totalMoneyEarned = m_totalMoneySpent = 0; - m_totalUnitsLost = m_totalUnitsBuilt = 0; - m_totalBuildingsLost = m_totalBuildingsBuilt = 0; - m_totalFactionBuildingsCaptured = m_totalTechBuildingsCaptured = 0; - m_currentScore = 0; - m_objectsBuilt.clear(); - m_objectsCaptured.clear(); - m_objectsLost.clear(); - for(int i = 0; i < MAX_PLAYER_COUNT; ++i) - { - m_objectsDestroyed[i].clear(); - m_totalBuildingsDestroyed[i] = m_totalUnitsDestroyed[i] = 0; - } - m_myPlayerIdx = playerIdx; -} - -void ScoreKeeper::addObjectBuilt( const Object *o) -{ - Bool addToCount = FALSE; - - if (TheGameLogic->isScoringEnabled() == FALSE) { - return; - } - - if(o->getTemplate()->isKindOfMulti(scoringBuildingMask, KINDOFMASK_NONE)) - { - ++m_totalBuildingsBuilt; - addToCount = TRUE; - } - else if (o->getTemplate()->isKindOfMulti(scoringBuildingCreateMask, KINDOFMASK_NONE)) - { - ++m_totalBuildingsBuilt; - addToCount = TRUE; - } - else if(o->getTemplate()->isKindOf(KINDOF_INFANTRY) || o->getTemplate()->isKindOf(KINDOF_VEHICLE)) - { - if (o->getTemplate()->isKindOf(KINDOF_SCORE) || o->getTemplate()->isKindOf(KINDOF_SCORE_CREATE)) - { - ++m_totalUnitsBuilt; - addToCount = TRUE; - } - } - - if(addToCount) - { - Int existingCount = 0; - ObjectCountMapIt it = m_objectsBuilt.find(o->getTemplate()); - if (it != m_objectsBuilt.end()) - existingCount = it->second; - m_objectsBuilt[o->getTemplate()] = existingCount + 1; - } -} - -Int ScoreKeeper::getTotalUnitsBuilt( KindOfMaskType validMask, KindOfMaskType invalidMask ) -{ - Int count = 0; - for (ObjectCountMapIt it = m_objectsBuilt.begin(); it != m_objectsBuilt.end(); ++it) - { - const ThingTemplate *theTemplate = it->first; - Int numBuilt = it->second; - if (theTemplate && theTemplate->isKindOfMulti(validMask, invalidMask)) - count += numBuilt; - } - return count; -} - -Int ScoreKeeper::getTotalObjectsBuilt( const ThingTemplate *pTemplate ) -{ - Int count = 0; - for (ObjectCountMapIt it = m_objectsBuilt.begin(); it != m_objectsBuilt.end(); ++it) - { - const ThingTemplate *theTemplate = it->first; - if (theTemplate && theTemplate->isEquivalentTo(pTemplate)) - ++count; - } - return count; -} - - -void ScoreKeeper::removeObjectBuilt( const Object *o) -{ - if (TheGameLogic->isScoringEnabled() == FALSE) { - return; - } - - Bool removeFromCount = FALSE; - if (o->getTemplate()->isKindOfMulti(scoringBuildingMask, KINDOFMASK_NONE)) - { - --m_totalBuildingsBuilt; - removeFromCount = TRUE; - } - else if (o->getTemplate()->isKindOfMulti(scoringBuildingCreateMask, KINDOFMASK_NONE)) - { - --m_totalBuildingsBuilt; - removeFromCount = TRUE; - } - else if (o->getTemplate()->isKindOf(KINDOF_INFANTRY) || o->getTemplate()->isKindOf(KINDOF_VEHICLE)) - { - if (o->getTemplate()->isKindOf(KINDOF_SCORE) || o->getTemplate()->isKindOf(KINDOF_SCORE_CREATE)) - { - --m_totalUnitsBuilt; - removeFromCount = TRUE; - } - } - - if (removeFromCount) - { - Int existingCount = 0; - ObjectCountMapIt it = m_objectsBuilt.find(o->getTemplate()); - if (it != m_objectsBuilt.end()) - existingCount = it->second; - m_objectsBuilt[o->getTemplate()] = existingCount - 1; - } -} - -void ScoreKeeper::addObjectCaptured( const Object *o ) -{ - if (TheGameLogic->isScoringEnabled() == FALSE) { - return; - } - - Bool addToCount = FALSE; - if(o->getTemplate()->isKindOf(KINDOF_STRUCTURE)) - { - if (o->getTemplate()->isKindOf(KINDOF_SCORE)) - { - ++m_totalFactionBuildingsCaptured; - } - else - { - ++m_totalTechBuildingsCaptured; - } - addToCount = TRUE; - } - - if(addToCount) - { - Int existingCount = 0; - ObjectCountMapIt it = m_objectsCaptured.find(o->getTemplate()); - if (it != m_objectsCaptured.end()) - existingCount = it->second; - m_objectsCaptured[o->getTemplate()] = existingCount + 1; - } -} - - - -void ScoreKeeper::addObjectDestroyed( const Object *o) -{ - - if (TheGameLogic->isScoringEnabled() == FALSE) { - return; - } - - Int playerIdx = o->getControllingPlayer()->getPlayerIndex(); - - Bool addToCount = FALSE; - if(o->getTemplate()->isKindOfMulti(scoringBuildingMask, KINDOFMASK_NONE)) - { - if (!(o->testStatus(OBJECT_STATUS_UNDER_CONSTRUCTION))) { - ++m_totalBuildingsDestroyed[playerIdx]; - addToCount = TRUE; - } - } - else if (o->getTemplate()->isKindOfMulti(scoringBuildingDestroyMask, KINDOFMASK_NONE)) - { - if (!(o->testStatus(OBJECT_STATUS_UNDER_CONSTRUCTION))) { - ++m_totalBuildingsDestroyed[playerIdx]; - addToCount = TRUE; - } - } - else if(o->getTemplate()->isKindOf(KINDOF_INFANTRY) || o->getTemplate()->isKindOf(KINDOF_VEHICLE)) - { - if (o->getTemplate()->isKindOf(KINDOF_SCORE) || o->getTemplate()->isKindOf(KINDOF_SCORE_DESTROY)) - { - if (!(o->testStatus(OBJECT_STATUS_UNDER_CONSTRUCTION))) { - m_totalUnitsDestroyed[playerIdx]++; - addToCount = TRUE; - } - } - } - - if(addToCount) - { - Int existingCount = 0; - ObjectCountMapIt it = m_objectsDestroyed[playerIdx].find(o->getTemplate()); - if (it != m_objectsDestroyed[playerIdx].end()) - existingCount = it->second; - m_objectsDestroyed[playerIdx][o->getTemplate()] = existingCount + 1; - } -} - -void ScoreKeeper::addObjectLost( const Object *o ) -{ - if (TheGameLogic->isScoringEnabled() == FALSE) { - return; - } - - Bool addToCount = FALSE; - if(o->getTemplate()->isKindOfMulti(scoringBuildingMask, KINDOFMASK_NONE)) - { - if (!(o->testStatus(OBJECT_STATUS_UNDER_CONSTRUCTION))) { - ++m_totalBuildingsLost; - addToCount = TRUE; - } - } - else if (o->getTemplate()->isKindOfMulti(scoringBuildingDestroyMask, KINDOFMASK_NONE)) - { - if (!(o->testStatus(OBJECT_STATUS_UNDER_CONSTRUCTION))) { - ++m_totalBuildingsLost; - addToCount = TRUE; - } - } - else if(o->getTemplate()->isKindOf(KINDOF_INFANTRY) || o->getTemplate()->isKindOf(KINDOF_VEHICLE)) - { - if (o->getTemplate()->isKindOf(KINDOF_SCORE) || o->getTemplate()->isKindOf(KINDOF_SCORE_DESTROY)) - { - if (!(o->testStatus(OBJECT_STATUS_UNDER_CONSTRUCTION))) { - ++m_totalUnitsLost; - addToCount = TRUE; - } - } - } - - if(addToCount) - { - Int existingCount = 0; - ObjectCountMapIt it = m_objectsLost.find(o->getTemplate()); - if (it != m_objectsLost.end()) - existingCount = it->second; - m_objectsLost[o->getTemplate()] = existingCount + 1; - } -} - -Int ScoreKeeper::calculateScore() -{ - Int score = 0; - score += m_totalUnitsBuilt * 100; - score += m_totalMoneyEarned; - score += m_totalBuildingsBuilt * 100; - for (Int i = 0; i < MAX_PLAYER_COUNT; ++i) - { - if(i == m_myPlayerIdx) - continue; - score += m_totalUnitsDestroyed[i] * 100; - score += m_totalBuildingsDestroyed[i] * 100; - } - - m_currentScore = score; - return m_currentScore; - -} - -//----------------------------------------------------------------------------- -// PRIVATE FUNCTIONS ////////////////////////////////////////////////////////// -//----------------------------------------------------------------------------- - -Int ScoreKeeper::getTotalBuildingsDestroyed() -{ - int count = 0; - for (int i = 0; i< MAX_PLAYER_COUNT; ++i) - { - // Design change, display even if we killed our own -// if(i == m_myPlayerIdx) -// continue; - count += m_totalBuildingsDestroyed[i]; - //for (ObjectCountMapIt it = m_objectsDestroyed[i].begin(); it != m_objectsDestroyed[i].end(); ++it) - // { - // - // count += it->second; - // } - - } - return count; -} -Int ScoreKeeper::getTotalUnitsDestroyed() -{ - int count = 0; - for (int i = 0; i< MAX_PLAYER_COUNT; ++i) - { - // Design change, display even if we killed our own -// if(i == m_myPlayerIdx) -// continue; - count += m_totalUnitsDestroyed[i]; -// for (ObjectCountMapIt it = m_objectsDestroyed[i].begin(); it != m_objectsDestroyed[i].end(); ++it) -// { -// } - } - return count; -} - -// ------------------------------------------------------------------------------------------------ -/** CRC */ -// ------------------------------------------------------------------------------------------------ -void ScoreKeeper::crc( Xfer *xfer ) -{ - -} - -// ------------------------------------------------------------------------------------------------ -/** Xfer of an object count map - * Version Info: - * 1: Initial version */ -// ------------------------------------------------------------------------------------------------ -void ScoreKeeper::xferObjectCountMap( Xfer *xfer, ObjectCountMap *map ) -{ - - // sanity - if( map == nullptr ) - { - - DEBUG_CRASH(( "xferObjectCountMap - Invalid map parameter" )); - throw SC_INVALID_DATA; - - } - - // version info - XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - // size of the map - UnsignedShort mapSize = map->size(); - xfer->xferUnsignedShort( &mapSize ); - - // map data - Int count; - const ThingTemplate *thingTemplate; - AsciiString thingTemplateName; - if( xfer->getXferMode() == XFER_SAVE ) - { - ObjectCountMapIt it; - - // save all entries - for( it = map->begin(); it != map->end(); ++it ) - { - - // thing template - thingTemplate = it->first; - thingTemplateName = thingTemplate->getName(); - xfer->xferAsciiString( &thingTemplateName ); - - // the count - count = it->second; - xfer->xferInt( &count ); - - } - - } - else - { - - // read all entries - for( UnsignedShort i = 0; i < mapSize; ++i ) - { - - // read thing template name - xfer->xferAsciiString( &thingTemplateName ); - thingTemplate = TheThingFactory->findTemplate( thingTemplateName ); - if( thingTemplate == nullptr ) - { - - DEBUG_CRASH(( "xferObjectCountMap - Unknown thing template '%s'", thingTemplateName.str() )); - throw SC_INVALID_DATA; - - } - - // read count - xfer->xferInt( &count ); - - // add to map - (*map)[ thingTemplate ] = count; - - } - - } - -} - -// ------------------------------------------------------------------------------------------------ -/** Xfer method - * Version Info: - * 1: Initial version */ -// ------------------------------------------------------------------------------------------------ -void ScoreKeeper::xfer( Xfer *xfer ) -{ - - // version - XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - // money earned - xfer->xferInt( &m_totalMoneyEarned ); - - // money spent - xfer->xferInt( &m_totalMoneySpent ); - - // units destroyed - xfer->xferUser( m_totalUnitsDestroyed, sizeof( Int ) * MAX_PLAYER_COUNT ); - - // units built - xfer->xferInt( &m_totalUnitsBuilt ); - - // units lost - xfer->xferInt( &m_totalUnitsLost ); - - // buildings destroyed - xfer->xferUser( m_totalBuildingsDestroyed, sizeof( Int ) * MAX_PLAYER_COUNT ); - - // buildings built - xfer->xferInt( &m_totalBuildingsBuilt ); - - // buildings lost - xfer->xferInt( &m_totalBuildingsLost ); - - // tech buildings captured - xfer->xferInt( &m_totalTechBuildingsCaptured ); - - // faction buildings captured - xfer->xferInt( &m_totalFactionBuildingsCaptured ); - - // current score - xfer->xferInt( &m_currentScore ); - - // player index - xfer->xferInt( &m_myPlayerIdx ); - - // objects built - xferObjectCountMap( xfer, &m_objectsBuilt ); - - // objects destroyed - UnsignedShort destroyedArraySize = MAX_PLAYER_COUNT; - xfer->xferUnsignedShort( &destroyedArraySize ); - if( destroyedArraySize != MAX_PLAYER_COUNT ) - { - - DEBUG_CRASH(( "ScoreKeeper::xfer - size of objects destroyed array has changed" )); - throw SC_INVALID_DATA; - - } - for( UnsignedShort i = 0; i < destroyedArraySize; ++i ) - { - - // xfer map data - xferObjectCountMap( xfer, &m_objectsDestroyed[ i ] ); - - } - - // objects lost - xferObjectCountMap( xfer, &m_objectsLost ); - - // objects captured - xferObjectCountMap( xfer, &m_objectsCaptured ); - -} - -// ------------------------------------------------------------------------------------------------ -/** Load post process */ -// ------------------------------------------------------------------------------------------------ -void ScoreKeeper::loadPostProcess() -{ - -} diff --git a/Generals/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp b/Generals/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp deleted file mode 100644 index 11160ede478..00000000000 --- a/Generals/Code/GameEngine/Source/Common/RTS/SpecialPower.cpp +++ /dev/null @@ -1,379 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: SpecialPower.cpp ///////////////////////////////////////////////////////////////////////// -// Author: Colin Day, April 2002 -// Desc: Special power templates and the system that holds them -// Edited: Kris Morness -- July 2002 (added BitFlag system) -/////////////////////////////////////////////////////////////////////////////////////////////////// - -// USER INCLUDES ////////////////////////////////////////////////////////////////////////////////// -#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine - -#include "Common/Player.h" -#include "Common/Science.h" -#include "Common/SpecialPower.h" -#include "GameLogic/Object.h" -#include "Common/BitFlagsIO.h" - - -// GLOBAL ///////////////////////////////////////////////////////////////////////////////////////// -SpecialPowerStore *TheSpecialPowerStore = nullptr; - -#define DEFAULT_DEFECTION_DETECTION_PROTECTION_TIME_LIMIT (LOGICFRAMES_PER_SECOND * 10) - -/////////////////////////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////////////////////////// - -// Externs //////////////////////////////////////////////////////////////////////////////////////// -template<> -const char* const SpecialPowerMaskType::s_bitNameList[] = -{ - "SPECIAL_INVALID", - - //Superweapons - "SPECIAL_DAISY_CUTTER", - "SPECIAL_PARADROP_AMERICA", - "SPECIAL_CARPET_BOMB", - "SPECIAL_CLUSTER_MINES", - "SPECIAL_EMP_PULSE", - "SPECIAL_NAPALM_STRIKE", - "SPECIAL_CASH_HACK", - "SPECIAL_NEUTRON_MISSILE", - "SPECIAL_SPY_SATELLITE", - "SPECIAL_DEFECTOR", - "SPECIAL_TERROR_CELL", - "SPECIAL_AMBUSH", - "SPECIAL_BLACK_MARKET_NUKE", - "SPECIAL_ANTHRAX_BOMB", - "SPECIAL_SCUD_STORM", -#ifdef ALLOW_DEMORALIZE - "SPECIAL_DEMORALIZE", -#else - "SPECIAL_DEMORALIZE_OBSOLETE", -#endif - "SPECIAL_CRATE_DROP", - "SPECIAL_A10_THUNDERBOLT_STRIKE", - "SPECIAL_DETONATE_DIRTY_NUKE", - "SPECIAL_ARTILLERY_BARRAGE", - - //Special abilities - "SPECIAL_MISSILE_DEFENDER_LASER_GUIDED_MISSILES", - "SPECIAL_REMOTE_CHARGES", - "SPECIAL_TIMED_CHARGES", - "SPECIAL_HELIX_NAPALM_BOMB", // Added in Zero Hour - "SPECIAL_HACKER_DISABLE_BUILDING", - "SPECIAL_TANKHUNTER_TNT_ATTACK", - "SPECIAL_BLACKLOTUS_CAPTURE_BUILDING", - "SPECIAL_BLACKLOTUS_DISABLE_VEHICLE_HACK", - "SPECIAL_BLACKLOTUS_STEAL_CASH_HACK", - "SPECIAL_INFANTRY_CAPTURE_BUILDING", - "SPECIAL_RADAR_VAN_SCAN", - "SPECIAL_SPY_DRONE", - "SPECIAL_DISGUISE_AS_VEHICLE", - "SPECIAL_BOOBY_TRAP", // Added in Zero Hour - "SPECIAL_REPAIR_VEHICLES", - "SPECIAL_PARTICLE_UPLINK_CANNON", - "SPECIAL_CASH_BOUNTY", - "SPECIAL_CHANGE_BATTLE_PLANS", - "SPECIAL_CIA_INTELLIGENCE", - "SPECIAL_CLEANUP_AREA", - "SPECIAL_LAUNCH_BAIKONUR_ROCKET", - // TheSuperHackers @info Added in Zero Hour: - "SPECIAL_SPECTRE_GUNSHIP", - "SPECIAL_GPS_SCRAMBLER", - "SPECIAL_FRENZY", - "SPECIAL_SNEAK_ATTACK", - - "SPECIAL_CHINA_CARPET_BOMB", - "EARLY_SPECIAL_CHINA_CARPET_BOMB", - "SPECIAL_LEAFLET_DROP", - "EARLY_SPECIAL_LEAFLET_DROP", - "EARLY_SPECIAL_FRENZY", - "SPECIAL_COMMUNICATIONS_DOWNLOAD", - "EARLY_SPECIAL_REPAIR_VEHICLES", - "SPECIAL_TANK_PARADROP", - "SUPW_SPECIAL_PARTICLE_UPLINK_CANNON", - "AIRF_SPECIAL_DAISY_CUTTER", - "NUKE_SPECIAL_CLUSTER_MINES", - "NUKE_SPECIAL_NEUTRON_MISSILE", - "AIRF_SPECIAL_A10_THUNDERBOLT_STRIKE", - "AIRF_SPECIAL_SPECTRE_GUNSHIP", - "INFA_SPECIAL_PARADROP_AMERICA", - "SLTH_SPECIAL_GPS_SCRAMBLER", - "AIRF_SPECIAL_CARPET_BOMB", - "SUPR_SPECIAL_CRUISE_MISSILE", - "LAZR_SPECIAL_PARTICLE_UPLINK_CANNON", - "SUPW_SPECIAL_NEUTRON_MISSILE", - - "SPECIAL_BATTLESHIP_BOMBARDMENT", - - nullptr -}; -static_assert(ARRAY_SIZE(SpecialPowerMaskType::s_bitNameList) == SpecialPowerMaskType::NumBits + 1, "Incorrect array size"); - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -void SpecialPowerStore::parseSpecialPowerDefinition( INI *ini ) -{ - // read the name - AsciiString name = ini->getNextToken(); - - SpecialPowerTemplate* specialPower = TheSpecialPowerStore->findSpecialPowerTemplatePrivate( name ); - - if ( ini->getLoadType() == INI_LOAD_CREATE_OVERRIDES ) - { - if (specialPower) - { - SpecialPowerTemplate* child = (SpecialPowerTemplate*)specialPower->friend_getFinalOverride(); - specialPower = newInstance(SpecialPowerTemplate); - *specialPower = *child; - child->setNextOverride(specialPower); - specialPower->markAsOverride(); - //TheSpecialPowerStore->m_specialPowerTemplates.push_back(specialPower); // nope, do NOT do this - } - else - { - specialPower = newInstance(SpecialPowerTemplate); - const SpecialPowerTemplate *defaultTemplate = TheSpecialPowerStore->findSpecialPowerTemplate( "DefaultSpecialPower" ); - if( defaultTemplate ) - *specialPower = *defaultTemplate; - specialPower->friend_setNameAndID(name, ++TheSpecialPowerStore->m_nextSpecialPowerID); - specialPower->markAsOverride(); - TheSpecialPowerStore->m_specialPowerTemplates.push_back(specialPower); - } - } - else - { - if (specialPower) - { - throw INI_INVALID_DATA; - } - else - { - specialPower = newInstance(SpecialPowerTemplate); - const SpecialPowerTemplate *defaultTemplate = TheSpecialPowerStore->findSpecialPowerTemplate( "DefaultSpecialPower" ); - if( defaultTemplate ) - *specialPower = *defaultTemplate; - specialPower->friend_setNameAndID(name, ++TheSpecialPowerStore->m_nextSpecialPowerID); - TheSpecialPowerStore->m_specialPowerTemplates.push_back(specialPower); - } - } - - // parse the ini definition - if (specialPower) - ini->initFromINI( specialPower, specialPower->getFieldParse() ); -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -/* static */ const FieldParse SpecialPowerTemplate::m_specialPowerFieldParse[] = -{ - - { "ReloadTime", INI::parseDurationUnsignedInt, nullptr, offsetof( SpecialPowerTemplate, m_reloadTime ) }, - { "RequiredScience", INI::parseScience, nullptr, offsetof( SpecialPowerTemplate, m_requiredScience ) }, - { "InitiateSound", INI::parseAudioEventRTS, nullptr, offsetof( SpecialPowerTemplate, m_initiateSound ) }, - { "InitiateAtLocationSound", INI::parseAudioEventRTS, nullptr, offsetof( SpecialPowerTemplate, m_initiateAtLocationSound ) }, - { "PublicTimer", INI::parseBool, nullptr, offsetof( SpecialPowerTemplate, m_publicTimer ) }, - { "Enum", INI::parseIndexList, SpecialPowerMaskType::getBitNames(), offsetof( SpecialPowerTemplate, m_type ) }, - { "DetectionTime", INI::parseDurationUnsignedInt, nullptr, offsetof( SpecialPowerTemplate, m_detectionTime ) }, - { "SharedSyncedTimer", INI::parseBool, nullptr, offsetof( SpecialPowerTemplate, m_sharedNSync ) }, - { "ViewObjectDuration", INI::parseDurationUnsignedInt, nullptr, offsetof( SpecialPowerTemplate, m_viewObjectDuration ) }, - { "ViewObjectRange", INI::parseReal, nullptr, offsetof( SpecialPowerTemplate, m_viewObjectRange ) }, - { "RadiusCursorRadius", INI::parseReal, nullptr, offsetof( SpecialPowerTemplate, m_radiusCursorRadius ) }, - { "ShortcutPower", INI::parseBool, nullptr, offsetof( SpecialPowerTemplate, m_shortcutPower ) }, - { "AcademyClassify", INI::parseIndexList, TheAcademyClassificationTypeNames, offsetof( SpecialPowerTemplate, m_academyClassificationType ) }, - { nullptr, nullptr, nullptr, 0 } - -}; - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -SpecialPowerTemplate::SpecialPowerTemplate() -{ - m_id = 0; - m_type = SPECIAL_INVALID; - m_reloadTime = 0; - m_requiredScience = SCIENCE_INVALID; - m_publicTimer = FALSE; - m_detectionTime = DEFAULT_DEFECTION_DETECTION_PROTECTION_TIME_LIMIT; - m_sharedNSync = FALSE; - m_viewObjectDuration = 0; - m_viewObjectRange = 0; - m_radiusCursorRadius = 0; - m_shortcutPower = FALSE; - -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -SpecialPowerTemplate::~SpecialPowerTemplate() -{ - -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////////////////////////// - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -SpecialPowerStore::SpecialPowerStore() -{ - - m_nextSpecialPowerID = 0; - -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -SpecialPowerStore::~SpecialPowerStore() -{ - - // delete all templates - for( size_t i = 0; i < m_specialPowerTemplates.size(); ++i ) - deleteInstance(m_specialPowerTemplates[ i ]); - - // erase the list - m_specialPowerTemplates.clear(); - - // set our count to zero - m_nextSpecialPowerID = 0; - -} - -//------------------------------------------------------------------------------------------------- -//------------------------------------------------------------------------------------------------- -SpecialPowerTemplate* SpecialPowerStore::findSpecialPowerTemplatePrivate( AsciiString name ) -{ - - // search the template list for matching name - for( size_t i = 0; i < m_specialPowerTemplates.size(); ++i ) - if( m_specialPowerTemplates[ i ]->getName() == name ) - return m_specialPowerTemplates[ i ]; - - return nullptr; // not found - -} - -//------------------------------------------------------------------------------------------------- -/** Find a special power template given unique ID */ -//------------------------------------------------------------------------------------------------- -const SpecialPowerTemplate *SpecialPowerStore::findSpecialPowerTemplateByID( UnsignedInt id ) -{ - - // search the template list for matching name - for( size_t i = 0; i < m_specialPowerTemplates.size(); ++i ) - if( m_specialPowerTemplates[ i ]->getID() == id ) - return m_specialPowerTemplates[ i ]; - - return nullptr; // not found - -} - -//------------------------------------------------------------------------------------------------- -/** Find a special power template given index (WB) */ -//------------------------------------------------------------------------------------------------- -const SpecialPowerTemplate *SpecialPowerStore::getSpecialPowerTemplateByIndex( UnsignedInt index ) -{ - - if (index >= 0 && index < m_specialPowerTemplates.size()) - return m_specialPowerTemplates[ index ]; - - return nullptr; // not found - -} - -//------------------------------------------------------------------------------------------------- -/** Return the size of the store (WB) */ -//------------------------------------------------------------------------------------------------- -Int SpecialPowerStore::getNumSpecialPowers() -{ - - return m_specialPowerTemplates.size(); - -} - -//------------------------------------------------------------------------------------------------- -/** does the object (and therefore the player) meet all the requirements to use this power */ -//------------------------------------------------------------------------------------------------- -Bool SpecialPowerStore::canUseSpecialPower( Object *obj, const SpecialPowerTemplate *specialPowerTemplate ) -{ - - // sanity - if( obj == nullptr || specialPowerTemplate == nullptr ) - return FALSE; - - // as a first sanity check, the object must have a module capable of executing the power - if( obj->getSpecialPowerModule( specialPowerTemplate ) == nullptr ) - return FALSE; - - // - // in order to execute the special powers we have attached special power modules to the objects - // that can use them. However, just because an object has a module that is capable of - // doing the power, does not mean the object and the player can actually execute the - // power because some powers require a specialized science that the player must select and - // they cannot have all of them. - // - - // check for required science - ScienceType requiredScience = specialPowerTemplate->getRequiredScience(); - if( requiredScience != SCIENCE_INVALID ) - { - Player *player = obj->getControllingPlayer(); - - if( player->hasScience( requiredScience ) == FALSE ) - return FALSE; - - } - - - // I THINK THIS IS WHERE WE BAIL OUT IF A DIFFERENT CONYARD IS ALREADY CHARGING THIS SPECIAL RIGHT NOW //LORENZEN - - - // all is well - return TRUE; - -} - -//------------------------------------------------------------------------------------------------- -/** Reset */ -//------------------------------------------------------------------------------------------------- -void SpecialPowerStore::reset() -{ - for (SpecialPowerTemplatePtrVector::iterator it = m_specialPowerTemplates.begin(); it != m_specialPowerTemplates.end(); /*++it*/) - { - SpecialPowerTemplate* si = *it; - Overridable* temp = si->deleteOverrides(); - if (temp == nullptr) - { - it = m_specialPowerTemplates.erase(it); - } - else - { - ++it; - } - } -} diff --git a/Generals/Code/GameEngine/Source/Common/RTS/Team.cpp b/Generals/Code/GameEngine/Source/Common/RTS/Team.cpp deleted file mode 100644 index 4c58ee8d5ab..00000000000 --- a/Generals/Code/GameEngine/Source/Common/RTS/Team.cpp +++ /dev/null @@ -1,2760 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: Team.cpp ///////////////////////////////////////////////////////////////////////////////// -// Team interface implementation -// Author: Michael S. Booth, March 2001 -/////////////////////////////////////////////////////////////////////////////////////////////////// - -// INCLUDES /////////////////////////////////////////////////////////////////////////////////////// -#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine -#include "Common/GameState.h" -#include "Common/Team.h" -#include "Common/ThingFactory.h" -#include "Common/PerfTimer.h" -#include "Common/Player.h" -#include "Common/PlayerList.h" -#include "Common/PlayerTemplate.h" -#include "Common/ThingTemplate.h" -#include "Common/WellKnownKeys.h" -#include "Common/Xfer.h" -#include "GameClient/Drawable.h" - -#include "GameLogic/SidesList.h" -#include "GameLogic/Object.h" -#include "GameLogic/Module/BodyModule.h" -#include "GameLogic/Module/ContainModule.h" -#include "GameLogic/PolygonTrigger.h" -#include "GameLogic/Module/AIUpdate.h" -#include "GameLogic/PartitionManager.h" -#include "GameLogic/ScriptActions.h" -#include "GameLogic/ScriptEngine.h" - - -///@todo - do delayed script evaluations for team scripts. jba. - -// GLOBALS //////////////////////////////////////////////////////////////////// -TeamFactory *TheTeamFactory = nullptr; - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -TeamRelationMap::TeamRelationMap() -{ - -} - -// ------------------------------------------------------------------------------------------------ -// ------------------------------------------------------------------------------------------------ -TeamRelationMap::~TeamRelationMap() -{ - - // maek sure the data is clear - m_map.clear(); - -} - -// ------------------------------------------------------------------------------------------------ -/** CRC */ -// ------------------------------------------------------------------------------------------------ -void TeamRelationMap::crc( Xfer *xfer ) -{ - -} - -// ------------------------------------------------------------------------------------------------ -/** Xfer method - * Version Info; - * 1: Initial version */ -// ------------------------------------------------------------------------------------------------ -void TeamRelationMap::xfer( Xfer *xfer ) -{ - - // version - XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - // team relation count - TeamRelationMapType::iterator teamRelationIt; - UnsignedShort teamRelationCount = m_map.size(); - xfer->xferUnsignedShort( &teamRelationCount ); - - // team relations - TeamID teamID; - Relationship r; - if( xfer->getXferMode() == XFER_SAVE ) - { - - // go through all team relations - for( teamRelationIt = m_map.begin(); teamRelationIt != m_map.end(); ++teamRelationIt ) - { - - // write team ID - teamID = (*teamRelationIt).first; - xfer->xferUser( &teamID, sizeof( TeamID ) ); - - // write relationship - r = (*teamRelationIt).second; - xfer->xferUser( &r, sizeof( Relationship ) ); - - } - - } - else - { - - for( UnsignedShort i = 0; i < teamRelationCount; ++i ) - { - - // read team ID - xfer->xferUser( &teamID, sizeof( TeamID ) ); - - // read relationship - xfer->xferUser( &r, sizeof( Relationship ) ); - - // assign relationship - m_map[teamID] = r; - - } - - } - -} - -// ------------------------------------------------------------------------------------------------ -/** Load post process */ -// ------------------------------------------------------------------------------------------------ -void TeamRelationMap::loadPostProcess() -{ - -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////////////////////////// - -// ------------------------------------------------------------------------ -// ------------------------------------------------------------------------ -// ------------------------------------------------------------------------ -// STATIC FUNCTIONS /////////////////////////////////////////////////////////// -static Bool locoSetMatches(LocomotorSurfaceTypeMask lstm, UnsignedInt surfaceBitFlags) -{ - surfaceBitFlags = (surfaceBitFlags & 0x01) | ((surfaceBitFlags & 0x02) << 2); - return (surfaceBitFlags & lstm) != 0; -} - -// ------------------------------------------------------------------------ - -// ------------------------------------------------------------------------ -TeamFactory::TeamFactory() -{ - - m_uniqueTeamPrototypeID = TEAM_PROTOTYPE_ID_INVALID; - m_uniqueTeamID = TEAM_ID_INVALID; - -} - -// ------------------------------------------------------------------------ -TeamFactory::~TeamFactory() -{ - clear(); -} - -// ------------------------------------------------------------------------ -void TeamFactory::init() -{ - clear(); -} - -// ------------------------------------------------------------------------ -void TeamFactory::reset() -{ - m_uniqueTeamPrototypeID = TEAM_PROTOTYPE_ID_INVALID; - m_uniqueTeamID = TEAM_ID_INVALID; - clear(); -} - -// ------------------------------------------------------------------------ -void TeamFactory::update() -{ -} - -// ------------------------------------------------------------------------ -void TeamFactory::clear() -{ - // must remove it from the map before deleting the TeamProto, since - // the TeamProto will try to remove itself from the list when it goes away - TeamPrototypeMap tmp = m_prototypes; - m_prototypes.clear(); - for (TeamPrototypeMap::iterator it = tmp.begin(); it != tmp.end(); ++it) - { - deleteInstance(it->second); - } -} - -// ------------------------------------------------------------------------ -void TeamFactory::initFromSides(SidesList *sides) -{ - clear(); - - // create the teams we need. - for(Int i = 0; i < sides->getNumTeams(); i++) - { - Dict *d = sides->getTeamInfo(i)->getDict(); - - AsciiString tname = d->getAsciiString(TheKey_teamName); - AsciiString oname = d->getAsciiString(TheKey_teamOwner); - Bool singleton = d->getBool(TheKey_teamIsSingleton); - initTeam(tname, oname, singleton, d); - } - -} - -// ------------------------------------------------------------------------ -void TeamFactory::initTeam(const AsciiString& name, const AsciiString& owner, Bool isSingleton, Dict *d) -{ - DEBUG_ASSERTCRASH(findTeamPrototype(name)==nullptr,("team already exists")); - Player *pOwner = ThePlayerList->findPlayerWithNameKey(NAMEKEY(owner)); - DEBUG_ASSERTCRASH(pOwner, ("no owner found for team %s (%s)",name.str(),owner.str())); - if (!pOwner) - pOwner = ThePlayerList->getNeutralPlayer(); - /*TeamPrototype *tp =*/ newInstance(TeamPrototype)(this, name, pOwner, isSingleton, d, ++m_uniqueTeamPrototypeID); - if (isSingleton) { - // Create the singleton team. - createInactiveTeam(name); - } -} - -//============================================================================= -void TeamFactory::addTeamPrototypeToList(TeamPrototype* team) -{ - NameKeyType nk = NAMEKEY(team->getName()); - TeamPrototypeMap::iterator it = m_prototypes.find(nk); - if (it != m_prototypes.end()) - { - DEBUG_ASSERTCRASH((*it).second==team, ("TeamFactory::addTeamPrototypeToList: Team %s already exists... skipping.", team->getName().str())); - return; // already present - } - - m_prototypes[nk] = team; -} - -//============================================================================= -void TeamFactory::removeTeamPrototypeFromList(TeamPrototype* team) -{ - NameKeyType nk = NAMEKEY(team->getName()); - TeamPrototypeMap::iterator it = m_prototypes.find(nk); - if (it != m_prototypes.end()) - m_prototypes.erase(it); -} - -// ------------------------------------------------------------------------ -TeamPrototype *TeamFactory::findTeamPrototype(const AsciiString& name) -{ - NameKeyType nk = NAMEKEY(name); - TeamPrototypeMap::iterator it = m_prototypes.find(nk); - if (it != m_prototypes.end()) - return it->second; - - return nullptr; -} - -// ------------------------------------------------------------------------ -TeamPrototype *TeamFactory::findTeamPrototypeByID( TeamPrototypeID id ) -{ - TeamPrototypeMap::iterator it; - TeamPrototype *prototype = nullptr; - - for( it = m_prototypes.begin(); it != m_prototypes.end(); ++it ) - { - - prototype = it->second; - if( prototype->getID() == id ) - return prototype; - - } - - // not found - return nullptr; - -} - -// ------------------------------------------------------------------------ -Team *TeamFactory::findTeamByID( TeamID teamID ) -{ - - // simple case - if( teamID == TEAM_ID_INVALID ) - return nullptr; - - // search all prototypes for the matching team ID - TeamPrototype *tp; - TeamPrototypeMap::iterator it; - Team *team; - for( it = m_prototypes.begin(); it != m_prototypes.end(); ++it ) - { - tp = (*it).second; - team = tp->findTeamByID( teamID ); - if( team ) - return team; - } - - return nullptr; - -} - -// ------------------------------------------------------------------------ -/** Creates an inactive team, suitable for adding members to as they are built. -Call team->setActive() when all members are added. */ -Team *TeamFactory::createInactiveTeam(const AsciiString& name) -{ - TeamPrototype *tp = findTeamPrototype(name); - if (!tp) { - DEBUG_CRASH(( "Team prototype '%s' does not exist", name.str() )); - return nullptr; - } - - Team *t = nullptr; - if (tp->getIsSingleton()) - { - t = tp->getFirstItemIn_TeamInstanceList(); - if (t) { - if (tp->getTemplateInfo()->m_executeActions) { - const Script *script = TheScriptEngine->findScriptByName(tp->getTemplateInfo()->m_productionCondition); - if (script) { - TheScriptEngine->friend_executeAction(script->getAction()); - } - } - return t; - } - } - - t = newInstance(Team)(tp, ++m_uniqueTeamID ); - if (tp->getTemplateInfo()->m_executeActions) { - const Script *script = TheScriptEngine->findScriptByName(tp->getTemplateInfo()->m_productionCondition); - if (script) { - TheScriptEngine->friend_executeAction(script->getAction()); - } - } - - return t; -} - -// ------------------------------------------------------------------------ -Team *TeamFactory::createTeam(const AsciiString& name) -{ - Team *t = createInactiveTeam(name); - - if (t) - t->setActive(); - - return t; -} - -// ------------------------------------------------------------------------ -Team *TeamFactory::createTeamOnPrototype( TeamPrototype *prototype ) -{ - if( prototype == nullptr ) - throw ERROR_BAD_ARG; - - Team *t = nullptr; - if( prototype->getIsSingleton() ) - { - t = prototype->getFirstItemIn_TeamInstanceList(); - if( t ) - return t; - } - t = newInstance(Team)( prototype, ++m_uniqueTeamID ); - t->setActive(); - return t; -} -// ------------------------------------------------------------------------ -Team* TeamFactory::findTeam(const AsciiString& name) -{ - TeamPrototype *tp = findTeamPrototype(name); - if (tp) - { - Team *t = tp->getFirstItemIn_TeamInstanceList(); - if (t == nullptr && !tp->getIsSingleton()) - { - t = createInactiveTeam(name); - } - return t; - } - return nullptr; -} - -// ------------------------------------------------------------------------ -void TeamFactory::teamAboutToBeDeleted(Team* team) -{ - for (TeamPrototypeMap::iterator it = m_prototypes.begin(); it != m_prototypes.end(); ++it) - { - it->second->teamAboutToBeDeleted(team); - } - if (ThePlayerList) - ThePlayerList->teamAboutToBeDeleted(team); -} - -// ------------------------------------------------------------------------ -/** CRC */ -// ------------------------------------------------------------------------ -void TeamFactory::crc( Xfer *xfer ) -{ - -} - -// ------------------------------------------------------------------------ -/** Xfer method - * Version Info: - * 1: Initial version */ -// ------------------------------------------------------------------------ -void TeamFactory::xfer( Xfer *xfer ) -{ - - // version - XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - // unique team ID counter - xfer->xferUser( &m_uniqueTeamID, sizeof( TeamID ) ); - - // how many team prototypes of data do we have to write - UnsignedShort prototypeCount = m_prototypes.size(); - xfer->xferUnsignedShort( &prototypeCount ); - - // - // prototypes cannot change in number during run time so the count should be the - // same as that already loaded into us from a map load - // - if( prototypeCount != m_prototypes.size() ) - { - - DEBUG_CRASH(( "TeamFactory::xfer - Prototype count mismatch '%d should be '%d'", - prototypeCount, m_prototypes.size() )); - throw SC_INVALID_DATA; - - } - - // xfer each of the prototype information - TeamPrototypeMap::iterator it; - TeamPrototypeID teamPrototypeID; - TeamPrototype *teamPrototype; - AsciiString prototypeName; - if( xfer->getXferMode() == XFER_SAVE ) - { - - // iterate each prototype and xfer if it needs to be in the save file - for( it = m_prototypes.begin(); it != m_prototypes.end(); ++it ) - { - - // get prototype - teamPrototype = it->second; - - // xfer prototype id - teamPrototypeID = teamPrototype->getID(); - xfer->xferUser( &teamPrototypeID, sizeof( TeamPrototypeID ) ); - - // xfer prototype data - xfer->xferSnapshot( teamPrototype ); - - } - - } - else - { - - // read all the team prototype info - for( UnsignedShort i = 0; i < prototypeCount; ++i ) - { - - // read prototype ID - xfer->xferUser( &teamPrototypeID, sizeof( TeamPrototypeID ) ); - - // find the prototype - teamPrototype = findTeamPrototypeByID( teamPrototypeID ); - - // sanity - if( teamPrototype == nullptr ) - { - - DEBUG_CRASH(( "TeamFactory::xfer - Unable to find team prototype by id" )); - throw SC_INVALID_DATA; - - } - - // xfer prototype data - xfer->xferSnapshot( teamPrototype ); - - } - - } - -/* -// SAVE_LOAD_DEBUG -if( xfer->getXferMode() == XFER_SAVE ) -{ - -FILE *fp = fopen( "TeamCheckSave.txt", "w+t" ); -if( fp == nullptr ) - return; - -Object *obj; -TeamPrototypeMap::iterator prototypeIt; -TeamPrototype *prototype; -Team *team; -for( prototypeIt = m_prototypes.begin(); prototypeIt != m_prototypes.end(); ++prototypeIt ) -{ - prototype = prototypeIt->second; -fprintf( fp, "Prototype '%s' for player index '%d'\n", prototype->getName().str(), prototype->getControllingPlayer()->getPlayerIndex() ); - for( DLINK_ITERATOR teamIt = prototype->iterate_TeamInstanceList(); !teamIt.done(); teamIt.advance() ) - { - team = teamIt.cur(); -fprintf( fp, " Team Instance '%s', id is '%d'\n", team->getName().str(), team->getID() ); - for( DLINK_ITERATOR objIt = team->iterate_TeamMemberList(); !objIt.done(); objIt.advance() ) - { - obj = objIt.cur(); -fprintf( fp, " Member '%s', id '%d'\n", obj->getTemplate()->getName().str(), obj->getID() ); - } - } - -} -fclose( fp ); - -} -*/ - -} - -// ------------------------------------------------------------------------ -/** Load post process */ -// ------------------------------------------------------------------------ -void TeamFactory::loadPostProcess() -{ - - // set the next unique team and prototype ID to just over the highest one in use - m_uniqueTeamID = 0; - m_uniqueTeamPrototypeID = 0; - TeamPrototypeMap::iterator prototypeIt; - TeamPrototype *prototype; - Team *team; - for( prototypeIt = m_prototypes.begin(); prototypeIt != m_prototypes.end(); ++prototypeIt ) - { - - // get prototype - prototype = prototypeIt->second; - - // do protype ID check - if( prototype->getID() >= m_uniqueTeamPrototypeID ) - m_uniqueTeamPrototypeID = prototype->getID() + 1; - - // iterate team instances on each prototype and do the team ID check - for( DLINK_ITERATOR iter = prototype->iterate_TeamInstanceList(); !iter.done(); iter.advance() ) - { - - team = iter.cur(); - if( team->getID() >= m_uniqueTeamID ) - m_uniqueTeamID = team->getID() + 1; - - } - - } - -/* -// SAVE_LOAD_DEBUG -FILE *fp = fopen( "TeamCheckLoad.txt", "w+t" ); -if( fp == nullptr ) - return; - -Object *obj; -for( prototypeIt = m_prototypes.begin(); prototypeIt != m_prototypes.end(); ++prototypeIt ) -{ - prototype = prototypeIt->second; -fprintf( fp, "Prototype '%s' for player index '%d'\n", prototype->getName().str(), prototype->getControllingPlayer()->getPlayerIndex() ); - for( DLINK_ITERATOR teamIt = prototype->iterate_TeamInstanceList(); !teamIt.done(); teamIt.advance() ) - { - team = teamIt.cur(); -fprintf( fp, " Team Instance '%s', id is '%d'\n", team->getName().str(), team->getID() ); - team->reverse_TeamMemberList(); - for( DLINK_ITERATOR objIt = team->iterate_TeamMemberList(); !objIt.done(); objIt.advance() ) - { - obj = objIt.cur(); -fprintf( fp, " Member '%s', id '%d'\n", obj->getTemplate()->getName().str(), obj->getID() ); - } - } - -} -fclose( fp ); -*/ - -} - -// ------------------------------------------------------------------------ -// ------------------------------------------------------------------------ -// ------------------------------------------------------------------------ -TeamTemplateInfo::TeamTemplateInfo(Dict *d) : - m_numUnitsInfo(0) -{ - Bool exists; - Int min, max; - AsciiString templateName; - min = d->getInt(TheKey_teamUnitMinCount1, &exists); - max = d->getInt(TheKey_teamUnitMaxCount1, &exists); - templateName = d->getAsciiString(TheKey_teamUnitType1, &exists); - if (max>0 && exists) { - m_unitsInfo[m_numUnitsInfo].minUnits = min; - m_unitsInfo[m_numUnitsInfo].maxUnits = max; - m_unitsInfo[m_numUnitsInfo].unitThingName = templateName; - m_numUnitsInfo++; - } - - min = d->getInt(TheKey_teamUnitMinCount2, &exists); - max = d->getInt(TheKey_teamUnitMaxCount2, &exists); - templateName = d->getAsciiString(TheKey_teamUnitType2, &exists); - if (max>0 && exists) { - m_unitsInfo[m_numUnitsInfo].minUnits = min; - m_unitsInfo[m_numUnitsInfo].maxUnits = max; - m_unitsInfo[m_numUnitsInfo].unitThingName = templateName; - m_numUnitsInfo++; - } - - min = d->getInt(TheKey_teamUnitMinCount3, &exists); - max = d->getInt(TheKey_teamUnitMaxCount3, &exists); - templateName = d->getAsciiString(TheKey_teamUnitType3, &exists); - if (max>0 && exists) { - m_unitsInfo[m_numUnitsInfo].minUnits = min; - m_unitsInfo[m_numUnitsInfo].maxUnits = max; - m_unitsInfo[m_numUnitsInfo].unitThingName = templateName; - m_numUnitsInfo++; - } - - min = d->getInt(TheKey_teamUnitMinCount4, &exists); - max = d->getInt(TheKey_teamUnitMaxCount4, &exists); - templateName = d->getAsciiString(TheKey_teamUnitType4, &exists); - if (max>0 && exists) { - m_unitsInfo[m_numUnitsInfo].minUnits = min; - m_unitsInfo[m_numUnitsInfo].maxUnits = max; - m_unitsInfo[m_numUnitsInfo].unitThingName = templateName; - m_numUnitsInfo++; - } - - min = d->getInt(TheKey_teamUnitMinCount5, &exists); - max = d->getInt(TheKey_teamUnitMaxCount5, &exists); - templateName = d->getAsciiString(TheKey_teamUnitType5, &exists); - if (max>0 && exists) { - m_unitsInfo[m_numUnitsInfo].minUnits = min; - m_unitsInfo[m_numUnitsInfo].maxUnits = max; - m_unitsInfo[m_numUnitsInfo].unitThingName = templateName; - m_numUnitsInfo++; - } - - min = d->getInt(TheKey_teamUnitMinCount6, &exists); - max = d->getInt(TheKey_teamUnitMaxCount6, &exists); - templateName = d->getAsciiString(TheKey_teamUnitType6, &exists); - if (max>0 && exists) { - m_unitsInfo[m_numUnitsInfo].minUnits = min; - m_unitsInfo[m_numUnitsInfo].maxUnits = max; - m_unitsInfo[m_numUnitsInfo].unitThingName = templateName; - m_numUnitsInfo++; - } - - min = d->getInt(TheKey_teamUnitMinCount7, &exists); - max = d->getInt(TheKey_teamUnitMaxCount7, &exists); - templateName = d->getAsciiString(TheKey_teamUnitType7, &exists); - if (max>0 && exists) { - m_unitsInfo[m_numUnitsInfo].minUnits = min; - m_unitsInfo[m_numUnitsInfo].maxUnits = max; - m_unitsInfo[m_numUnitsInfo].unitThingName = templateName; - m_numUnitsInfo++; - } - - AsciiString waypoint = d->getAsciiString(TheKey_teamHome, &exists); - m_homeLocation.x = m_homeLocation.y = 0; - m_homeLocation.z = 0; - m_hasHomeLocation = false; - if (exists) { - for (Waypoint *way = TheTerrainLogic->getFirstWaypoint(); way; way = way->getNext()) { - if (way->getName() == waypoint) { - m_homeLocation = *way->getLocation(); - m_hasHomeLocation = true; - } - } - } - - m_scriptOnCreate = d->getAsciiString(TheKey_teamOnCreateScript, &exists); - m_isAIRecruitable = d->getBool(TheKey_teamIsAIRecruitable, &exists); - if (!exists) { - m_isAIRecruitable = false; - } - m_isBaseDefense = d->getBool(TheKey_teamIsBaseDefense, &exists); - m_isPerimeterDefense = d->getBool(TheKey_teamIsPerimeterDefense, &exists); - m_automaticallyReinforce = d->getBool(TheKey_teamAutoReinforce, &exists); - - Int interact = d->getInt(TheKey_teamAggressiveness, &exists); - m_initialTeamAttitude = ATTITUDE_NORMAL; - if (exists) { - m_initialTeamAttitude = (AttitudeType) interact; - } - - m_transportsReturn = d->getBool(TheKey_teamTransportsReturn, &exists); - m_avoidThreats = d->getBool(TheKey_teamAvoidThreats, &exists); - - m_attackCommonTarget = d->getBool(TheKey_teamAttackCommonTarget, &exists); - - m_maxInstances = d->getInt(TheKey_teamMaxInstances, &exists); - - m_scriptOnIdle = d->getAsciiString(TheKey_teamOnIdleScript, &exists); - m_initialIdleFrames = d->getInt(TheKey_teamInitialIdleFrames, &exists); - m_scriptOnEnemySighted = d->getAsciiString(TheKey_teamEnemySightedScript, &exists); - m_scriptOnAllClear = d->getAsciiString(TheKey_teamAllClearScript, &exists); - m_scriptOnDestroyed = d->getAsciiString(TheKey_teamOnDestroyedScript, &exists); - m_destroyedThreshold = d->getReal(TheKey_teamDestroyedThreshold, &exists); - m_scriptOnUnitDestroyed = d->getAsciiString(TheKey_teamOnUnitDestroyedScript, &exists); - - m_productionPriority = d->getInt(TheKey_teamProductionPriority, &exists); - m_productionPrioritySuccessIncrease = d->getInt(TheKey_teamProductionPrioritySuccessIncrease, &exists); - m_productionPriorityFailureDecrease = d->getInt(TheKey_teamProductionPriorityFailureDecrease, &exists); - - // Production scripts stuff - m_productionCondition = d->getAsciiString(TheKey_teamProductionCondition, &exists); - m_executeActions = d->getBool(TheKey_teamExecutesActionsOnCreate, &exists); - - - // Which scripts to attempt during run? - for (int i = 0; i < MAX_GENERIC_SCRIPTS; ++i) { - AsciiString keyName; - keyName.format("%s%d", TheNameKeyGenerator->keyToName(TheKey_teamGenericScriptHook).str(), i); - m_teamGenericScripts[i] = d->getAsciiString(NAMEKEY(keyName), &exists); - if (!exists) { - m_teamGenericScripts[i].clear(); - } - } - - - // reinforcement team info. - m_transportUnitType = d->getAsciiString(TheKey_teamTransport, &exists); - m_transportsExit = d->getBool(TheKey_teamTransportsExit, &exists); - m_teamStartsFull = d->getBool(TheKey_teamStartsFull, &exists); - m_startReinforceWaypoint = d->getAsciiString(TheKey_teamReinforcementOrigin, &exists); - m_veterancy = (VeterancyLevel)d->getInt(TheKey_teamVeterancy, &exists); -} - -// ------------------------------------------------------------------------ -/** CRC */ -// ------------------------------------------------------------------------ -void TeamTemplateInfo::crc( Xfer *xfer ) -{ - -} - -// ------------------------------------------------------------------------ -/** Xfer method - * Version Info: - * 1: Initial version */ -// ------------------------------------------------------------------------ -void TeamTemplateInfo::xfer( Xfer *xfer ) -{ - - // version - XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - // xfer the production priority - xfer->xferInt( &m_productionPriority ); - -} - -// ------------------------------------------------------------------------ -/** Load post process */ -// ------------------------------------------------------------------------ -void TeamTemplateInfo::loadPostProcess() -{ - -} - -// ------------------------------------------------------------------------ -// ------------------------------------------------------------------------ -// ------------------------------------------------------------------------ -// ------------------------------------------------------------------------ - -// ------------------------------------------------------------------------ -TeamPrototype::TeamPrototype( TeamFactory *tf, - const AsciiString &name, - Player *ownerPlayer, - Bool isSingleton, - Dict *d, - TeamPrototypeID id ) : - m_id(id), - m_factory(tf), - m_name(name), - m_owningPlayer(ownerPlayer), - m_flags(isSingleton ? TeamPrototype::TEAM_SINGLETON : 0), - m_teamTemplate(d), - m_productionConditionAlwaysFalse(false), - m_productionConditionScript(nullptr) -{ - DEBUG_ASSERTCRASH(!(m_owningPlayer == nullptr), ("bad args to TeamPrototype ctor")); - if (m_factory) - m_factory->addTeamPrototypeToList(this); - - if (m_owningPlayer) - m_owningPlayer->addTeamToList(this); - - m_retrievedGenericScripts = false; - for (Int i = 0; i < MAX_GENERIC_SCRIPTS; ++i) { - m_genericScriptsToRun[i] = nullptr; - } -} - -// ------------------------------------------------------------------------ - - static void deleteTeamCallback(Team* o) - { - if (o) - { - TheTeamFactory->teamAboutToBeDeleted(o); - deleteInstance(o); - } - } - -TeamPrototype::~TeamPrototype() -{ - removeAll_TeamInstanceList(deleteTeamCallback); - - if (m_owningPlayer) - m_owningPlayer->removeTeamFromList(this); - - if (m_factory) - m_factory->removeTeamPrototypeFromList(this); - - deleteInstance(m_productionConditionScript); - m_productionConditionScript = nullptr; - - for (Int i = 0; i < MAX_GENERIC_SCRIPTS; ++i) - { - deleteInstance(m_genericScriptsToRun[i]); - m_genericScriptsToRun[i] = nullptr; - } -} - -// ------------------------------------------------------------------------ -Player *TeamPrototype::getControllingPlayer() const -{ - return m_owningPlayer; -} - -// ------------------------------------------------------------------------ -Team *TeamPrototype::findTeamByID( TeamID teamID ) -{ - for (DLINK_ITERATOR iter = iterate_TeamInstanceList(); !iter.done(); iter.advance()) - { - if( iter.cur()->getID() == teamID ) - return iter.cur(); - } - return nullptr; -} - -// ------------------------------------------------------------------------ -void TeamPrototype::setControllingPlayer(Player *newController) -{ - DEBUG_ASSERTCRASH(newController, ("Attempted to set null player as team-owner, illegal.")); - if (!newController) { - return; - } - - if (m_owningPlayer) - m_owningPlayer->removeTeamFromList(this); - - m_owningPlayer = newController; - - // impossible to get here with a nullptr pointer. - m_owningPlayer->addTeamToList(this); -} - -// ------------------------------------------------------------------------ -void TeamPrototype::countObjectsByThingTemplate(Int numTmplates, const ThingTemplate* const* things, Bool ignoreDead, Int *counts, Bool ignoreUnderConstruction) const -{ - for (DLINK_ITERATOR iter = iterate_TeamInstanceList(); !iter.done(); iter.advance()) - { - iter.cur()->countObjectsByThingTemplate(numTmplates, things, ignoreDead, counts, ignoreUnderConstruction); - } -} - -// ------------------------------------------------------------------------ -void TeamPrototype::teamAboutToBeDeleted(Team* team) -{ - for (DLINK_ITERATOR iter = iterate_TeamInstanceList(); !iter.done(); iter.advance()) - { -// iter.cur()->removeOverrideTeamRelationship(team); - iter.cur()->removeOverrideTeamRelationship(team ? team->getID() : TEAM_ID_INVALID ); - } -} - -// ------------------------------------------------------------------------ -Script *TeamPrototype::getGenericScript(Int scriptToRetrieve) -{ - if (!m_retrievedGenericScripts) { - m_retrievedGenericScripts = TRUE; // set this to true so we won't do the lookup again. - // Go get them from the script engine, and duplicate each one. - for (Int i = 0; i < MAX_GENERIC_SCRIPTS; ++i) { - const Script *tmpScript = nullptr; - Script *scriptToSave = nullptr; - if (!m_teamTemplate.m_teamGenericScripts[i].isEmpty()) { - tmpScript = TheScriptEngine->findScriptByName(m_teamTemplate.m_teamGenericScripts[i]); - if (tmpScript) { - scriptToSave = tmpScript->duplicate(); - } else { - DEBUG_CRASH(("We attempted to find a generic script, but couldn't. ('%s')", m_teamTemplate.m_teamGenericScripts[i].str())); - } - } - - // I now own this one. I'm responsible for cleaning it up on destruction. - m_genericScriptsToRun[i] = scriptToSave; - } - } - - return m_genericScriptsToRun[scriptToRetrieve]; -} - -// ------------------------------------------------------------------------ -// Make a team more likely to be selected by the ai for building due to success. -void TeamPrototype::increaseAIPriorityForSuccess() const -{ - m_teamTemplate.m_productionPriority += m_teamTemplate.m_productionPrioritySuccessIncrease; -} - -// ------------------------------------------------------------------------ -// Make a team more likely to be selected by the ai for building due to success. -void TeamPrototype::decreaseAIPriorityForFailure() const -{ - m_teamTemplate.m_productionPriority -= m_teamTemplate.m_productionPriorityFailureDecrease; -} - -// ------------------------------------------------------------------------ -Int TeamPrototype::countBuildings() -{ - int retVal = 0; - for (DLINK_ITERATOR iter = iterate_TeamInstanceList(); !iter.done(); iter.advance()) { - retVal += iter.cur()->countBuildings(); - } - return retVal; -} - -// ------------------------------------------------------------------------ -Int TeamPrototype::countObjects(KindOfMaskType setMask, KindOfMaskType clearMask) -{ - int retVal = 0; - for (DLINK_ITERATOR iter = iterate_TeamInstanceList(); !iter.done(); iter.advance()) { - retVal += iter.cur()->countObjects(setMask, clearMask); - } - return retVal; -} - -// ------------------------------------------------------------------------ -void TeamPrototype::healAllObjects() -{ - for (DLINK_ITERATOR iter = iterate_TeamInstanceList(); !iter.done(); iter.advance()) - { - iter.cur()->healAllObjects(); - } -} - -// ------------------------------------------------------------------------ -void TeamPrototype::iterateObjects( ObjectIterateFunc func, void *userData ) -{ - for (DLINK_ITERATOR iter = iterate_TeamInstanceList(); !iter.done(); iter.advance()) - { - iter.cur()->iterateObjects( func, userData ); - } -} - -// ------------------------------------------------------------------------ -/** - * Count the number of teams that have been instanced by this prototype - */ -Int TeamPrototype::countTeamInstances() -{ - Int count = 0; - for (DLINK_ITERATOR iter = iterate_TeamInstanceList(); !iter.done(); iter.advance()) - count++; - - return count; -} - - -// ------------------------------------------------------------------------ -Bool TeamPrototype::hasAnyBuildings() const -{ - for (DLINK_ITERATOR iter = iterate_TeamInstanceList(); !iter.done(); iter.advance()) - { - if (iter.cur()->hasAnyBuildings()) return true; - } - return false; -} - -// ------------------------------------------------------------------------ -Bool TeamPrototype::hasAnyBuildings(KindOfMaskType kindOf) const -{ - for (DLINK_ITERATOR iter = iterate_TeamInstanceList(); !iter.done(); iter.advance()) - { - if (iter.cur()->hasAnyBuildings(kindOf)) return true; - } - return false; -} - -// ------------------------------------------------------------------------ -Bool TeamPrototype::hasAnyUnits() const -{ - for (DLINK_ITERATOR iter = iterate_TeamInstanceList(); !iter.done(); iter.advance()) - { - if (iter.cur()->hasAnyUnits()) return true; - } - return false; -} - -// ------------------------------------------------------------------------ -Bool TeamPrototype::hasAnyObjects() const -{ - for (DLINK_ITERATOR iter = iterate_TeamInstanceList(); !iter.done(); iter.advance()) - { - if (iter.cur()->hasAnyObjects()) return true; - } - return false; -} - -// ------------------------------------------------------------------------ -void TeamPrototype::updateState() -{ - for (DLINK_ITERATOR iter = iterate_TeamInstanceList(); !iter.done(); iter.advance()) - { - iter.cur()->updateState(); - } - /* remove empty teams. */ - Bool done = false; - while (!done) { - done = true; - for (DLINK_ITERATOR iter = iterate_TeamInstanceList(); !iter.done(); iter.advance()) - { - if (iter.cur()->getFirstItemIn_TeamMemberList() == nullptr) - { - // Team has no members. - if (this->getIsSingleton()) - { - continue; // Don't delete singleton teams, even if they are empty. - } - - if (iter.cur()->getControllingPlayer() && iter.cur()->getControllingPlayer()->getDefaultTeam() == iter.cur()) - { - // This is the player's default team, so don't remove it. - continue; - } - - // don't delete inactive teams - they are under construction - if (iter.cur()->isActive() == false) - { - continue; - } - - // So remove it - TheTeamFactory->teamAboutToBeDeleted(iter.cur()); - deleteInstance(iter.cur()); - - done = false; - break; // Not sure what state the iterator is in after deleting a member of the list. jba - } - } - } -} - -// ------------------------------------------------------------------------ -Bool TeamPrototype::hasAnyBuildFacility() const -{ - for (DLINK_ITERATOR iter = iterate_TeamInstanceList(); !iter.done(); iter.advance()) - { - if (iter.cur()->hasAnyBuildFacility()) return true; - } - return false; -} - -// ------------------------------------------------------------------------ -void TeamPrototype::damageTeamMembers(Real amount) -{ - for (DLINK_ITERATOR iter = iterate_TeamInstanceList(); !iter.done(); iter.advance()) - { - iter.cur()->damageTeamMembers(amount); - } -} - - -// ------------------------------------------------------------------------ -void TeamPrototype::moveTeamTo(Coord3D destination) -{ - for (DLINK_ITERATOR iter = iterate_TeamInstanceList(); !iter.done(); iter.advance()) - { - iter.cur()->moveTeamTo(destination); - } -} - -// ------------------------------------------------------------------------ -Bool TeamPrototype::evaluateProductionCondition() -{ - if (m_productionConditionAlwaysFalse) { - // Set if we don't have a script. - return false; - } - if (m_productionConditionScript) { - // If we are doing periodic evaluation, check the frame. - if (TheGameLogic->getFrame()getFrameToEvaluate()) { - return false; - } - Int delaySeconds = m_productionConditionScript->getDelayEvalSeconds(); - - if (delaySeconds>0) { - m_productionConditionScript->setFrameToEvaluate(TheGameLogic->getFrame()+delaySeconds*LOGICFRAMES_PER_SECOND); - } - return TheScriptEngine->evaluateConditions(m_productionConditionScript, nullptr, getControllingPlayer()); - } - // We don't have a script yet, so check for one. - if (m_teamTemplate.m_productionCondition.isEmpty()) { - // No script defined. - m_productionConditionAlwaysFalse = true; - return false; - } - const Script *pScript = TheScriptEngine->findScriptByName(m_teamTemplate.m_productionCondition); - if (pScript) { - // Check difficulty. - switch (getControllingPlayer()->getPlayerDifficulty() ) { - case DIFFICULTY_EASY: - if (!pScript->isEasy()) { - m_productionConditionAlwaysFalse = true; - return false; - } - break; - case DIFFICULTY_NORMAL: - if (!pScript->isNormal()) { - m_productionConditionAlwaysFalse = true; - return false; - } - break; - case DIFFICULTY_HARD: - if (!pScript->isHard()) { - m_productionConditionAlwaysFalse = true; - return false; - } - break; - } - - // Make a copy of the script locally, just for paranoia's sake. We can't be sure - // exactly what order the teams & scripts will get reset, so be safe. - m_productionConditionScript = pScript->duplicate(); - return TheScriptEngine->evaluateConditions(m_productionConditionScript, nullptr, getControllingPlayer()); - } - // Couldn't find a script. - m_productionConditionAlwaysFalse = true; - return false; -} - -// ------------------------------------------------------------------------ -/** CRC */ -// ------------------------------------------------------------------------ -void TeamPrototype::crc( Xfer *xfer ) -{ - -} - -// ------------------------------------------------------------------------ -/** Xfer method - * Version Info: - * 1: Initial version */ -// ------------------------------------------------------------------------ -void TeamPrototype::xfer( Xfer *xfer ) -{ - - // version - XferVersion currentVersion = 2; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - // owning player index - Int owningPlayerIndex; - if( xfer->getXferMode() == XFER_SAVE ) - owningPlayerIndex = m_owningPlayer->getPlayerIndex(); - xfer->xferInt( &owningPlayerIndex ); - m_owningPlayer = ThePlayerList->getNthPlayer( owningPlayerIndex ); - - if (version>=2) { - xfer->xferAsciiString(&m_attackPriorityName); - } - - // production condition - xfer->xferBool( &m_productionConditionAlwaysFalse ); - - // team template information - xfer->xferSnapshot( &m_teamTemplate ); - - // xfer team instance count - UnsignedShort teamInstanceCount = 0; - for( DLINK_ITERATOR iter = iterate_TeamInstanceList(); !iter.done(); iter.advance() ) - teamInstanceCount++; - xfer->xferUnsignedShort( &teamInstanceCount ); - - // xfer team instances - Team *teamInstance; - TeamID teamID; - if( xfer->getXferMode() == XFER_SAVE ) - { - - // xfer each team instance - for( DLINK_ITERATOR iter = iterate_TeamInstanceList(); !iter.done(); iter.advance() ) - { - - // get the team - teamInstance = iter.cur(); - - // write team id - teamID = teamInstance->getID(); - xfer->xferUser( &teamID, sizeof( TeamID ) ); - - // write team data - xfer->xferSnapshot( teamInstance ); - - } - - } - else - { - - // - // there is no need to check to make sure the instance list is empty here ... see - // the large bock comment below where we find a team given an id - // - - // read each block - for( UnsignedShort i = 0; i < teamInstanceCount; ++i ) - { - - // read team id - xfer->xferUser( &teamID, sizeof( TeamID ) ); - - // - // find this team, if it's not there create it ... note that there will in fact - // be some teams in the instance when were are loading as they are creating during - // the map load. But since the team ids are reset on the map load, they are - // created with exactly the same team IDs they had before - // - teamInstance = TheTeamFactory->findTeamByID( teamID ); - if( teamInstance == nullptr ) - { - - // create team - teamInstance = TheTeamFactory->createTeamOnPrototype( this ); - - // restore original ID we read from the file - teamInstance->setID( teamID ); - - } - - // xfer team data - xfer->xferSnapshot( teamInstance ); - - } - - } - -} - -// ------------------------------------------------------------------------ -/** Load post process */ -// ------------------------------------------------------------------------ -void TeamPrototype::loadPostProcess() -{ - -} - -// ------------------------------------------------------------------------ -// ------------------------------------------------------------------------ -// ------------------------------------------------------------------------ - -// ------------------------------------------------------------------------ -// ------------------------------------------------------------------------ -// ------------------------------------------------------------------------ - -// ------------------------------------------------------------------------ -Team::Team(TeamPrototype *proto, TeamID id ) : - m_id( id ), - m_proto(proto), - m_enteredOrExited(false), - m_active(false), - m_seeEnemy(false), - m_prevSeeEnemy(false), - m_checkEnemySighted(false), - m_isRecruitablitySet(false), - m_isRecruitable(false), - m_destroyThreshold(0), - m_curUnits(0), - m_wasIdle(false) -{ - m_created = FALSE; - m_commonAttackTarget = INVALID_ID; - - // allocate new relation map pools - m_playerRelations = newInstance(PlayerRelationMap); - m_teamRelations = newInstance(TeamRelationMap); - - if (proto) - { - proto->prependTo_TeamInstanceList(this); - if (!proto->getTemplateInfo()->m_scriptOnAllClear.isEmpty() || - !proto->getTemplateInfo()->m_scriptOnEnemySighted.isEmpty()) - { - m_checkEnemySighted = true; // Only keep track of enemy sighted if there is a script that cares. - } - - AsciiString teamName = proto->getName(); - teamName.concat(" - creating team instance."); - TheScriptEngine->AppendDebugMessage(teamName, false); - } - - for (Int i = 0; i < MAX_GENERIC_SCRIPTS; ++i) - { - m_shouldAttemptGenericScript[i] = true; - } - - -} - -// ------------------------------------------------------------------------ -Team::~Team() -{ -// DEBUG_ASSERTCRASH(getFirstItemIn_TeamMemberList() == nullptr, ("Team still has members in existence")); - - TheScriptEngine->notifyOfTeamDestruction(this); - - // Tell the players a team is going away. - Int i; - for (i=0; igetPlayerCount(); i++) { - Player *plyr = ThePlayerList->getNthPlayer(i); - if (plyr) { - plyr->preTeamDestroy(this); - } - } - - Object* tm; - while ((tm = getFirstItemIn_TeamMemberList()) != nullptr) - { - tm->setTeam(nullptr); - } -//this test is valid, but will generate a 'false positive' during game teardown -//DEBUG_ASSERTCRASH(!(getControllingPlayer() && getControllingPlayer()->getDefaultTeam()==this),("I am still someones default team -- sure you want to delete me?")); - - DEBUG_ASSERTCRASH(m_proto, ("proto should not be null")); - if (m_proto && m_proto->isInList_TeamInstanceList(this)) - m_proto->removeFrom_TeamInstanceList(this); - - // delete the relation maps (the destructor clears the actual map if any data is present) - deleteInstance(m_teamRelations); - deleteInstance(m_playerRelations); - - // make sure the xfer list is clear - m_xferMemberIDList.clear(); - -} - -// ------------------------------------------------------------------------ -Player *Team::getControllingPlayer() const -{ - return m_proto->getControllingPlayer(); -} - -// ------------------------------------------------------------------------ -void Team::setControllingPlayer(Player *newController) -{ - Player* oldOwner = m_proto->getControllingPlayer(); - // nullptr is not allowed, but is caught by TeamPrototype::setControllingPlayer() - m_proto->setControllingPlayer(newController); - - // This function is used by one script, and it is kind of odd. The actual units - // are not getting captured, the team they are on is being reassigned to a new player. - // The Team doesn't change, it just starts to return a different answer when you ask for - // the controlling player. I don't want to make the major change of onCapture on everyone, - // so I will do the minor fix for the specific bug, which is harmless even when misused. - // TheSuperHackers @fix xezon 07/12/2025 Now does onCapture on everyone. - - // Tell all members to redo their looking status, as their Player has changed, but they don't know. - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - Object *obj = iter.cur(); - if (!obj) - continue; - - if constexpr (RETAIL_COMPATIBLE_CRC) // Not sure if necessary. But likely is. - { - obj->handlePartitionCellMaintenance(); - } - else - { - obj->onCapture(oldOwner, newController); - } - } - -} - -// ------------------------------------------------------------------------ -void Team::setAttackPriorityName(AsciiString name) -{ - if (m_proto) m_proto->setAttackPriorityName(name); -} - -// ------------------------------------------------------------------------ -void Team::getTeamAsAIGroup(AIGroup *pAIGroup) -{ - if (!pAIGroup) { - return; - } - - // Should this clear out the pAIGroup that it receives? I don't think so, but that - // would go here if so. jkmcd - - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) { - if (iter.cur()) { - pAIGroup->add(iter.cur()); - } - } -} - - -// ------------------------------------------------------------------------ -Int Team::getTargetableCount() const -{ - Int retVal = 0; - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) { - Object *obj = iter.cur(); - if (!obj) { - continue; - } - - if (obj->isEffectivelyDead() || (obj->getAIUpdateInterface() == nullptr && !obj->isKindOf(KINDOF_STRUCTURE))) { - continue; - } - - ++retVal; - } - - return retVal; -} - -// ------------------------------------------------------------------------ -Relationship Team::getRelationship(const Team *that) const -{ - // do we have an override for that particular team? if so, return it. - if (!m_teamRelations->m_map.empty() && that != nullptr) - { - TeamRelationMapType::const_iterator it = m_teamRelations->m_map.find(that->getID()); - if (it != m_teamRelations->m_map.end()) - { - return (*it).second; - } - } - - // hummm... well, do we have an override for that team's player? - if (!m_playerRelations->m_map.empty() && that != nullptr) - { - Player* thatPlayer = that->getControllingPlayer(); - if (thatPlayer != nullptr) - { - PlayerRelationMapType::const_iterator it = m_playerRelations->m_map.find(thatPlayer->getPlayerIndex()); - if (it != m_playerRelations->m_map.end()) - { - return (*it).second; - } - } - } - - // nope -- go with our Player's view on the matter. - return getControllingPlayer()->getRelationship(that); -} - -// ------------------------------------------------------------------------ -void Team::setTeamTargetObject(const Object *target) -{ - if (target==nullptr) { - m_commonAttackTarget = INVALID_ID; - return; - } - // Only ai players do common attack. - if (getControllingPlayer()->getPlayerType() == PLAYER_COMPUTER) { - if (getControllingPlayer()->getPlayerDifficulty() == DIFFICULTY_EASY) { - return; // we don't do this for easy. jba. - } - m_commonAttackTarget = target->getID(); - } -} - -// ------------------------------------------------------------------------ -Object *Team::getTeamTargetObject() -{ - if (m_commonAttackTarget == INVALID_ID) { - return nullptr; - } - Object *target = TheGameLogic->findObjectByID(m_commonAttackTarget); - if (target) { - //If the enemy unit is stealthed and not detected, then we can't attack it! - if( target->testStatus( OBJECT_STATUS_STEALTHED ) && - !target->testStatus( OBJECT_STATUS_DETECTED ) -#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) - && !target->testStatus( OBJECT_STATUS_DISGUISED ) -#endif - ) - { - target = nullptr; - } - } - if (target && target->isEffectivelyDead()) { - target = nullptr; - } - if (target && target->getContainedBy()) { - target = nullptr; // target entered a building or vehicle, so stop targeting. - } -#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) - if (target && target->isKindOf(KINDOF_AIRCRAFT)) { - // It is just generally bad to have an aircraft as the team target. - // Let team members acquire aircraft individually. jba. [8/27/2003] - target = nullptr; - } -#endif - if (target == nullptr) { - m_commonAttackTarget = INVALID_ID; - } - return target; -} - -// ------------------------------------------------------------------------ - void Team::setOverrideTeamRelationship( TeamID teamID, Relationship r) -{ - if (teamID != TEAM_ID_INVALID ) - { - // note that this creates the entry if it doesn't exist. - m_teamRelations->m_map[teamID] = r; - } -} - -// ------------------------------------------------------------------------ -Bool Team::removeOverrideTeamRelationship( TeamID teamID ) -{ - if (!m_teamRelations->m_map.empty()) - { - if (teamID == TEAM_ID_INVALID) - { - m_teamRelations->m_map.clear(); - return true; - } - else - { - TeamRelationMapType::iterator it = m_teamRelations->m_map.find(teamID); - if (it != m_teamRelations->m_map.end()) - { - m_teamRelations->m_map.erase(it); - return true; - } - } - } - return false; -} - -// ------------------------------------------------------------------------ -void Team::setOverridePlayerRelationship( Int playerIndex, Relationship r ) -{ - if (playerIndex != PLAYER_INDEX_INVALID) - { - // note that this creates the entry if it doesn't exist. - m_playerRelations->m_map[playerIndex] = r; - } -} - -// ------------------------------------------------------------------------ -Bool Team::removeOverridePlayerRelationship( Int playerIndex ) -{ - if (!m_playerRelations->m_map.empty()) - { - if (playerIndex == PLAYER_INDEX_INVALID) - { - m_playerRelations->m_map.clear(); - return true; - } - else - { - PlayerRelationMapType::iterator it = m_playerRelations->m_map.find(playerIndex); - if (it != m_playerRelations->m_map.end()) - { - m_playerRelations->m_map.erase(it); - return true; - } - } - } - return false; -} - -// ------------------------------------------------------------------------ -void Team::countObjectsByThingTemplate(Int numTmplates, const ThingTemplate* const* things, Bool ignoreDead, Int *counts, Bool ignoreUnderConstruction) const -{ - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - const ThingTemplate *objtmpl = iter.cur()->getTemplate(); - for (Int i = 0; i < numTmplates; ++i) - { - //Kris: Compare - if( !objtmpl->isEquivalentTo( things[i] ) ) - { - continue; - } - - if (ignoreDead && iter.cur()->isEffectivelyDead()) - continue; - - if( ignoreUnderConstruction && iter.cur()->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) ) - continue; - - counts[i] += 1; - break; // from 'next i', NOT 'next object' - - } - } -} - -// ------------------------------------------------------------------------ -Int Team::countBuildings() -{ - int retVal = 0; - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) { - const ThingTemplate* objtmpl = iter.cur()->getTemplate(); - if (!objtmpl) { - continue; - } - if (objtmpl->isKindOf(KINDOF_STRUCTURE)) { - ++retVal; - } - } - return retVal; -} - -// ------------------------------------------------------------------------ -Int Team::countObjects(KindOfMaskType setMask, KindOfMaskType clearMask) -{ - int retVal = 0; - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) { - const ThingTemplate* objtmpl = iter.cur()->getTemplate(); - if (!objtmpl) { - continue; - } - if (objtmpl->isKindOfMulti(setMask, clearMask)) { - ++retVal; - } - } - return retVal; -} - -// ------------------------------------------------------------------------ -void Team::healAllObjects() -{ - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - iter.cur()->healCompletely(); - } -} - -// ------------------------------------------------------------------------ -void Team::iterateObjects( ObjectIterateFunc func, void *userData ) -{ - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - func( iter.cur(), userData ); - } -} - -// ------------------------------------------------------------------------ -Bool Team::hasAnyBuildings() const -{ - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - if (iter.cur()->isEffectivelyDead()) - continue; - - if (iter.cur()->isDestroyed()) - continue; - - if (iter.cur()->isKindOf(KINDOF_STRUCTURE)) - return true; - } - return false; -} - -// ------------------------------------------------------------------------ -Bool Team::hasAnyBuildings(KindOfMaskType kindOf) const -{ - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - if (iter.cur()->isEffectivelyDead()) - continue; - - if (iter.cur()->isDestroyed()) - continue; - - kindOf.set(KINDOF_STRUCTURE); - if (iter.cur()->isKindOfMulti(kindOf, KINDOFMASK_NONE)) - return true; - } - return false; -} - -// ------------------------------------------------------------------------ -Bool Team::hasAnyUnits() const -{ - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - if (iter.cur()->isEffectivelyDead()) - continue; - - if (iter.cur()->isDestroyed()) - continue; - - // If it's a structure, it's not a unit. - if (iter.cur()->isKindOf(KINDOF_STRUCTURE)) continue; - - // If it's a projectile, it's not a unit. - if (iter.cur()->isKindOf(KINDOF_PROJECTILE)) continue; - - // If it's a mine, it's not a unit. - if (iter.cur()->isKindOf(KINDOF_MINE)) continue; - - return true; - } - return false; -} - -// ------------------------------------------------------------------------ -Bool Team::isIdle() const -{ - Bool idle = true; // assume idle. - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - AIUpdateInterface *ai = iter.cur()->getAIUpdateInterface(); - if (!ai) continue; // Non-ai things are idle. - - if (iter.cur()->isEffectivelyDead()) - continue; - - if (!ai->isIdle()) - { - idle = false; - break; - } - } - return idle; -} - -// ------------------------------------------------------------------------ -Bool Team::hasAnyObjects() const -{ - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - if (iter.cur()->isEffectivelyDead()) - continue; - - if (iter.cur()->isDestroyed()) - continue; - - if (iter.cur()->isKindOf(KINDOF_PROJECTILE)) { - continue; // shell & missiles don't count. jba. - } - - if (iter.cur()->isKindOf(KINDOF_INERT)) { - // inert stuff doesn't count. This is for radiation fields, which are living - // so they can be attacked by ambulances. - continue; - } - - if (iter.cur()->isKindOf(KINDOF_MINE)) { - // Mines don't count. - continue; - } - - return true; - } - return false; -} - -// ------------------------------------------------------------------------ -/** Clears m_enteredExited, checks & clears m_created. */ -void Team::updateState() -{ - m_enteredOrExited = false; - if (!m_active) { - return; - } - const TeamTemplateInfo *pInfo = m_proto->getTemplateInfo(); - if (m_created) - { - m_created = false; - // Run the on create script, if any. - if (!pInfo->m_scriptOnCreate.isEmpty()) - { - TheScriptEngine->runScript(pInfo->m_scriptOnCreate, this); - } - - // Set up info for the onDestroyed script, if needed. - if (!pInfo->m_scriptOnDestroyed.isEmpty() ) - { - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - m_curUnits++; - } - m_destroyThreshold = m_curUnits - (m_curUnits * pInfo->m_destroyedThreshold); - if (m_destroyThreshold>m_curUnits-1) m_destroyThreshold = m_curUnits-1; - if (m_destroyThreshold<0) m_destroyThreshold = 0; - } - } - - // Do enemy sighted/on clear checks. - if (m_checkEnemySighted) { - m_prevSeeEnemy = m_seeEnemy; - m_seeEnemy = false; - Bool anyAliveInTeam = false; // If we're all dead, don't do all clear. - // only consider enemies. - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - if (iter.cur()->isEffectivelyDead()) - continue; - - PartitionFilterRelationship filterTeam(iter.cur(), PartitionFilterRelationship::ALLOW_ENEMIES); - - // and only stuff that is not dead - PartitionFilterAlive filterAlive; - PartitionFilterSameMapStatus filterMapStatus(iter.cur()); - - PartitionFilter *filters[] = { &filterTeam, &filterAlive, &filterMapStatus, nullptr }; - Real visionRange = iter.cur()->getVisionRange(); - anyAliveInTeam = true; - Object *pObj = ThePartitionManager->getClosestObject( iter.cur(), visionRange, - FROM_CENTER_2D, filters ); - if (pObj) { - m_seeEnemy = true; - break; - } - } - if (anyAliveInTeam) { - if (m_prevSeeEnemy != m_seeEnemy) - { - if (m_seeEnemy) - { - // fire onEnemySighted - TheScriptEngine->runScript(pInfo->m_scriptOnEnemySighted, this); - } else { - // fire on all clear. - TheScriptEngine->runScript(pInfo->m_scriptOnAllClear, this); - } - } - } - } - - // Do onDestroyed checks. - if (!pInfo->m_scriptOnDestroyed.isEmpty()) - { - Int prevUnits = m_curUnits; - m_curUnits = 0; - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - if (iter.cur()->isEffectivelyDead()) - continue; - - m_curUnits++; - } - if (m_curUnits != prevUnits && m_curUnits <= m_destroyThreshold) - { - TheScriptEngine->runScript(pInfo->m_scriptOnDestroyed, this); - m_destroyThreshold = -1; // don't trigger again. - } - } - - // Do onIdle checks. - if (!pInfo->m_scriptOnIdle.isEmpty()) - { - Bool isIdle = true; - Bool anyAliveInTeam = false; // If we're all dead, don't do all clear. - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - if (iter.cur()->isEffectivelyDead()) { - continue; - } - AIUpdateInterface *ai = iter.cur()->getAIUpdateInterface(); - if (!ai) continue; - anyAliveInTeam = true; - if (!ai->isIdle()) { - isIdle = false; - } - } - if (anyAliveInTeam && isIdle && m_wasIdle) - { - TheScriptEngine->runScript(pInfo->m_scriptOnIdle, this); - } - m_wasIdle = isIdle; - } -} - -// ------------------------------------------------------------------------ -void Team::notifyTeamOfObjectDeath() -{ - const TeamTemplateInfo *pInfo = m_proto->getTemplateInfo(); - if (!pInfo) { - return; - } - - if (pInfo->m_scriptOnUnitDestroyed.isEmpty()) { - return; - } - - TheScriptEngine->runScript(pInfo->m_scriptOnUnitDestroyed, this); -} - -// ------------------------------------------------------------------------ -Bool Team::didAllEnter(PolygonTrigger *pTrigger, UnsignedInt whichToConsider) const -{ - // If any units entered or exited, they set this flag. - if (!m_enteredOrExited) return false; - - Bool anyConsidered = false; - Bool entered = false; - Bool outside = false; - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - AIUpdateInterface *ai = iter.cur()->getAIUpdateInterface(); - if (ai) { - const LocomotorSet& locoSet = ai->getLocomotorSet(); - { - if (!locoSetMatches(locoSet.getValidSurfaces(), whichToConsider)) { - continue; - } - } - } else { - // things without ai should consider themselves ground units - if (!locoSetMatches(LOCOMOTORSURFACE_GROUND, whichToConsider)) { - continue; - } - } - - if (iter.cur()->isEffectivelyDead()) - continue; - - if (iter.cur()->isKindOf(KINDOF_INERT)) - continue; - - if (iter.cur()->didEnter(pTrigger)) { - entered = true; - } else { - if (!iter.cur()->isInside(pTrigger)) { - outside = true; - } - } - - // We need this in order to prevent this from returning a false positive - anyConsidered = true; - } - return entered && !outside; -} - -// ------------------------------------------------------------------------ -Bool Team::didPartialEnter(PolygonTrigger *pTrigger, UnsignedInt whichToConsider) const -{ - // If any units entered or exited, they set this flag. - if (!m_enteredOrExited) return false; - - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - AIUpdateInterface *ai = iter.cur()->getAIUpdateInterface(); - if (ai) { - const LocomotorSet& locoSet = ai->getLocomotorSet(); - { - if (!locoSetMatches(locoSet.getValidSurfaces(), whichToConsider)) { - continue; - } - } - } else { - // things without ai should consider themselves ground units - if (!locoSetMatches(LOCOMOTORSURFACE_GROUND, whichToConsider)) { - continue; - } - } - - if (iter.cur()->isEffectivelyDead()) - continue; - - if (iter.cur()->isKindOf(KINDOF_INERT)) - continue; - - if (iter.cur()->didEnter(pTrigger)) { - return true; - } - } - return false; -} - -// ------------------------------------------------------------------------ -Bool Team::didPartialExit(PolygonTrigger *pTrigger, UnsignedInt whichToConsider) const -{ - // If any units entered or exited, they set this flag. - if (!m_enteredOrExited) return false; - - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - AIUpdateInterface *ai = iter.cur()->getAIUpdateInterface(); - if (ai) { - const LocomotorSet& locoSet = ai->getLocomotorSet(); - { - if (!locoSetMatches(locoSet.getValidSurfaces(), whichToConsider)) { - continue; - } - } - } else { - // things without ai should consider themselves ground units - if (!locoSetMatches(LOCOMOTORSURFACE_GROUND, whichToConsider)) { - continue; - } - } - - if (iter.cur()->isEffectivelyDead()) - continue; - - if (iter.cur()->isKindOf(KINDOF_INERT)) - continue; - - if (iter.cur()->didExit(pTrigger)) { - return true; - } - } - return false; -} - -// ------------------------------------------------------------------------ -Bool Team::didAllExit(PolygonTrigger *pTrigger, UnsignedInt whichToConsider) const -{ - // If any units entered or exited, they set this flag. - if (!m_enteredOrExited) - return false; - - Bool anyConsidered = false; - Bool exited = false; - Bool inside = false; - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - AIUpdateInterface *ai = iter.cur()->getAIUpdateInterface(); - if (ai) { - const LocomotorSet& locoSet = ai->getLocomotorSet(); - { - if (!locoSetMatches(locoSet.getValidSurfaces(), whichToConsider)) { - continue; - } - } - } else { - // things without ai should consider themselves ground units - if (!locoSetMatches(LOCOMOTORSURFACE_GROUND, whichToConsider)) { - continue; - } - } - - if (iter.cur()->isEffectivelyDead()) - continue; - - if (iter.cur()->isKindOf(KINDOF_INERT)) - continue; - - if (iter.cur()->didExit(pTrigger)) { - exited = true; - } else { - if (iter.cur()->isInside(pTrigger)) { - inside = true; - } - } - - // We need this in order to prevent this from returning a false positive - anyConsidered = true; - } - return anyConsidered && exited && !inside; -} - -// ------------------------------------------------------------------------ -Bool Team::allInside(PolygonTrigger *pTrigger, UnsignedInt whichToConsider) const -{ - // empty teams are not inside. - if (!hasAnyObjects()) { - return false; - } - - Bool anyConsidered = false; - Bool anyOutside = false; - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - AIUpdateInterface *ai = iter.cur()->getAIUpdateInterface(); - if (ai) { - const LocomotorSet& locoSet = ai->getLocomotorSet(); - { - if (!locoSetMatches(locoSet.getValidSurfaces(), whichToConsider)) { - continue; - } - } - } else { - // things without ai should consider themselves ground units - if (!locoSetMatches(LOCOMOTORSURFACE_GROUND, whichToConsider)) { - continue; - } - } - - if (iter.cur()->isEffectivelyDead()) { - continue; - } - - if (iter.cur()->isKindOf(KINDOF_INERT)) - continue; - - if (!iter.cur()->isInside(pTrigger)) { - anyOutside = true; - } - - // We need this in order to prevent this from returning a false positive - anyConsidered = true; - } - return anyConsidered && !anyOutside; -} - -// ------------------------------------------------------------------------ -Bool Team::noneInside(PolygonTrigger *pTrigger, UnsignedInt whichToConsider) const -{ - Bool anyConsidered = false; - Bool anyInside = false; - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - AIUpdateInterface *ai = iter.cur()->getAIUpdateInterface(); - if (ai) { - const LocomotorSet& locoSet = ai->getLocomotorSet(); - { - if (!locoSetMatches(locoSet.getValidSurfaces(), whichToConsider)) { - continue; - } - } - } else { - // things without ai should consider themselves ground units - if (!locoSetMatches(LOCOMOTORSURFACE_GROUND, whichToConsider)) { - continue; - } - } - - // don't consider dead things. - if (iter.cur()->isEffectivelyDead()) { - continue; - } - - if (iter.cur()->isKindOf(KINDOF_INERT)) - continue; - - if (iter.cur()->isInside(pTrigger)) { - anyInside = true; - } - - // We need this in order to prevent this from returning a false positive - anyConsidered = true; - } - return anyConsidered && !anyInside; -} - -// ------------------------------------------------------------------------ -Bool Team::someInsideSomeOutside(PolygonTrigger *pTrigger, UnsignedInt whichToConsider) const -{ - Bool anyConsidered = false; - Bool anyInside = false; - Bool anyOutside = false; - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - AIUpdateInterface *ai = iter.cur()->getAIUpdateInterface(); - if (ai) { - const LocomotorSet& locoSet = ai->getLocomotorSet(); - { - if (!locoSetMatches(locoSet.getValidSurfaces(), whichToConsider)) { - continue; - } - } - } else { - // things without ai should consider themselves ground units - if (!locoSetMatches(LOCOMOTORSURFACE_GROUND, whichToConsider)) { - continue; - } - } - - // don't consider dead things. - if (iter.cur()->isEffectivelyDead()) { - continue; - } - - if (iter.cur()->isKindOf(KINDOF_INERT)) - continue; - - if (iter.cur()->isInside(pTrigger)) { - anyInside = true; - } else { - anyOutside = true; - } - - // In this particular case, this is unnecessary. However, unless it is a performance hit, please - // leave it. - anyConsidered = true; - } - return anyConsidered && anyInside && anyOutside; -} - -const Coord3D* Team::getEstimateTeamPosition() const -{ - // this doesn't actually calculate the team position, but rather estimates it by - // returning the position of the first member of the team - DLINK_ITERATOR iter = iterate_TeamMemberList(); - Object *obj = iter.cur(); - if (!obj) - return nullptr; - - const Coord3D *pos = iter.cur()->getPosition(); - if (!pos) - return nullptr; - - return pos; -} - -// ------------------------------------------------------------------------ -void Team::deleteTeam(Bool ignoreDead) -{ - // First off, if this Team is the Player's default team, we need to Evacuate everyone or else - // Garrisoned buildings will fall victim to this deletion as well, since they were added to the - // Default when captured. Design intends with this script to kill the people out from inside. - // If the thing is a transport, everything will still work, as the issue at hand is the container's - // wanting to change sides when emptied. The bug is that the people in the Garrisoned building - // are deleted, and that changes the Team of the building, and then the DLink walks down the new team - // and deletes the wrong stuff. Like every tree and civialian building on the map. - // Of course, to prevent the exact same DLINK jumping bug, I must first record what guys I am going to - // Evacuate, or else after the first occupied building is emptied, he will move his Next into the - // same damn wrong team. - if( this == getControllingPlayer()->getDefaultTeam() ) - { - std::list guysToMakeEvacuate; - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - Object *obj = iter.cur(); - if (!obj) - continue; - - if( obj->getContain() && (obj->getContain()->getContainCount() > 0) ) - { - // Write them all down, so the DLINK track jumping doesn't screw me up here as well. - guysToMakeEvacuate.push_back( obj ); - } - } - - for( std::list::iterator it = guysToMakeEvacuate.begin(); it != guysToMakeEvacuate.end(); /*nothing*/ ) - { - Object *obj = *it; - it++; - if( obj->getContain() ) - { - obj->getContain()->removeAllContained(); - } - } - } - - // this doesn't actually delete the team, it deletes the members of the team. - // the team itself will be deleted in updateState. - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - Object *obj = iter.cur(); - if (!obj) { - continue; - } - - // The reason the comment says the team will be deleted is because it will see that it is empty. - // So yes, the Team will survive for a while, but it was going to anyway. This is a script flag, so if - // they use it on a team with things that can't die, then yeah, the Team will last forever. But then it is - // user error. - if( ignoreDead && obj->isEffectivelyDead() ) - continue; - - TheGameLogic->destroyObject(obj); - } -} - -// ------------------------------------------------------------------------ -/* Transfer our units to new team. */ -void Team::transferUnitsTo(Team *newTeam) -{ - if (this == newTeam) return; - if (newTeam == nullptr) return; - Object *obj; - while ((obj = getFirstItemIn_TeamMemberList()) != nullptr) - { - obj->setTeam(newTeam); - } -} - -// ------------------------------------------------------------------------ -static Bool isInBuildVariations(const ThingTemplate* ttWithVariations, const ThingTemplate* b) -{ - const std::vector& bv = ttWithVariations->getBuildVariations(); - if (bv.empty()) - return false; - - for (std::vector::const_iterator it = bv.begin(); it != bv.end(); ++it) - { - if (b->getName() == *it) - return true; - } - return false; -} - -// ------------------------------------------------------------------------ -/* Try to recruit a unit from other teams of this player. */ -Object *Team::tryToRecruit(const ThingTemplate *tTemplate, const Coord3D *teamHome, Real maxDist) -{ - Player *myPlayer = getControllingPlayer(); - Object *obj=nullptr; - Real distSqr = maxDist*maxDist; - Object *recruit = nullptr; - for( obj = TheGameLogic->getFirstObject(); obj; obj = obj->getNextObject() ) - { - if (!obj->getTemplate()->isEquivalentTo(tTemplate)) - { - // it might be ok, if tTemplate is really just a "build-variations" template... - if (!isInBuildVariations(tTemplate, obj->getTemplate())) - continue; - } - if (obj->getControllingPlayer() != myPlayer) - continue; - Team *team = obj->getTeam(); - Bool isDefaultTeam = false; - if (team == myPlayer->getDefaultTeam()) { - isDefaultTeam = true; - } - if (!team->isActive()) { - continue; // Team is building, so don't steal it's members yet. - } - if (team->getPrototype()->getTemplateInfo()->m_productionPriority>=getPrototype()->getTemplateInfo()->m_productionPriority) { - continue; - } - Bool teamIsRecruitable = isDefaultTeam; // Default team always recruitable. - if (team->getPrototype()->getTemplateInfo()->m_isAIRecruitable) { - teamIsRecruitable = true; - } - // Check & see if individual team has been marked for recruitability. - if (team->m_isRecruitablitySet) { - teamIsRecruitable = team->m_isRecruitable; - } - if (!teamIsRecruitable) { - continue; - } - if (obj->getAIUpdateInterface() && !obj->getAIUpdateInterface()->isRecruitable()) { - continue; // can't recruit this unit. - } - if( obj->isDisabledByType( DISABLED_HELD ) ) - { - continue; // Don't recruit held units. - } - Real dx, dy; - dx = teamHome->x - obj->getPosition()->x; - dy = teamHome->y - obj->getPosition()->y; - - if (isDefaultTeam && recruit == nullptr) { - recruit = obj; - distSqr = dx*dx+dy*dy; - } - - if (dx*dx+dy*dy > distSqr) { - continue; - } - distSqr = dx*dx+dy*dy; - recruit = obj; - } - if (recruit!=nullptr) { - return recruit; - } - return nullptr; -} - -// ------------------------------------------------------------------------ -void Team::evacuateTeam() -{ - std::list objectsToProcess; - - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) { - Object *obj = iter.cur(); - if (!obj || obj->isDestroyed() || obj->isEffectivelyDead()) { - continue; - } - - ContainModuleInterface *cmi = obj->getContain(); - UnsignedInt numContained = 0; - if (cmi != nullptr) { - numContained = cmi->getContainCount(); - } - if (numContained > 0) { - objectsToProcess.push_back(obj); - } - } - - // evacuate any containers - std::list::iterator objIt; - for (objIt = objectsToProcess.begin(); objIt != objectsToProcess.end(); ++objIt) - { - Object *obj = *objIt; - ContainModuleInterface *cmi = obj->getContain(); - if (cmi) - { - cmi->removeAllContained(); - } - } - objectsToProcess.clear(); -} - -// ------------------------------------------------------------------------ -void Team::killTeam() -{ - std::list objectsToProcess; - - evacuateTeam(); - - // TheSuperHackers @bugfix Mauller 20/07/2025 the neutral player has no player template so we need to check for a null template - const PlayerTemplate* playerTemplate = getControllingPlayer()->getPlayerTemplate(); - // beacons are effectively dead, so we need to destroy via a non-kill() method - const ThingTemplate* beaconTemplate = playerTemplate ? TheThingFactory->findTemplate( playerTemplate->getBeaconTemplate() ) : nullptr; - - // now find objects to kill - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) { - Object *obj = iter.cur(); - if (!obj || obj->isDestroyed() || (obj->isEffectivelyDead() && !obj->getTemplate()->isEquivalentTo(beaconTemplate))) - { - continue; - } - Team *objTeam = obj->getTeam(); - // the object's team could change after having all the passengers get out. - if (objTeam == this) { - objectsToProcess.push_back(obj); - } - } - - // and finally, kill things - std::list::iterator objIt; - for (objIt = objectsToProcess.begin(); objIt != objectsToProcess.end(); ++objIt) - { - Object *obj = *objIt; - if (obj->isKindOf(KINDOF_TECH_BUILDING)) - obj->setTeam(ThePlayerList->getNeutralPlayer()->getDefaultTeam()); - else - obj->kill(); - } - objectsToProcess.clear(); -} - -// ------------------------------------------------------------------------ -Bool Team::damageTeamMembers(Real amount) -{ - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - if (iter.cur()->isEffectivelyDead()) - continue; - - if (iter.cur()->isDestroyed()) - continue; - - // do max amount of damage to object - if (amount < 0.0) { - iter.cur()->kill(); - } else { - DamageInfo damageInfo; - - damageInfo.in.m_damageType = DAMAGE_UNRESISTABLE; - damageInfo.in.m_deathType = DEATH_NORMAL; - damageInfo.in.m_sourceID = INVALID_ID; - damageInfo.in.m_amount = amount; - iter.cur()->attemptDamage( &damageInfo ); - } - - } - return false; -} - -// ------------------------------------------------------------------------ -/// @todo This should give a "team move" command, not individual move orders (MSB) -void Team::moveTeamTo(Coord3D destination) -{ - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - if (iter.cur()->isEffectivelyDead()) - continue; - - if (iter.cur()->isDestroyed()) - continue; - } -} - -// ------------------------------------------------------------------------ -Bool Team::hasAnyBuildFacility() const -{ - for (DLINK_ITERATOR iter = iterate_TeamMemberList(); !iter.done(); iter.advance()) - { - const ThingTemplate *objtmpl = iter.cur()->getTemplate(); - if (objtmpl->isBuildFacility()) - return true; - } - return false; -} - -// ------------------------------------------------------------------------ -//DECLARE_PERF_TIMER(updateGenericScripts) -void Team::updateGenericScripts() -{ - //USE_PERF_TIMER(updateGenericScripts) - for (Int i = 0; i < MAX_GENERIC_SCRIPTS; ++i) { - if (m_shouldAttemptGenericScript[i]) { - // Does the condition succeed? If so, run it. If it is a run once script, also mark that we - // shouldn't run it again. - Script *script = m_proto->getGenericScript(i); - if (script) { - if (TheScriptEngine->evaluateConditions(script, this)) { - // It was successful. - if (script->isOneShot()) { - m_shouldAttemptGenericScript[i] = false; - } - TheScriptEngine->friend_executeAction(script->getAction(), this); - AsciiString msg = "Generic script '"; - msg.concat(script->getName()); - msg.concat("' run on team "); - msg.concat(getName()); - TheScriptEngine->AppendDebugMessage(msg, false); - } - } else { - m_shouldAttemptGenericScript[i] = false; - } - } - } -} - -// ------------------------------------------------------------------------------------------------ -/** CRC */ -// ------------------------------------------------------------------------------------------------ -void Team::crc( Xfer *xfer ) -{ - -} - -// ------------------------------------------------------------------------------------------------ -/** Xfer Method - * Version Info: - * 1: Initial version */ -// ------------------------------------------------------------------------------------------------ -void Team::xfer( Xfer *xfer ) -{ - - // version - XferVersion currentVersion = 1; - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - // xfer id, this is a sanity check as team id m_id should always be valid at this point - TeamID teamID = m_id; - xfer->xferUser( &teamID, sizeof( TeamID ) ); - if( teamID != m_id ) - { - - DEBUG_CRASH(( "Team::xfer - TeamID mismatch. Xfered '%d' but should be '%d'", - teamID, m_id )); - throw SC_INVALID_DATA; - - } - - // member list count and data - ObjectID memberID; - UnsignedShort memberCount = 0; - for( DLINK_ITERATOR< Object > objIt = iterate_TeamMemberList(); - objIt.done() == FALSE; - objIt.advance() ) - memberCount++; - xfer->xferUnsignedShort( &memberCount ); - if( xfer->getXferMode() == XFER_SAVE ) - { - Object *obj; - - // save all member info - for( DLINK_ITERATOR< Object > objIt = iterate_TeamMemberList(); - objIt.done() == FALSE; - objIt.advance() ) - { - - // get object - obj = objIt.cur(); - - // save id - memberID = obj->getID(); - xfer->xferObjectID( &memberID ); - - } - - } - else - { - - // load all members - for( UnsignedShort i = 0; i < memberCount; ++i ) - { - - // read ID - xfer->xferObjectID( &memberID ); - - // put on pending list for later processing - m_xferMemberIDList.push_back( memberID ); - - } - - } - - // state - xfer->xferAsciiString( &m_state ); - - // entered or exited - xfer->xferBool( &m_enteredOrExited ); - - // active status - xfer->xferBool( &m_active ); - - // created flag - xfer->xferBool( &m_created ); - - // check enemy sighted - xfer->xferBool( &m_checkEnemySighted ); - - // see enemy - xfer->xferBool( &m_seeEnemy ); - - // previous see enemy - xfer->xferBool( &m_prevSeeEnemy ); - - // was idle - xfer->xferBool( &m_wasIdle ); - - // destroy threshold - xfer->xferInt( &m_destroyThreshold ); - - // current units - xfer->xferInt( &m_curUnits ); - - // waypoint - UnsignedInt currentWaypointID = m_currentWaypoint ? m_currentWaypoint->getID() : 0; - xfer->xferUnsignedInt( ¤tWaypointID ); - if( xfer->getXferMode() == XFER_LOAD ) - m_currentWaypoint = TheTerrainLogic->getWaypointByID( currentWaypointID ); - - UnsignedShort shouldAttemptGenericScriptCount = MAX_GENERIC_SCRIPTS; - xfer->xferUnsignedShort( &shouldAttemptGenericScriptCount ); - if ( shouldAttemptGenericScriptCount != MAX_GENERIC_SCRIPTS ) - { - DEBUG_CRASH(("Team::xfer - The number of allowable Generic scripts has changed, and this chunk needs to be versioned.")); - throw SC_INVALID_DATA; - } - - for (Int i = 0; i < shouldAttemptGenericScriptCount; ++i) - xfer->xferBool(&m_shouldAttemptGenericScript[i]); - - // recruitability set - xfer->xferBool( &m_isRecruitablitySet ); - - // is recruitable - xfer->xferBool( &m_isRecruitable ); - - // Common attack target. - xfer->xferObjectID( &m_commonAttackTarget ); - - // team relations - xfer->xferSnapshot( m_teamRelations ); - - // player relations - xfer->xferSnapshot( m_playerRelations ); - -} - -// ------------------------------------------------------------------------------------------------ -/** Load post process */ -// ------------------------------------------------------------------------------------------------ -void Team::loadPostProcess() -{ - - // - // now that all objects have actually been loaded, populate the member list with - // real object pointers - // - Object *obj; - std::list< ObjectID >::const_iterator it; - for( it = m_xferMemberIDList.begin(); it != m_xferMemberIDList.end(); ++it ) - { - - // find object - obj = TheGameLogic->findObjectByID( *it ); - if( obj == nullptr ) - { - - DEBUG_CRASH(( "Team::loadPostProcess - Unable to post process object to member list, object ID = '%d'", *it )); - throw SC_INVALID_DATA; - - } - - // - // we are now disabling this code since the objects set their team during their - // own xfer function which will actually put it on the team ... however, we will sanity - // check everything here to make sure that all the objects that should be on the team, - // are in fact on the team - // - if( isInList_TeamMemberList( obj ) == FALSE ) - { - - DEBUG_CRASH(( "Team::loadPostProcess - Object '%s'(%d) should be in team list but is not", - obj->getTemplate()->getName().str(), obj->getID() )); - throw SC_INVALID_DATA; - - } - - } - - // since we prepended the object member pointers, reverse that list so it's just like before -// reverse_TeamMemberList(); - - // we're done with the xfer list now - m_xferMemberIDList.clear(); - -} - - - -// ------------------------------------------------------------------------ -// ------------------------------------------------------------------------ -// ------------------------------------------------------------------------ - diff --git a/Generals/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp b/Generals/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp deleted file mode 100644 index 98fa254c058..00000000000 --- a/Generals/Code/GameEngine/Source/Common/RTS/TunnelTracker.cpp +++ /dev/null @@ -1,569 +0,0 @@ -/* -** Command & Conquer Generals(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 . -*/ - -//////////////////////////////////////////////////////////////////////////////// -// // -// (c) 2001-2003 Electronic Arts Inc. // -// // -//////////////////////////////////////////////////////////////////////////////// - -// FILE: TunnelTracker.cpp /////////////////////////////////////////////////////////// -// The part of a Player's brain that holds the communal Passenger list of all tunnels. -// Author: Graham Smallwood, March, 2002 - -#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine - -#include "Common/GameState.h" -#include "Common/GlobalData.h" -#include "Common/KindOf.h" -#include "Common/TunnelTracker.h" -#include "Common/Xfer.h" - -#include "GameClient/ControlBar.h" -#include "GameClient/Drawable.h" - -#include "GameLogic/AI.h" -#include "GameLogic/AIPathfind.h" -#include "GameLogic/GameLogic.h" -#include "GameLogic/Object.h" -#include "GameLogic/PartitionManager.h" - -#include "GameLogic/Module/BodyModule.h" -#include "GameLogic/Module/TunnelContain.h" - - -// ------------------------------------------------------------------------ -TunnelTracker::TunnelTracker() -{ -#if RETAIL_COMPATIBLE_CRC - m_tunnelCount = 0; -#endif - m_containListSize = 0; - m_heroUnitsContained = 0; - m_curNemesisID = INVALID_ID; - m_nemesisTimestamp = 0; - m_framesForFullHeal = 0; - m_needsFullHealTimeUpdate = false; -} - -// ------------------------------------------------------------------------ -TunnelTracker::~TunnelTracker() -{ - m_tunnelIDs.clear(); -} - -// ------------------------------------------------------------------------ -void TunnelTracker::iterateContained( ContainIterateFunc func, void *userData, Bool reverse ) -{ - if (reverse) - { - // note that this has to be smart enough to handle items in the list being deleted - // via the callback function. - for(ContainedItemsList::reverse_iterator it = m_containList.rbegin(); it != m_containList.rend(); ) - { - // save the obj... - Object* obj = *it; - - // incr the iterator BEFORE calling the func (if the func removes the obj, - // the iterator becomes invalid) - ++it; - - // call it - (*func)( obj, userData ); - } - } - else - { - // note that this has to be smart enough to handle items in the list being deleted - // via the callback function. - for(ContainedItemsList::iterator it = m_containList.begin(); it != m_containList.end(); ) - { - // save the obj... - Object* obj = *it; - - // incr the iterator BEFORE calling the func (if the func removes the obj, - // the iterator becomes invalid) - ++it; - - // call it - (*func)( obj, userData ); - } - } -} - -// ------------------------------------------------------------------------ -Int TunnelTracker::getContainMax() const -{ - return TheGlobalData->m_maxTunnelCapacity; -} - -// ------------------------------------------------------------------------ -void TunnelTracker::swapContainedItemsList(ContainedItemsList& newList) -{ - m_containList.swap(newList); - m_containListSize = (Int)m_containList.size(); -} - -// ------------------------------------------------------------------------ -void TunnelTracker::updateNemesis(const Object *target) -{ - if (getCurNemesis()==nullptr) { - if (target) { - if (target->isKindOf(KINDOF_VEHICLE) || target->isKindOf(KINDOF_STRUCTURE) || - target->isKindOf(KINDOF_INFANTRY) || target->isKindOf(KINDOF_AIRCRAFT)) { - m_curNemesisID = target->getID(); - m_nemesisTimestamp = TheGameLogic->getFrame(); - } - } - } else if (getCurNemesis()==target) { - m_nemesisTimestamp = TheGameLogic->getFrame(); - } -} - -// ------------------------------------------------------------------------ -Object *TunnelTracker::getCurNemesis() -{ - if (m_curNemesisID == INVALID_ID) { - return nullptr; - } - if (m_nemesisTimestamp + 4*LOGICFRAMES_PER_SECOND < TheGameLogic->getFrame()) { - m_curNemesisID = INVALID_ID; - return nullptr; - } - Object *target = TheGameLogic->findObjectByID(m_curNemesisID); - if (target) { - //If the enemy unit is stealthed and not detected, then we can't attack it! - if( target->testStatus( OBJECT_STATUS_STEALTHED ) && - !target->testStatus( OBJECT_STATUS_DETECTED ) -#if !(RTS_GENERALS && RETAIL_COMPATIBLE_CRC) - && !target->testStatus( OBJECT_STATUS_DISGUISED ) -#endif - ) - { - target = nullptr; - } - } - if (target && target->isEffectivelyDead()) { - target = nullptr; - } - if (target == nullptr) { - m_curNemesisID = INVALID_ID; - } - return target; -} - -// ------------------------------------------------------------------------ -Bool TunnelTracker::isValidContainerFor(const Object* obj, Bool checkCapacity) const -{ - //October 11, 2002 -- Kris : Dustin wants ALL units to be able to use tunnels! - // srj sez: um, except aircraft. - if (obj && !obj->isKindOf(KINDOF_AIRCRAFT)) - { - if (checkCapacity) - { - Int containMax = getContainMax(); - Int containCount = getContainCount(); - return ( containCount < containMax ); - } - else - { - return true; - } - } - return false; -} - -// ------------------------------------------------------------------------ -void TunnelTracker::addToContainList( Object *obj ) -{ - m_containList.push_back(obj); - ++m_containListSize; - - if (obj->isKindOf(KINDOF_HERO)) - { - ++m_heroUnitsContained; - } -} - -// ------------------------------------------------------------------------ -Bool TunnelTracker::removeFromContain( Object *obj, Bool exposeStealthUnits ) -{ - - ContainedItemsList::iterator it = std::find(m_containList.begin(), m_containList.end(), obj); - if (it != m_containList.end()) - { - // note that this invalidates the iterator! - m_containList.erase(it); - --m_containListSize; - - if (obj->isKindOf(KINDOF_HERO)) - { - DEBUG_ASSERTCRASH(m_heroUnitsContained > 0, ("TunnelTracker::removeFromContain - Removing hero but hero count is %d", m_heroUnitsContained)); - --m_heroUnitsContained; - } - - return true; - } - - return false; -} - -// ------------------------------------------------------------------------ -Bool TunnelTracker::isInContainer( Object *obj ) -{ - return (std::find(m_containList.begin(), m_containList.end(), obj) != m_containList.end()) ; -} - -// ------------------------------------------------------------------------ -void TunnelTracker::onTunnelCreated( const Object *newTunnel ) -{ - DEBUG_ASSERTCRASH(std::find(m_tunnelIDs.begin(), m_tunnelIDs.end(), newTunnel->getID()) == m_tunnelIDs.end(), - ("TunnelTracker::onTunnelCreated - New tunnel was already added; this shouldn't happen")); - -#if RETAIL_COMPATIBLE_CRC - m_tunnelCount++; -#endif - m_tunnelIDs.push_back( newTunnel->getID() ); - m_needsFullHealTimeUpdate = true; -} - -// ------------------------------------------------------------------------ -void TunnelTracker::onTunnelDestroyed( const Object *deadTunnel ) -{ -#if RETAIL_COMPATIBLE_CRC - - DEBUG_ASSERTLOG(static_cast(m_tunnelCount) > 0 && m_tunnelCount == m_tunnelIDs.size(), - ("TunnelTracker::onTunnelDestroyed - Tunnel count is unexpected")); - - const size_t oldSize = m_tunnelIDs.size(); - m_tunnelIDs.remove(deadTunnel->getID()); - - (void)oldSize; - DEBUG_ASSERTLOG(oldSize != m_tunnelIDs.size(), - ("TunnelTracker::onTunnelDestroyed - Attempting to remove object '%s' that has never been tracked as a tunnel", deadTunnel->getName().str())); - - m_tunnelCount--; - - if( m_tunnelCount == 0 ) - { - // Kill everyone in our contain list. Cave in! - iterateContained( destroyObject, nullptr, FALSE ); - m_containList.clear(); - m_containListSize = 0; - } - else - { - // TheSuperHackers @bugfix Caball009 01/09/2026 Check if container is empty before accessing it. - // The tunnel count may diverge from the container size, because of bugs that cannot be fixed with - // retail compatibility enabled. Expected retail behavior: empty container access results in a nullptr. - Object *tunnel = m_tunnelIDs.empty() ? nullptr : TheGameLogic->findObjectByID( m_tunnelIDs.front() ); - - // Otherwise, make sure nobody inside remembers the dead tunnel as the one they entered - // (scripts need to use so there must be something valid here) - for(ContainedItemsList::iterator it = m_containList.begin(); it != m_containList.end(); ) - { - Object* obj = *it; - ++it; - if( obj->getContainedBy() == deadTunnel ) - obj->onContainedBy( tunnel ); - } - } - -#else - - const std::list::iterator it = std::find(m_tunnelIDs.begin(), m_tunnelIDs.end(), deadTunnel->getID()); - if (it != m_tunnelIDs.end()) - { - m_tunnelIDs.erase(it); - - m_needsFullHealTimeUpdate = true; - } - else - { - DEBUG_CRASH(("TunnelTracker::onTunnelDestroyed - Attempting to remove object '%s' that has never been tracked as a tunnel", - deadTunnel->getName().str())); - } - - if( m_tunnelIDs.empty() ) - { - // Kill everyone in our contain list. Cave in! - iterateContained( destroyObject, nullptr, FALSE ); - m_containList.clear(); - m_containListSize = 0; - } - else - { - Object *validTunnel = TheGameLogic->findObjectByID( m_tunnelIDs.front() ); - - // Otherwise, make sure nobody inside remembers the dead tunnel as the one they entered - // (scripts need to use so there must be something valid here) - for(ContainedItemsList::iterator it = m_containList.begin(); it != m_containList.end(); ) - { - Object* obj = *it; - ++it; - if( obj->getContainedBy() == deadTunnel ) - obj->onContainedBy( validTunnel ); - } - } - -#endif // RETAIL_COMPATIBLE_CRC -} - -// ------------------------------------------------------------------------ -void TunnelTracker::destroyObject( Object *obj, void * ) -{ - // Now that tunnels consider ContainedBy to be "the tunnel you entered", I need to say goodbye - // like other contain types so they don't look us up on their deletion and crash - obj->onRemovedFrom( obj->getContainedBy() ); - TheGameLogic->destroyObject( obj ); -} - -// ------------------------------------------------------------------------ - // heal all the objects within the tunnel system using the iterateContained function -#if RETAIL_COMPATIBLE_CRC || PRESERVE_TUNNEL_HEAL_STACKING -void TunnelTracker::healObjects(Real frames) -{ - iterateContained(healObject, &frames, FALSE); -} -#else -void TunnelTracker::healObjects() -{ - if (m_needsFullHealTimeUpdate) - { - updateFullHealTime(); - m_needsFullHealTimeUpdate = false; - } - - iterateContained(healObject, &m_framesForFullHeal, FALSE); -} -#endif - -// ------------------------------------------------------------------------ - // heal one object within the tunnel network system -void TunnelTracker::healObject( Object *obj, void *frames) -{ - - //get the number of frames to heal -#if RETAIL_COMPATIBLE_CRC || PRESERVE_TUNNEL_HEAL_STACKING - Real *framesForFullHeal = (Real*)frames; -#else - UnsignedInt* framesForFullHeal = (UnsignedInt*)frames; -#endif - - // setup the healing damageInfo structure with all but the amount - DamageInfo healInfo; - healInfo.in.m_damageType = DAMAGE_HEALING; - healInfo.in.m_deathType = DEATH_NONE; - //healInfo.in.m_sourceID = getObject()->getID(); - - // get body module of the thing to heal - BodyModuleInterface *body = obj->getBodyModule(); - - // if we've been in here long enough ... set our health to max - if( TheGameLogic->getFrame() - obj->getContainedByFrame() >= *framesForFullHeal ) - { - - // set the amount to max just to be sure we're at the top - healInfo.in.m_amount = body->getMaxHealth(); - - // set max health - body->attemptHealing( &healInfo ); - - } - else - { - // - // given the *whole* time it would take to heal this object, lets pretend that the - // object is at zero health ... and give it a sliver of health as if it were at 0 health - // and would be fully healed at 'framesForFullHeal' - // - healInfo.in.m_amount = body->getMaxHealth() / *framesForFullHeal; - - // do the healing - body->attemptHealing( &healInfo ); - - } -} - -void TunnelTracker::updateFullHealTime() -{ - UnsignedInt minFrames = ~0u; - - for (std::list::const_iterator it = m_tunnelIDs.begin(); it != m_tunnelIDs.end(); ++it) - { - const Object* tunnelObj = TheGameLogic->findObjectByID(*it); - if (!tunnelObj) - continue; - - const ContainModuleInterface* contain = tunnelObj->getContain(); - DEBUG_ASSERTCRASH(contain != nullptr, ("Contain module is null")); - - if (!contain->isTunnelContain()) - continue; - - const TunnelContain* tunnelContain = static_cast(contain); - const UnsignedInt framesForFullHeal = tunnelContain->getFullTimeForHeal(); - if (framesForFullHeal < minFrames) - minFrames = framesForFullHeal; - } - - m_framesForFullHeal = minFrames; -} - -// ------------------------------------------------------------------------------------------------ -/** CRC */ -// ------------------------------------------------------------------------------------------------ -void TunnelTracker::crc( Xfer *xfer ) -{ - -} - -// ------------------------------------------------------------------------------------------------ -/** Xfer method - * Version Info: - * 1: Initial version - * 2: TheSuperHackers @tweak Removed m_tunnelCount (should always be equal to m_tunnelIDs.size()) - */ -// ------------------------------------------------------------------------------------------------ -void TunnelTracker::xfer( Xfer *xfer ) -{ - - // version -#if RETAIL_COMPATIBLE_XFER_SAVE - XferVersion currentVersion = 1; -#else - XferVersion currentVersion = 2; -#endif - XferVersion version = currentVersion; - xfer->xferVersion( &version, currentVersion ); - - // tunnel object id list - xfer->xferSTLObjectIDList( &m_tunnelIDs ); - - // contain list count - xfer->xferInt( &m_containListSize ); - - // contain list data - ObjectID objectID; - if( xfer->getXferMode() == XFER_SAVE ) - { - ContainedItemsList::const_iterator it; - - for( it = m_containList.begin(); it != m_containList.end(); ++it ) - { - - objectID = (*it)->getID(); - xfer->xferObjectID( &objectID ); - - } - - } - else - { - - for( UnsignedShort i = 0; i < m_containListSize; ++i ) - { - - xfer->xferObjectID( &objectID ); - m_xferContainList.push_back( objectID ); - - } - - m_needsFullHealTimeUpdate = true; - } - -#if RETAIL_COMPATIBLE_CRC - if (version <= 1) - { - xfer->xferUnsignedInt(&m_tunnelCount); - } - else - { - if (xfer->getXferMode() == XFER_LOAD) - { - m_tunnelCount = m_tunnelIDs.size(); - } - } -#else - if (version <= 1) - { - UnsignedInt tunnelCount = m_tunnelIDs.size(); - xfer->xferUnsignedInt(&tunnelCount); - } -#endif - -} - -// ------------------------------------------------------------------------------------------------ -/** Load post process */ -// ------------------------------------------------------------------------------------------------ -void TunnelTracker::loadPostProcess() -{ - - // sanity, the contain list should be empty until we post process the id list - if( !m_containList.empty() ) - { - - DEBUG_CRASH(( "TunnelTracker::loadPostProcess - m_containList should be empty but is not" )); - throw SC_INVALID_DATA; - - } - - // translate each object ids on the xferContainList into real object pointers in the contain list - m_containListSize = 0; - m_heroUnitsContained = 0; - Object *obj; - std::list< ObjectID >::const_iterator it; - for( it = m_xferContainList.begin(); it != m_xferContainList.end(); ++it ) - { - - obj = TheGameLogic->findObjectByID( *it ); - if( obj == nullptr ) - { - - DEBUG_CRASH(( "TunnelTracker::loadPostProcess - Unable to find object ID '%d'", *it )); - throw SC_INVALID_DATA; - - } - - // push on the back of the contain list - addToContainList( obj ); - - // Crap. This is in OpenContain as a fix, but not here. - { - // remove object from its group (if any) - obj->leaveGroup(); - - // remove rider from partition manager - ThePartitionManager->unRegisterObject( obj ); - - // hide the drawable associated with rider - if( obj->getDrawable() ) - obj->getDrawable()->setDrawableHidden( true ); - - // remove object from pathfind map - if( TheAI ) - TheAI->pathfinder()->removeObjectFromPathfindMap( obj ); - - } - } - - // we're done with the xfer contain list now - m_xferContainList.clear(); - -} diff --git a/GeneralsMD/Code/GameEngine/CMakeLists.txt b/GeneralsMD/Code/GameEngine/CMakeLists.txt index fb3b718bf66..80ad2be24d1 100644 --- a/GeneralsMD/Code/GameEngine/CMakeLists.txt +++ b/GeneralsMD/Code/GameEngine/CMakeLists.txt @@ -1,6 +1,6 @@ set(GAMEENGINE_SRC # Include/Common/AcademyStats.h - Include/Common/ActionManager.h +# Include/Common/ActionManager.h # Include/Common/ArchiveFile.h # Include/Common/ArchiveFileSystem.h # Include/Common/AsciiString.h @@ -34,7 +34,7 @@ set(GAMEENGINE_SRC Include/Common/DrawModule.h # Include/Common/DynamicAudioEventInfo.h Include/Common/encrypt.h - Include/Common/Energy.h +# Include/Common/Energy.h # Include/Common/Errors.h # Include/Common/file.h # Include/Common/FileSystem.h @@ -53,7 +53,7 @@ set(GAMEENGINE_SRC # Include/Common/GameType.h Include/Common/Geometry.h Include/Common/GlobalData.h - Include/Common/Handicap.h +# Include/Common/Handicap.h Include/Common/IgnorePreferences.h # Include/Common/INI.h Include/Common/INIException.h @@ -69,11 +69,11 @@ set(GAMEENGINE_SRC # Include/Common/MessageStream.h # Include/Common/MiniLog.h # Include/Common/MiscAudio.h - Include/Common/MissionStats.h +# Include/Common/MissionStats.h Include/Common/ModelState.h Include/Common/Module.h Include/Common/ModuleFactory.h - Include/Common/Money.h +# Include/Common/Money.h Include/Common/MultiplayerSettings.h Include/Common/NameKeyGenerator.h # Include/Common/ObjectStatusTypes.h @@ -83,10 +83,10 @@ set(GAMEENGINE_SRC Include/Common/PartitionSolver.h Include/Common/PerfMetrics.h # Include/Common/PerfTimer.h - Include/Common/Player.h - Include/Common/PlayerList.h - Include/Common/PlayerTemplate.h - Include/Common/ProductionPrerequisite.h +# Include/Common/Player.h +# Include/Common/PlayerList.h +# Include/Common/PlayerTemplate.h +# Include/Common/ProductionPrerequisite.h Include/Common/QuickmatchPreferences.h Include/Common/QuotedPrintable.h # Include/Common/Radar.h @@ -95,32 +95,32 @@ set(GAMEENGINE_SRC Include/Common/Recorder.h # Include/Common/ReplaySimulation.h Include/Common/Registry.h - Include/Common/ResourceGatheringManager.h - Include/Common/Science.h +# Include/Common/ResourceGatheringManager.h +# Include/Common/Science.h Include/Common/ScopedMutex.h - Include/Common/ScoreKeeper.h +# Include/Common/ScoreKeeper.h # Include/Common/simpleplayer.h Include/Common/SkirmishBattleHonors.h Include/Common/SkirmishPreferences.h # Include/Common/Snapshot.h Include/Common/SparseMatchFinder.h - Include/Common/SpecialPower.h - Include/Common/SpecialPowerMaskType.h - Include/Common/SpecialPowerType.h +# Include/Common/SpecialPower.h +# Include/Common/SpecialPowerMaskType.h +# Include/Common/SpecialPowerType.h Include/Common/StackDump.h Include/Common/StateMachine.h Include/Common/StatsCollector.h # Include/Common/STLTypedefs.h # Include/Common/StreamingArchiveFile.h # Include/Common/SubsystemInterface.h - Include/Common/Team.h +# Include/Common/Team.h Include/Common/Terrain.h # Include/Common/TerrainTypes.h Include/Common/Thing.h Include/Common/ThingFactory.h Include/Common/ThingSort.h # Include/Common/ThingTemplate.h - Include/Common/TunnelTracker.h +# Include/Common/TunnelTracker.h # Include/Common/UnicodeString.h Include/Common/UnitTimings.h Include/Common/Upgrade.h @@ -605,21 +605,21 @@ set(GAMEENGINE_SRC Source/Common/Recorder.cpp # Source/Common/ReplaySimulation.cpp # Source/Common/RTS/AcademyStats.cpp - Source/Common/RTS/ActionManager.cpp - Source/Common/RTS/Energy.cpp - Source/Common/RTS/Handicap.cpp - Source/Common/RTS/MissionStats.cpp - Source/Common/RTS/Money.cpp - Source/Common/RTS/Player.cpp - Source/Common/RTS/PlayerList.cpp - Source/Common/RTS/PlayerTemplate.cpp - Source/Common/RTS/ProductionPrerequisite.cpp - Source/Common/RTS/ResourceGatheringManager.cpp - Source/Common/RTS/Science.cpp - Source/Common/RTS/ScoreKeeper.cpp - Source/Common/RTS/SpecialPower.cpp - Source/Common/RTS/Team.cpp - Source/Common/RTS/TunnelTracker.cpp +# Source/Common/RTS/ActionManager.cpp +# Source/Common/RTS/Energy.cpp +# Source/Common/RTS/Handicap.cpp +# Source/Common/RTS/MissionStats.cpp +# Source/Common/RTS/Money.cpp +# Source/Common/RTS/Player.cpp +# Source/Common/RTS/PlayerList.cpp +# Source/Common/RTS/PlayerTemplate.cpp +# Source/Common/RTS/ProductionPrerequisite.cpp +# Source/Common/RTS/ResourceGatheringManager.cpp +# Source/Common/RTS/Science.cpp +# Source/Common/RTS/ScoreKeeper.cpp +# Source/Common/RTS/SpecialPower.cpp +# Source/Common/RTS/Team.cpp +# Source/Common/RTS/TunnelTracker.cpp Source/Common/SkirmishBattleHonors.cpp Source/Common/StateMachine.cpp Source/Common/StatsCollector.cpp diff --git a/scripts/cpp/unify_move_files.py b/scripts/cpp/unify_move_files.py index 6517e02ec7e..00370ebf93e 100644 --- a/scripts/cpp/unify_move_files.py +++ b/scripts/cpp/unify_move_files.py @@ -761,6 +761,39 @@ def main(): #unify_file_lib(Game.ZEROHOUR, "Libraries/Source/WWVegas/WW3D2/vertmaterial.cpp", Game.CORE, "Libraries/Source/WWVegas/WW3D2/vertmaterial.cpp") #unify_file_lib(Game.ZEROHOUR, "Libraries/Source/WWVegas/WW3D2/vertmaterial.h", Game.CORE, "Libraries/Source/WWVegas/WW3D2/vertmaterial.h") + #unify_file(Game.ZEROHOUR, "GameEngine/Source/Common/RTS/ActionManager.cpp", Game.CORE, "GameEngine/Source/Common/RTS/ActionManager.cpp") + #unify_file(Game.ZEROHOUR, "GameEngine/Include/Common/ActionManager.h", Game.CORE, "GameEngine/Include/Common/ActionManager.h") + #unify_file(Game.ZEROHOUR, "GameEngine/Source/Common/RTS/Energy.cpp", Game.CORE, "GameEngine/Source/Common/RTS/Energy.cpp") + #unify_file(Game.ZEROHOUR, "GameEngine/Include/Common/Energy.h", Game.CORE, "GameEngine/Include/Common/Energy.h") + #unify_file(Game.ZEROHOUR, "GameEngine/Source/Common/RTS/Handicap.cpp", Game.CORE, "GameEngine/Source/Common/RTS/Handicap.cpp") + #unify_file(Game.ZEROHOUR, "GameEngine/Include/Common/Handicap.h", Game.CORE, "GameEngine/Include/Common/Handicap.h") + #unify_file(Game.ZEROHOUR, "GameEngine/Source/Common/RTS/MissionStats.cpp", Game.CORE, "GameEngine/Source/Common/RTS/MissionStats.cpp") + #unify_file(Game.ZEROHOUR, "GameEngine/Include/Common/MissionStats.h", Game.CORE, "GameEngine/Include/Common/MissionStats.h") + #unify_file(Game.ZEROHOUR, "GameEngine/Source/Common/RTS/Money.cpp", Game.CORE, "GameEngine/Source/Common/RTS/Money.cpp") + #unify_file(Game.ZEROHOUR, "GameEngine/Include/Common/Money.h", Game.CORE, "GameEngine/Include/Common/Money.h") + #unify_file(Game.ZEROHOUR, "GameEngine/Source/Common/RTS/Player.cpp", Game.CORE, "GameEngine/Source/Common/RTS/Player.cpp") + #unify_file(Game.ZEROHOUR, "GameEngine/Include/Common/Player.h", Game.CORE, "GameEngine/Include/Common/Player.h") + #unify_file(Game.ZEROHOUR, "GameEngine/Source/Common/RTS/PlayerList.cpp", Game.CORE, "GameEngine/Source/Common/RTS/PlayerList.cpp") + #unify_file(Game.ZEROHOUR, "GameEngine/Include/Common/PlayerList.h", Game.CORE, "GameEngine/Include/Common/PlayerList.h") + #unify_file(Game.ZEROHOUR, "GameEngine/Source/Common/RTS/PlayerTemplate.cpp", Game.CORE, "GameEngine/Source/Common/RTS/PlayerTemplate.cpp") + #unify_file(Game.ZEROHOUR, "GameEngine/Include/Common/PlayerTemplate.h", Game.CORE, "GameEngine/Include/Common/PlayerTemplate.h") + #unify_file(Game.ZEROHOUR, "GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp", Game.CORE, "GameEngine/Source/Common/RTS/ProductionPrerequisite.cpp") + #unify_file(Game.ZEROHOUR, "GameEngine/Include/Common/ProductionPrerequisite.h", Game.CORE, "GameEngine/Include/Common/ProductionPrerequisite.h") + #unify_file(Game.ZEROHOUR, "GameEngine/Source/Common/RTS/ResourceGatheringManager.cpp", Game.CORE, "GameEngine/Source/Common/RTS/ResourceGatheringManager.cpp") + #unify_file(Game.ZEROHOUR, "GameEngine/Include/Common/ResourceGatheringManager.h", Game.CORE, "GameEngine/Include/Common/ResourceGatheringManager.h") + #unify_file(Game.ZEROHOUR, "GameEngine/Source/Common/RTS/Science.cpp", Game.CORE, "GameEngine/Source/Common/RTS/Science.cpp") + #unify_file(Game.ZEROHOUR, "GameEngine/Include/Common/Science.h", Game.CORE, "GameEngine/Include/Common/Science.h") + #unify_file(Game.ZEROHOUR, "GameEngine/Source/Common/RTS/ScoreKeeper.cpp", Game.CORE, "GameEngine/Source/Common/RTS/ScoreKeeper.cpp") + #unify_file(Game.ZEROHOUR, "GameEngine/Include/Common/ScoreKeeper.h", Game.CORE, "GameEngine/Include/Common/ScoreKeeper.h") + #unify_file(Game.ZEROHOUR, "GameEngine/Source/Common/RTS/SpecialPower.cpp", Game.CORE, "GameEngine/Source/Common/RTS/SpecialPower.cpp") + #unify_file(Game.ZEROHOUR, "GameEngine/Include/Common/SpecialPower.h", Game.CORE, "GameEngine/Include/Common/SpecialPower.h") + #unify_file(Game.ZEROHOUR, "GameEngine/Source/Common/RTS/Team.cpp", Game.CORE, "GameEngine/Source/Common/RTS/Team.cpp") + #unify_file(Game.ZEROHOUR, "GameEngine/Include/Common/Team.h", Game.CORE, "GameEngine/Include/Common/Team.h") + #unify_file(Game.ZEROHOUR, "GameEngine/Source/Common/RTS/TunnelTracker.cpp", Game.CORE, "GameEngine/Source/Common/RTS/TunnelTracker.cpp") + #unify_file(Game.ZEROHOUR, "GameEngine/Include/Common/TunnelTracker.h", Game.CORE, "GameEngine/Include/Common/TunnelTracker.h") + #unify_file(Game.ZEROHOUR, "GameEngine/Include/Common/SpecialPowerType.h", Game.CORE, "GameEngine/Include/Common/SpecialPowerType.h") + #unify_file(Game.ZEROHOUR, "GameEngine/Include/Common/SpecialPowerMaskType.h", Game.CORE, "GameEngine/Include/Common/SpecialPowerMaskType.h") + return