Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
fix(gameengine): second pass over upstream bugs, 72 more fixed
Olcay Seygan4319c010379b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8de49b47f..eee1eae1f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -792,7 +792,44 @@ A third pass went through the generals' powers, promotions and unit abilities.- The camera stops following a unit the moment it goes stealthed or into the fog, instead of showing you where it went.- A broken map.ini, a damaged map cache in your user folder or a map name with forward slashes no longer crash the game or lose the map from the list; the cache is rebuilt.- A replay no longer crashes when it has no player from this machine, and a skirmish restarted from the menu records its replay with the slots you set up.-- Replays recorded before this version that have burning infantry, missiles, captured vehicles or cancelled production in them play back differently.+- The Laser and Superweapon generals' supply Chinooks crashed the game the moment their supply center finished. Changing their orders in the game data had left them with no way to fly.+- A skirmish computer player could crash the game while pulling a unit off one team for another.+- A map with its own sound effects no longer crashes or freezes the game some time after it has been played.+- Weapons that promote their shooter with the kill no longer write into a weapon that was already thrown away. Angry mobs were the usual victims.+- Loading a save of a map with its own map.ini no longer crashes.+- A Dragon Tank firing at a bunker on a hill hits it. Every missile fired uphill from a raised barrel used to be aimed twice and flew over the target.+- A Missile Defender grouped with Rangers keeps its laser lock after you give the group the flashbang.+- Units in guard mode no longer chase enemies they cannot see through the fog, and a Helix or Comanche no longer keeps its engine noise playing after it flies into the fog.+- Infantry can climb into a Helix that is guarding or attacking; it lands for them.+- A worker or dozer sent into a Tunnel Network stays inside instead of walking back out to the foundation it was headed for. Loaded workers stop building from inside, and a builder called off halfway stops the construction noise.+- A Bunker Buster or Neutron Shell on a tunnel's scaffold no longer hits everyone hiding in your tunnel network.+- Supply trucks move freely round a supply center with China mines around it.+- An Emergency Repair heals units an Ambulance or a Propaganda Tower is already working on.+- Your first power plant no longer finishes half the unit in the queue at once, and losing power no longer throws built progress away. The new rate applies from that moment on.+- Units kept inside a Tunnel Network or a garrison are put out and hurt one at a time, so a demolition rider's blast no longer lets the rest walk out unharmed.+- A hijacker killed on the frame he reached the tank no longer takes it, and Jarmen Kell no longer spends a snipe on a vehicle that has driven out of range.+- A Stinger Site killed or sold takes its soldiers with it.+- The Rebel Ambush drops its rebels on dry ground instead of into the water.+- A sniped Helix on the ground throws out its passengers the way every other transport does.+- A Comanche that hits the ground inside a second and a half still throws out its pilot.+- Helicopters flying to a pad that was destroyed stop, and a helicopter already on a pad ignores a second order to repair there. A Chinook unloading on a pad keeps being repaired.+- The starting command center no longer counts its power twice.+- A Battlemaster at the edge of a horde gets the horde bonus like the ones in the middle.+- A damaged plane only shows the repair cursor on an airfield with a free space.+- Composite Armor gives the same health whether it was bought before or after a promotion.+- The Spectre's machine gun keeps firing while the gunship's orbit swings past the edge of the map.+- Selling a building from a group, with a group hotkey pressed in the same moment, no longer sells tech buildings or captured civilian structures.+- The network lobby keeps answering joins and chat while the game is minimized, and a map transfer no longer stalls for two minutes on a preview picture from an ordinary paint program.+- The victory or defeat screen no longer waits thirty seconds when the last opponent had already left.+- A team you assign with Ctrl and a number selects the right units even when you press the number again before the game has caught up.+- Keys work after switching away from a window and back, and releasing Ctrl before a letter no longer fires that letter's plain hotkey.+- A save keeps the game speed it was made at, and its replay keeps its length.+- Bridges load when the game is switched away from while a map is loading.+- The minimap stays on in a replay when a mission widens the map's border.+- The water stops moving while the game is paused.+- A stealth unit that fires in plain sight no longer vanishes for a few frames before it shows up again.+- Revealing the fog at a waypoint in a mission reveals it for the right players.+- Replays recorded before this version that have burning infantry, missiles, captured vehicles, cancelled production, guard mode, tunnels or power plants in them play back differently.## The buildings nobody repairs, repair themselvesdiff --git a/GeneralsMD/Code/GameEngine/Include/Common/AudioEventRTS.h b/GeneralsMD/Code/GameEngine/Include/Common/AudioEventRTS.hindex 468de7862..08fdf0156 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/AudioEventRTS.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/AudioEventRTS.h@@ -147,7 +147,8 @@ public:void setPlayingAudioIndex( Int pai ) { m_playingAudioIndex = pai; };Bool getUninterruptable( ) const { return m_uninterruptable; }- void setUninterruptable( Bool uninterruptable ) { m_uninterruptable = uninterruptable; }+ void setUninterruptable( Bool uninterruptable ) { m_uninterruptable = uninterruptable; }+ void setSkipAttack( Bool skipAttack ) { m_skipAttack = skipAttack; } ///< start on the loop itself, for a loop picked up again mid-way// This will retrieve the appropriate position based on type.@@ -187,6 +188,7 @@ protected:Bool m_shouldFade; ///< This should fade in or out (if it is starting or stopping)Bool m_isLogicalAudio; ///< Should probably only be true for scripted soundsBool m_uninterruptable;+ Bool m_skipAttack;// Playing attributesReal m_pitchShift; ///< Pitch shift that should occur on this piece of audiodiff --git a/GeneralsMD/Code/GameEngine/Include/Common/GameState.h b/GeneralsMD/Code/GameEngine/Include/Common/GameState.hindex 2c07a5f04..1d08def9e 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GameState.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GameState.h@@ -111,6 +111,7 @@ public:UnicodeString description; // user description for save game fileSaveFileType saveFileType; // type of save file we're dealing withAsciiString missionMapName; // used for mission saves+ Int framesPerSecond; // game speed the match was playing at, 0 in saves older than that};diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Player.h b/GeneralsMD/Code/GameEngine/Include/Common/Player.hindex fd0df3f06..11a7b4d22 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/Player.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/Player.h@@ -830,6 +830,17 @@ public:Int getRankLevel() const { return m_rankLevel; }Int getSkillPointsLevelUp() const { return m_levelUp; }Int getSkillPointsLevelDown() const { return m_levelDown; }+ /// How far from this rank to the next, 0 to 100. A level a script disabled (-1 points) or two+ /// ranks a Rank.ini gave the same points leave no way on, and count as full; the bars used to+ /// divide by that difference.+ Int getRankProgressPercent() const+ {+ const Int span = m_levelUp - m_levelDown;+ if( span <= 0 )+ return 100;+ const Int progress = ( m_skillPoints - m_levelDown ) * 100 / span;+ return progress < 0 ? 0 : ( progress > 100 ? 100 : progress );+ }UnicodeString getGeneralName() const { return m_generalName; }void setGeneralName( UnicodeString name ){ m_generalName = name; }/// returns TRUE if rank level really changed.diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.hindex dea6993a1..b0c77f12e 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h@@ -1065,6 +1065,9 @@ public:return ( panel < 0 || panel >= CB_PANEL_COUNT ) ? 0.0f : m_panelSlide[ panel ];}+ /// post process step, after all commands and command sets are loaded - and again after a map.ini+ void postProcessCommands( void );+protected:/// place one window and its descendants inside 'panel'; see layoutPanelsvoid placeInPanel( GameWindow *win, Int panel,@@ -1111,9 +1114,6 @@ protected:/// show rally point at world location, a NULL location will hide any visible rally point markervoid showRallyPoint( const Coord3D *loc );- /// post process step, after all commands and command sets are loaded- void postProcessCommands( void );-// the following methods are for resetting data for vaious contextsvoid resetContainData( void ); /// reset container data we use to tie controls to objects IDs for containmentvoid resetBuildQueueData( void ); /// reset the build queue data we use to die queue entires to controldiff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Credits.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Credits.hindex e77ab5ebe..ae1e9a9e2 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/Credits.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Credits.h@@ -138,7 +138,8 @@ private:CreditsLineList m_displayedCreditLineList;- Int m_scrollRate; // in pixels+ Int m_scrollRate; // in pixels of an 800x600 screen+ Real m_scrollCarry; // the part of a pixel the last step did not move, at the real screen heightInt m_scrollRatePerFrames;Bool m_scrollDown; // if TRUE text will come from the top to the bottom if False, it will go from the bottom updiff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Drawable.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Drawable.hindex fa718eafd..a629ef304 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/Drawable.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Drawable.h@@ -197,7 +197,7 @@ public:UnsignedInt decayFrames = DEF_DECAY_FRAMES,UnsignedInt sustainAtPeak = DEF_SUSTAIN_FRAMES ); // ask MLorenzenvoid sustain(void) { m_envState = ENVELOPE_STATE_SUSTAIN; }- void release(void) { m_envState = ENVELOPE_STATE_DECAY; }+ void release(void);void rest(void) { m_envState = ENVELOPE_STATE_REST; } // goes away now!Bool isEffective() const { return m_affect; }const Vector3* getColor() const { return &m_currentColor; }diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/KeyDefs.h b/GeneralsMD/Code/GameEngine/Include/GameClient/KeyDefs.hindex 6dc472fa8..93fe012c8 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/KeyDefs.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/KeyDefs.h@@ -245,6 +245,7 @@ enumKEY_STATE_AUTOREPEAT = 0x0100, // Key is down due to autorepeat (only seen in conjunction with KEY_STATE_DOWN)KEY_STATE_CAPSLOCK = 0x0200, // Caps Lock key is on.KEY_STATE_SHIFT2 = 0x0400, // Alternate shift key is pressed (I think this is for foreign keyboards..)+ KEY_STATE_PRESSED_WITH_CTRL_ALT = 0x0800, // on a release only: the key went down with Ctrl or Alt held, whatever is held now// modifier combinations when left/right isn't a factorKEY_STATE_CONTROL = (KEY_STATE_LCONTROL | KEY_STATE_RCONTROL),diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/SelectionXlat.h b/GeneralsMD/Code/GameEngine/Include/GameClient/SelectionXlat.hindex d7272bb8c..000d6ee83 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/SelectionXlat.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/SelectionXlat.h@@ -31,6 +31,7 @@#define _H_SelectionXlat#include "GameClient/InGameUI.h"+#include "Common/Player.h" // NUM_HOTKEY_SQUADSclass ThingTemplate;@@ -61,6 +62,16 @@ private:SelectCountMap m_selectCountMap;+ // A team key's new members reach the logic a run-ahead after the press in a network game. A+ // select in between drew the squad the logic still held, while the logic, taking the two in+ // order, selected the new one: the screen and the orders went to different units. What each+ // key last sent and the frame it lands on, 0 for nothing on the way.+ std::vector<ObjectID> m_pendingSquad[ NUM_HOTKEY_SQUADS ];+ UnsignedInt m_pendingSquadLands[ NUM_HOTKEY_SQUADS ];++ Bool isSquadPending( Int group ) const;+ void selectHotkeySquad( Player *player, Int group, Bool ownOnly ); ///< what the logic will have in the squad by the time a select sent now lands+Bool selectFriends( Drawable *draw, GameMessage *createTeamMsg, Bool dragSelecting );Bool killThemKillThemAll( Drawable *draw, GameMessage *killThemAllMsg );@@ -76,7 +87,8 @@ public://changes the mode of drag selecting to it's oppositevoid setDragSelecting(Bool dragSelect);void setLeftMouseButton(Bool state);-+ void forgetPendingSquads(); ///< a match is over: what its team keys sent will never land+#if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE)Bool m_HandOfGodSelectionMode;Bool isHandOfGodSelectionMode( void) { return m_HandOfGodSelectionMode; };diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.hindex 6c7e5169d..ef8a958e0 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/AIUpdate.h@@ -775,6 +775,7 @@ public:inline Bool getRetryPath(void) {return m_retryPath;}inline Bool didPathfindFindNothing(void) const {return m_pathfindFoundNothing;}void queueForPathOrRetry(void); ///< join the pathfind queue, or try again shortly when it is full+ Int repathDebounceFrames(void) const {return (Int)(m_pathTimestamp + 3 - TheGameLogic->getFrame());} ///< what is left of the three frames a new path waits after the last oneUnsignedInt getQueueForPathFrame(void) const {return m_queueForPathFrame;} ///< nonzero while a too-quick path request is held backinline void setAllowedToChase( Bool allow ) { m_allowedToChase = allow; }diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/BattleBusSlowDeathBehavior.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/BattleBusSlowDeathBehavior.hindex f553de09a..271316f01 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/BattleBusSlowDeathBehavior.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/BattleBusSlowDeathBehavior.h@@ -78,6 +78,7 @@ public:// slow death methodsvirtual void onDie( const DamageInfo *damageInfo );virtual void beginSlowDeath( const DamageInfo *damageInfo );+ virtual Bool canBeginSecondLife() const { return !m_isRealDeath; }virtual UpdateSleepTime update( void );protected:diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ProductionUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ProductionUpdate.hindex 00563fee6..2bf3183cc 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ProductionUpdate.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/ProductionUpdate.h@@ -105,6 +105,7 @@ protected:ProductionID m_productionID; ///< our very own production ID!Real m_percentComplete; ///< percent our construction is completeInt m_framesUnderConstruction; ///< counter for how many frames we've been under construction (incremented once per update)+ Int m_totalProductionFrames; ///< the build time m_framesUnderConstruction was last measured againstInt m_productionQuantityTotal; ///< it is now possible to construct multiple units simultaneously.Int m_productionQuantityProduced; ///< And we need to allow pausing within an entry, so we keep track of number of sub-successesExitDoorType m_exitDoor;diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SlowDeathBehavior.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SlowDeathBehavior.hindex fa83c4617..bc4b2d07b 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SlowDeathBehavior.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/SlowDeathBehavior.h@@ -119,6 +119,7 @@ public:virtual void beginSlowDeath( const DamageInfo *damageInfo ) = 0;virtual Int getProbabilityModifier( const DamageInfo *damageInfo ) const = 0;virtual Bool isDieApplicable(const DamageInfo *damageInfo) const = 0;+ virtual Bool canBeginSecondLife() const = 0; ///< can this module turn an UndeadBody's first death into its second life};//-------------------------------------------------------------------------------------------------@@ -154,6 +155,7 @@ public:virtual void beginSlowDeath( const DamageInfo *damageInfo );virtual Int getProbabilityModifier( const DamageInfo *damageInfo ) const;virtual Bool isDieApplicable(const DamageInfo *damageInfo) const { return getSlowDeathBehaviorModuleData()->m_dieMuxData.isDieApplicable(getObject(), damageInfo); }+ virtual Bool canBeginSecondLife() const { return FALSE; }protected:diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/StealthUpdate.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/StealthUpdate.hindex 20194d5a2..23e882c48 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/StealthUpdate.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Module/StealthUpdate.h@@ -131,6 +131,8 @@ public:Int getDisguisedPlayerIndex() const { return m_disguiseAsPlayerIndex; }const ThingTemplate *getDisguisedTemplate() { return m_disguiseAsTemplate; }void markAsDetected( UnsignedInt numFrames = 0 );+ void keepDetected( UnsignedInt numFrames ); ///< extend the detection only: no disguise loss, no wake-ups+void disguiseAsObject( const Object *target ); //wrapper function for ease.Real getFriendlyOpacity() const;UnsignedInt getStealthDelay() const { return getStealthUpdateModuleData()->m_stealthDelay; }diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.hindex f0ffbc4c2..5f3a9a9d1 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Object.h@@ -523,7 +523,8 @@ public:void setCommandSetStringOverride( AsciiString newCommandSetString ) { m_commandSetStringOverride = newCommandSetString; }/// People are faking their commandsets, and, Surprise!, they are authoritative. Challenge everything.- Bool Object::canProduceUpgrade( const UpgradeTemplate *upgrade );+ Bool Object::canProduceUpgrade( const UpgradeTemplate *upgrade );+ Bool canSwitchToWeapon( WeaponSlotType weaponSlot ) const; ///< does our command set hold a button that switches to this slot// Weapons & Damage -------------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.hindex 95d06baa2..a63812e7b 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/Weapon.h@@ -822,7 +822,7 @@ private:OK to swap an Object's Weapon out at any given time.)*///--------------------------------------------------------------------------------------------------class WeaponStore : public SubsystemInterface+class WeaponStore : public SubsystemInterface, public Snapshot{friend class WeaponTemplate;@@ -848,6 +848,9 @@ public:return newInstance(Weapon)(tmpl, wslot); // my, that was easy}+ // frees a Weapon at the end of this logic frame, for one that may still be firing on the stack+ void deleteWeaponLater( Weapon *weapon ) { m_weaponsToDelete.push_back( weapon ); }+void createAndFireTempWeapon(const WeaponTemplate* w, const Object *source, const Coord3D* pos);void createAndFireTempWeapon(const WeaponTemplate* w, const Object *source, Object *target);@@ -863,9 +866,17 @@ protected:WeaponTemplate *newOverride( WeaponTemplate *weaponTemplate );void deleteAllDelayedDamage();+ void deleteWeaponsNow();void resetWeaponTemplates( void );void setDelayedDamage(const WeaponTemplate *weapon, const Coord3D* pos, UnsignedInt whichFrame, ObjectID sourceID, ObjectID victimID, const WeaponBonus& bonus);+ // Snapshot: the hits each weapon's historic bonus is counting and the delayed damage still in+ // flight, both keyed by weapon name. A save lost both, so an Inferno bonus half counted and a+ // tank shell in the air were gone after a load.+ virtual void crc( Xfer *xfer ) { }+ virtual void xfer( Xfer *xfer );+ virtual void loadPostProcess( void ) { }+private:/**@@ -892,6 +903,7 @@ private:typedef std::hash_map<NameKeyType, WeaponTemplate*, rts::hash<NameKeyType>, rts::equal_to<NameKeyType> > WeaponTemplateMap;WeaponTemplateMap m_weaponTemplateHashMap;std::list<WeaponDelayedDamageInfo> m_weaponDDI;+ std::vector<Weapon*> m_weaponsToDelete; ///< from deleteWeaponLater, freed by the next update or reset; nothing in it is game state};// EXTERNALS //////////////////////////////////////////////////////////////////////////////////////diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Audio/AudioEventRTS.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Audio/AudioEventRTS.cppindex 0fcf2db04..7b761834e 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/Audio/AudioEventRTS.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/Audio/AudioEventRTS.cpp@@ -82,7 +82,8 @@ AudioEventRTS::AudioEventRTS()m_allCount(0),m_playerIndex(-1),m_delay(0.0f),- m_uninterruptable(FALSE)+ m_uninterruptable(FALSE),+ m_skipAttack(FALSE){m_attackName.clear();m_decayName.clear();@@ -109,7 +110,8 @@ AudioEventRTS::AudioEventRTS( const AsciiString& eventName )m_allCount(0),m_playerIndex(-1),m_delay(0.0f),- m_uninterruptable(FALSE)+ m_uninterruptable(FALSE),+ m_skipAttack(FALSE){m_attackName.clear();m_decayName.clear();@@ -137,7 +139,8 @@ AudioEventRTS::AudioEventRTS( const AsciiString& eventName, ObjectID ownerID )m_allCount(0),m_playerIndex(-1),m_delay(0.0f),- m_uninterruptable(FALSE)+ m_uninterruptable(FALSE),+ m_skipAttack(FALSE){m_attackName.clear();m_decayName.clear();@@ -173,7 +176,8 @@ AudioEventRTS::AudioEventRTS( const AsciiString& eventName, DrawableID drawableIm_allCount(0),m_playerIndex(-1),m_delay(0.0f),- m_uninterruptable(FALSE)+ m_uninterruptable(FALSE),+ m_skipAttack(FALSE){m_attackName.clear();m_decayName.clear();@@ -208,7 +212,8 @@ AudioEventRTS::AudioEventRTS( const AsciiString& eventName, const Coord3D *positm_allCount(0),m_playerIndex(-1),m_delay(0.0f),- m_uninterruptable(FALSE)+ m_uninterruptable(FALSE),+ m_skipAttack(FALSE){m_positionOfAudio.set( positionOfAudio );m_attackName.clear();@@ -240,6 +245,7 @@ AudioEventRTS::AudioEventRTS( const AudioEventRTS& right )m_decayName = right.m_decayName;m_portionToPlayNext = right.m_portionToPlayNext;m_uninterruptable = right.m_uninterruptable;+ m_skipAttack = right.m_skipAttack;if( m_ownerType == OT_Positional || m_ownerType == OT_Dead ){@@ -281,6 +287,7 @@ AudioEventRTS& AudioEventRTS::operator=( const AudioEventRTS& right )m_decayName = right.m_decayName;m_portionToPlayNext = right.m_portionToPlayNext;m_uninterruptable = right.m_uninterruptable;+ m_skipAttack = right.m_skipAttack;if( m_ownerType == OT_Positional || m_ownerType == OT_Dead ){@@ -390,7 +397,7 @@ void AudioEventRTS::generatePlayInfo( void )m_portionToPlayNext = PP_Attack;Int attackSize = m_eventInfo->m_attackSounds.size();- if (attackSize > 0) {+ if (attackSize > 0 && !m_skipAttack) {m_attackName = generateFilenamePrefix(m_eventInfo->m_soundType, false);// needs to be logic because it needs to be the same on all systems.Int attackToPlay;diff --git a/GeneralsMD/Code/GameEngine/Source/Common/INI/INICommandButton.cpp b/GeneralsMD/Code/GameEngine/Source/Common/INI/INICommandButton.cppindex cf2117573..bed2a8384 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/INI/INICommandButton.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/INI/INICommandButton.cpp@@ -77,6 +77,11 @@ void ControlBar::parseCommandButtonDefinition( INI *ini )// parse the ini definitionini->initFromINI( button, button->getFieldParse() );++ // ControlBar::postProcessCommands looks the images up once, at startup, and a map.ini is read at+ // map load, long after: a button it adds or re-images drew empty. Look that one up now.+ if( ini->getLoadType() == INI_LOAD_CREATE_OVERRIDES )+ button->cacheButtonImage();//Make sure buttons with special power templates also have the appropriate option set.diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cppindex 8db656569..1f6ba5c31 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/ActionManager.cpp@@ -285,6 +285,22 @@ Bool ActionManager::canGetRepairedAt( const Object *obj, const Object *repairDesif( !obj->isAboveTerrain() ||repairDest->isKindOf( KINDOF_FS_AIRFIELD ) == FALSE )return FALSE;++ // A plane lands on a parking space, its own or a free one; helicopters use the helipad. With+ // every space held by other planes the cursor still offered the landing, and the plane never+ // came down (upstream #152). canEnterObject asks the same of a plane coming in to rearm.+ if( !obj->isKindOf( KINDOF_PRODUCED_AT_HELIPAD ) )+ {+ Bool parking = FALSE;+ for( BehaviorModule** i = repairDest->getBehaviorModules(); *i && !parking; ++i )+ {+ ParkingPlaceBehaviorInterface* pp = (*i)->getParkingPlaceBehaviorInterface();+ if( pp != NULL )+ parking = pp->hasReservedSpace( obj->getID() ) || pp->hasAvailableSpaceFor( obj->getTemplate() );+ }+ if( !parking )+ return FALSE;+ }}else{diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cppindex d56efe412..5b317c2c7 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Team.cpp@@ -2399,7 +2399,9 @@ Object *Team::tryToRecruit(const ThingTemplate *tTemplate, const Coord3D *teamHoif (!teamIsRecruitable) {continue;}- if (obj->getAIUpdateInterface() && !obj->getAIUpdateInterface()->isRecruitable()) {+ // a recruit is sent home or told to stop the moment it joins, so one with no AI to take the+ // order cannot be recruited: AIPlayer::queueUnits read the missing AI and crashed+ if (!obj->getAIUpdateInterface() || !obj->getAIUpdateInterface()->isRecruitable()) {continue; // can't recruit this unit.}if( obj->isDisabledByType( DISABLED_HELD ) )diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cppindex dcbdce42d..271d9e542 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/Recorder.cpp@@ -1115,6 +1115,7 @@ Bool RecorderClass::playbackFile(AsciiString filename)m_crcInfo->skipFirstCRC();}+ m_nextFrame = 0; // the last playback may have left -1 here, and readNextFrame reads forward from itreadNextFrame();// send a message to the logic for a new game@@ -1320,9 +1321,22 @@ AsciiString RecorderClass::readAsciiString() {* is stopped and the next frame is said to be -1.*/void RecorderClass::readNextFrame() {+ const UnsignedInt lastFrame = m_nextFrame;Int retcode = fread(&m_nextFrame, sizeof(m_nextFrame), 1, m_file);- if (retcode != 1) {- DEBUG_LOG(("RecorderClass::readNextFrame - fread failed on frame %d\n", TheGameLogic->getFrame()));+ //+ // Commands are written in frame order and none after the duration the header is closed with, so a+ // frame behind the last one, or past that end, is a damaged file. Playback used to wait for that+ // frame, which never comes back or comes after the game is over, and a headless run never ended.+ // A header left at 0 is a game that never closed its file, and has no end to hold the frame to.+ //+ const Bool damaged = retcode == 1 && ( m_nextFrame < lastFrame ||+ ( m_playbackFrameDuration != 0 && m_nextFrame > m_playbackFrameDuration ) );+ if (retcode != 1 || damaged) {+ if (damaged)+ DEBUG_LOG(("RecorderClass::readNextFrame - next command on frame %u after one on frame %u, replay ends on frame %u: file is damaged\n",+ m_nextFrame, lastFrame, m_playbackFrameDuration));+ else+ DEBUG_LOG(("RecorderClass::readNextFrame - fread failed on frame %d\n", TheGameLogic->getFrame()));m_nextFrame = -1;stopPlayback();}diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/BuildAssistant.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/BuildAssistant.cppindex 5060c1023..727016d01 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/BuildAssistant.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/BuildAssistant.cpp@@ -727,6 +727,8 @@ LegalBuildCode BuildAssistant::isLocationClearOfObjects( const Coord3D *worldPos{if( them->testStatus( OBJECT_STATUS_IS_USING_ABILITY ) || them->getAI() && them->getAI()->isBusy() ){+ // marked like every other refusal below, or the placement goes red with nothing showing why+ TheTerrainVisual->addFactionBib( them, TRUE );return LBC_OBJECTS_IN_THE_WAY;}}@@ -770,6 +772,25 @@ LegalBuildCode BuildAssistant::isLocationClearOfObjects( const Coord3D *worldPosreturn LBC_GENERIC_FAILURE;}+ //+ // Nor can a thing with no AI to tell it to move, and moveObjectsForConstruction turns a+ // human's order down for one - after the trees in the footprint are already cleared and the+ // other units already sent away, with no money taken and nothing placed. Most train cars are+ // such a thing. Say so here, where the ghost goes red. The AI builds over them regardless+ // (buildObjectNow lets it), so its placement is left as it was.+ //+ if( builderObject && !onlyCheckEnemies &&+ builderObject->getControllingPlayer()->getPlayerType() == PLAYER_HUMAN &&+ !them->isKindOf( KINDOF_ALWAYS_SELECTABLE ) && them->getAIUpdateInterface() == NULL )+ {+ if( feedbackWithFailure )+ {+ TheTerrainVisual->addFactionBib( them, TRUE );+ return LBC_OBJECTS_IN_THE_WAY;+ }+ return LBC_GENERIC_FAILURE;+ }+//// if this is an enemy object of the builder object (and therefore the thing// that will be constructed) we can't build here@@ -1708,14 +1729,18 @@ void BuildAssistant::sellObject( Object *obj )// unfortunately, structures don't keep list of mines they own, so we must do// this the hard way :-( [fortunately, this doens't happen very often, so this// is probably an acceptable, if icky, solution.] (srj)- for (Object* mine = TheGameLogic->getFirstObject(); mine; mine = mine->getNextObject())+ // The same walk takes the soldiers of a structure whose spawns are its weapons (the Stinger+ // Site): the site stopped shooting above, but its soldiers fired on until the sale finished, a+ // way to keep damaging an attacker while getting the money back.+ const Bool spawnsAreWeapons = obj->isKindOf(KINDOF_SPAWNS_ARE_THE_WEAPONS);+ for (Object* owned = TheGameLogic->getFirstObject(); owned; owned = owned->getNextObject()){- if (mine->isKindOf(KINDOF_MINE))+ if (owned->getProducerID() != obj->getID())+ continue;++ if (owned->isKindOf(KINDOF_MINE) || spawnsAreWeapons){- if (mine->getProducerID() == obj->getID())- {- TheGameLogic->destroyObject(mine);- }+ TheGameLogic->destroyObject(owned);}}diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cppindex ad1db1cc4..47d3dd8f4 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/Debug.cpp@@ -841,9 +841,12 @@ void ReleaseCrash(const char *reason)// ::MessageBox(NULL, "You have encountered a serious error. Serious errors can be caused by many things including viruses, overheated hardware and hardware that does not meet the minimum specifications for the game. Please visit the forums at www.generals.ea.com for suggested courses of action or consult your manual for Technical Support contact information.", "Technical Difficulties...", MB_OK|MB_TASKMODAL|MB_ICONERROR);// crash error message changed again 8/22/03 M Lorenzen... made this message box modal to the system so it will appear on top of any task-modal windows, splash-screen, etc.- ::MessageBox(NULL, "You have encountered a serious error. Serious errors can be caused by many things including viruses, overheated hardware and hardware that does not meet the minimum specifications for the game. Please visit the forums at www.generals.ea.com for suggested courses of action or consult your manual for Technical Support contact information.",- "Technical Difficulties...",- MB_OK|MB_SYSTEMMODAL|MB_ICONERROR);+// The 2003 text sent the player to forums at generals.ea.com that no longer exist, and never said+// that a report had just been written or where. Name the file instead.+ char buff[ 2 * _MAX_PATH ];+ _snprintf(buff, ARRAY_SIZE(buff), "You have encountered a serious error and the game has to close.\n\nA crash report was written to:\n%s\n\nPlease include that file when you report the problem.", curbuf);+ buff[ARRAY_SIZE(buff) - 1] = 0;+ ::MessageBox(NULL, buff, "Technical Difficulties...", MB_OK|MB_SYSTEMMODAL|MB_ICONERROR);#endifdiff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cppindex 9a6b5755e..01cac9494 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp@@ -39,6 +39,7 @@#include "Common/PlayerList.h"#include "Common/RandomValue.h"#include "Common/Radar.h"+#include "Common/Recorder.h"#include "Common/Team.h"#include "Common/WellKnownKeys.h"#include "Common/XferLoad.h"@@ -58,6 +59,7 @@#include "GameLogic/ScriptEngine.h"#include "GameLogic/SidesList.h"#include "GameLogic/TerrainLogic.h"+#include "GameLogic/Weapon.h"#ifdef _INTERNAL// for occasional debugging...@@ -93,6 +95,7 @@ SaveGameInfo::SaveGameInfo( void )date.year = 0;missionNumber = 0;saveFileType = SAVE_FILE_TYPE_NORMAL;+ framesPerSecond = 0;} // end SaveGameInfo@@ -322,7 +325,8 @@ void GameState::init( void )addSnapshotBlock( "CHUNK_TeamFactory", TheTeamFactory, SNAPSHOT_SAVELOAD );addSnapshotBlock( "CHUNK_Players", ThePlayerList, SNAPSHOT_SAVELOAD );addSnapshotBlock( "CHUNK_GameLogic", TheGameLogic, SNAPSHOT_SAVELOAD );- addSnapshotBlock( "CHUNK_Radar", TheRadar, SNAPSHOT_SAVELOAD );+ addSnapshotBlock( "CHUNK_WeaponStore", TheWeaponStore, SNAPSHOT_SAVELOAD ); // absent from older saves, which load without it+ addSnapshotBlock( "CHUNK_Radar", TheRadar, SNAPSHOT_SAVELOAD );addSnapshotBlock( "CHUNK_ScriptEngine", TheScriptEngine, SNAPSHOT_SAVELOAD );addSnapshotBlock( "CHUNK_SidesList", TheSidesList, SNAPSHOT_SAVELOAD );addSnapshotBlock( "CHUNK_TacticalView", TheTacticalView, SNAPSHOT_SAVELOAD );@@ -725,6 +729,11 @@ SaveCode GameState::loadGame( AvailableGameInfo gameInfo )XferLoad xferLoad;xferLoad.open( filepath );+ // A match still recording ends here, before the engine reset closes its file with no length+ // written into the header.+ if( TheRecorder->getMode() == RECORDERMODETYPE_RECORD )+ TheRecorder->stopRecording();+// clear out the game engineTheGameEngine->reset();@@ -784,6 +793,11 @@ SaveCode GameState::loadGame( AvailableGameInfo gameInfo )} // end if+ // A loaded match played at the default 30 whatever speed it was saved at: the reset during the+ // load puts the default back, and nothing kept the speed. A mission save starts its map afresh.+ if( getSaveGameInfo()->saveFileType != SAVE_FILE_TYPE_MISSION && getSaveGameInfo()->framesPerSecond > 0 )+ TheGameEngine->setFramesPerSecondLimit( getSaveGameInfo()->framesPerSecond );+//// when loading a mission save, we want to do as much normal loading stuff as we// can cause we don't have any real save game data to load other than the@@ -1614,13 +1628,22 @@ void GameState::xfer( Xfer *xfer ){// version- XferVersion currentVersion = 2;+ XferVersion currentVersion = 3;XferVersion version = currentVersion;xfer->xferVersion( &version, currentVersion );// get structure for our current game infoSaveGameInfo *saveGameInfo = getSaveGameInfo();+ // version 3: the game speed, read back by loadGame. It goes first because the rest of this+ // block ends in branches.+ if( xfer->getXferMode() == XFER_SAVE )+ saveGameInfo->framesPerSecond = TheGameEngine->getFramesPerSecondLimit();+ else+ saveGameInfo->framesPerSecond = 0;+ if( version >= 3 )+ xfer->xferInt( &saveGameInfo->framesPerSecond );+// version 2if( version >= 2 ){diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Thing/ModuleFactory.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Thing/ModuleFactory.cppindex 2551e42d2..13bb8c321 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/Thing/ModuleFactory.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/Thing/ModuleFactory.cpp@@ -209,7 +209,6 @@#include "GameLogic/Module/UnpauseSpecialPowerUpgrade.h"#include "GameLogic/Module/WeaponBonusUpgrade.h"#include "GameLogic/Module/WeaponSetUpgrade.h"-#include "GameLogic/Module/WeaponBonusUpgrade.h"#include "GameLogic/Module/CostModifierUpgrade.h"#include "GameLogic/Module/ExperienceScalarUpgrade.h"#include "GameLogic/Module/MaxHealthUpgrade.h"@@ -493,7 +492,6 @@ void ModuleFactory::init( void )addModule( UnpauseSpecialPowerUpgrade );addModule( WeaponBonusUpgrade );addModule( WeaponSetUpgrade );- addModule( WeaponBonusUpgrade );addModule( ExperienceScalarUpgrade );addModule( MaxHealthUpgrade );diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingTemplate.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingTemplate.cppindex 272b97ee7..fb177347d 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingTemplate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/Thing/ThingTemplate.cpp@@ -791,6 +791,12 @@ void ThingTemplate::parseReplaceModule(INI *ini, void *instance, void *store, coself->m_moduleParsingMode = MODULEPARSE_ADD_REMOVE_REPLACE;+ // The object's Locomotor lines are stored in its AI module's data, so a replaced AI module takes+ // them along: Lazr_AmericaVehicleChinook's replaced ChinookAIUpdate left it no locomotor, and the+ // first move order it got off the pad read a null one.+ const AIUpdateModuleData *aiBefore = self->friend_getAIModuleInfo();+ const LocomotorTemplateMap locomotorsBefore = aiBefore ? aiBefore->m_locomotorTemplates : LocomotorTemplateMap();+const char *modToRemove = ini->getNextToken();AsciiString removedModuleName;Bool removed = self->removeModuleInfo(modToRemove, removedModuleName);@@ -801,9 +807,15 @@ void ThingTemplate::parseReplaceModule(INI *ini, void *instance, void *store, cothrow INI_INVALID_DATA;}+ const Bool replacesAIModule = aiBefore != NULL && self->friend_getAIModuleInfo() == NULL;+self->m_moduleBeingReplacedName = removedModuleName;self->m_moduleBeingReplacedTag = modToRemove;ini->initFromINI(self, self->getFieldParse());++ AIUpdateModuleData *aiAfter = self->friend_getAIModuleInfo();+ if (replacesAIModule && aiAfter != NULL && aiAfter->m_locomotorTemplates.empty())+ aiAfter->m_locomotorTemplates = locomotorsBefore;self->m_moduleBeingReplacedName.clear();self->m_moduleBeingReplacedTag.clear();diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Credits.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Credits.cppindex 7dd91e402..10d2c4f13 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/Credits.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Credits.cpp@@ -126,6 +126,7 @@ CreditsLine::~CreditsLine()CreditsManager::CreditsManager(void){m_scrollRate = 1; // in pixels+ m_scrollCarry = 0.0f;m_scrollRatePerFrames = 1;m_scrollDown = TRUE; // if TRUE text will come from the top to the bottom if False, it will go from the bottom upm_framesSinceStarted = 0;@@ -183,6 +184,7 @@ void CreditsManager::reset( void )m_isFinished = FALSE;m_creditLineListIt = m_creditLineList.begin();m_framesSinceStarted = 0;+ m_scrollCarry = 0.0f;}@@ -194,7 +196,14 @@ void CreditsManager::update( void )if(m_framesSinceStarted%m_scrollRatePerFrames != 0)return;-++ // ScrollRate is in 800x600 pixels. The lines are set in fonts that grow with the screen, so a+ // step of the same pixel count took minutes longer at 1600x1200; the step grows with the fonts.+ const Int FONT_SCALE_PROBE = 1000;+ const Real fontScale = (Real)TheGlobalLanguageData->adjustFontSize( FONT_SCALE_PROBE ) / FONT_SCALE_PROBE;+ const Real scrollStep = m_scrollRate * fontScale + m_scrollCarry;+ const Int scrollPixels = (Int)scrollStep;+ m_scrollCarry = scrollStep - scrollPixels;Int y = 0;Int yTest = 0;@@ -208,7 +217,7 @@ void CreditsManager::update( void )while (drawIt != m_displayedCreditLineList.end()){CreditsLine *cLine = *drawIt;- y = cLine->m_pos.y = cLine->m_pos.y + (m_scrollRate * directionMultiplyer);+ y = cLine->m_pos.y = cLine->m_pos.y + (scrollPixels * directionMultiplyer);lastHeight = cLine->m_height;yTest = y + ((lastHeight + CREDIT_SPACE_OFFSET) * offsetEndMultiplyer);if(((m_scrollDown && (yTest > end)) || (!m_scrollDown && (yTest < end))))diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cppindex e53826332..260be7941 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp@@ -6215,6 +6215,19 @@ void TintEnvelope::setDecayFrames( UnsignedInt frames )m_decayRate.Scale( Vector3(recipFrames, recipFrames, recipFrames) );}+//-------------------------------------------------------------------------------------------------+void TintEnvelope::release(void)+{+ /* play() aims the decay at the peak it was given, which is only right when the tint got there.+ An EMP running out under a Frenzy starts the frenzy red from the disabled grey, and a frenzy+ that ends before that attack finishes decayed the grey along the red: away from zero, into a+ cyan that never met the rest test. Decay from the colour we are at, at the same pace. */+ const Real peakLength = m_peakColor.Length();+ if (peakLength > FADE_RATE_EPSILON)+ m_decayRate = m_currentColor * ( -m_decayRate.Length() / peakLength );+ m_envState = ENVELOPE_STATE_DECAY;+}+//-------------------------------------------------------------------------------------------------void TintEnvelope::update(void){diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cppindex 928418b64..7d834bb78 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp@@ -794,9 +794,7 @@ void ControlBar::populatePurchaseScience( Player* player )win = TheWindowManager->winGetWindowFromId( m_contextParent[ CP_PURCHASE_SCIENCE ], key_progressBarExperience );if(win){- Int progress;- progress = ((player->getSkillPoints() - player->getSkillPointsLevelDown()) * 100) /(player->getSkillPointsLevelUp() - player->getSkillPointsLevelDown());- GadgetProgressBarSetProgress(win, progress);+ GadgetProgressBarSetProgress(win, player->getRankProgressPercent());}win = TheWindowManager->winGetWindowFromId( m_contextParent[ CP_PURCHASE_SCIENCE ], TheNameKeyGenerator->nameToKey( "GeneralsExpPoints.wnd:StaticTextTitle" ) );@@ -855,11 +853,9 @@ void ControlBar::updateContextPurchaseScience( void )win = TheWindowManager->winGetWindowFromId( m_contextParent[ CP_PURCHASE_SCIENCE ], key_progressBarExperience );if(win){- Int progress;- progress = ((player->getSkillPoints() - player->getSkillPointsLevelDown()) * 100) /(player->getSkillPointsLevelUp() - player->getSkillPointsLevelDown());- GadgetProgressBarSetProgress(win, progress);+ GadgetProgressBarSetProgress(win, player->getRankProgressPercent());}-+// win = TheWindowManager->winGetWindowFromId( m_contextParent[ CP_PURCHASE_SCIENCE ], TheNameKeyGenerator->nameToKey( "ControlBar.wnd:TextEntryGeneralName" ) );// if(win)// {@@ -5026,9 +5022,11 @@ void CommandButton::cacheButtonImage()//-------------------------------------------------------------------------------------------------void ControlBar::postProcessCommands( void ){- for ( CommandButton *button = m_commandButtons; button; button = button->friend_getNext() )+ for ( CommandButton *button = m_commandButtons; button; button = button->friend_getNext() ){- button->cacheButtonImage();+ // a map.ini's edit of a button is an override hanging off it, not a button in this list+ for ( Overridable *o = button; o; o = o->friend_getNextOverride() )+ static_cast<CommandButton *>( o )->cacheButtonImage();}}diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cppindex b036156c0..e0ff370bb 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanGameOptionsMenu.cpp@@ -1141,7 +1141,8 @@ void updateGameOptions( void )if (comboBoxSuperweapons)UpdateSuperweaponComboBox( comboBoxSuperweapons, theGame, TheLAN->AmIHost() );Int itemCount = GadgetComboBoxGetLength(comboBoxStartingCash);- for ( Int index = 0; index < itemCount; index++ )+ Int index;+ for ( index = 0; index < itemCount; index++ ){Int value = (Int)GadgetComboBoxGetItemData(comboBoxStartingCash, index);if ( value == theGame->getStartingCash().countMoney() )@@ -1151,7 +1152,10 @@ void updateGameOptions( void )}}- DEBUG_ASSERTCRASH( index < itemCount, ("Could not find new starting cash amount %d in list", theGame->getStartingCash().countMoney() ) );+ // the preferences set the cash after the box was filled, so an amount the list does not carry+ // (StartingCash in the player's INI) was in force but never shown+ if ( index == itemCount )+ PopulateStartingCashComboBox( comboBoxStartingCash, theGame );if (comboBoxPeaceTime)UpdatePeaceTimeComboBox( comboBoxPeaceTime, theGame, TheLAN->AmIHost() );diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cppindex aa9890241..9298591d5 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishGameOptionsMenu.cpp@@ -1314,7 +1314,8 @@ void updateSkirmishGameOptions( void )if ( comboBoxTechRespawn )UpdateTechRespawnComboBox( comboBoxTechRespawn, TheSkirmishGameInfo, TRUE );Int itemCount = GadgetComboBoxGetLength(comboBoxStartingCash);- for ( Int index = 0; index < itemCount; index++ )+ Int index;+ for ( index = 0; index < itemCount; index++ ){Int value = (Int)GadgetComboBoxGetItemData(comboBoxStartingCash, index);if ( value == TheSkirmishGameInfo->getStartingCash().countMoney() )@@ -1323,8 +1324,10 @@ void updateSkirmishGameOptions( void )break;}}-- DEBUG_ASSERTCRASH( index < itemCount, ("Could not find new starting cash amount %d in list", TheSkirmishGameInfo->getStartingCash().countMoney() ) );++ // see LanGameOptionsMenu: an amount from the player's INI that the list does not carry+ if ( index == itemCount )+ PopulateStartingCashComboBox( comboBoxStartingCash, TheSkirmishGameInfo );}//-------------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cppindex 09e0ec8ab..cdfec814a 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/WOLGameSetupMenu.cpp@@ -1138,7 +1138,8 @@ void WOLDisplayGameOptions( void )Int itemCount = GadgetComboBoxGetLength(comboBoxStartingCash);- for ( Int index = 0; index < itemCount; index++ )+ Int index;+ for ( index = 0; index < itemCount; index++ ){Int value = (Int)GadgetComboBoxGetItemData(comboBoxStartingCash, index);if ( value == theGame->getStartingCash().countMoney() )@@ -1153,7 +1154,9 @@ void WOLDisplayGameOptions( void )}}- DEBUG_ASSERTCRASH( index < itemCount, ("Could not find new starting cash amount %d in list", theGame->getStartingCash().countMoney() ) );+ // see LanGameOptionsMenu: an amount from the player's INI that the list does not carry+ if ( index == itemCount )+ PopulateStartingCashComboBox( comboBoxStartingCash, theGame );// UpdatePeaceTimeComboBox only writes when the selection actually changes, which is what keeps// this out of the same recursion the two above are guarding againstdiff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetTextEntry.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetTextEntry.cppindex 472aa058b..05cdf2e50 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetTextEntry.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetTextEntry.cpp@@ -105,6 +105,13 @@ WindowMsgHandledType GadgetTextEntryInput( GameWindow *window, UnsignedInt msg,// --------------------------------------------------------------------if ( ch == VK_RETURN ){+ // WM_CHAR's lParam bit 30 says the key was already down: a held Enter repeating. The meta+ // map ignores repeats, but this did not, so holding Enter opened the chat with the press and+ // sent it shut with the first repeat, over and over.+ const WindowMsgData KEY_WAS_DOWN = 1 << 30;+ if( BitTest( mData2, KEY_WAS_DOWN ) )+ return MSG_HANDLED;+// Done with this editTheWindowManager->winSendSystemMsg( window->winGetOwner(),GEM_EDIT_DONE,diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cppindex e14dcad5f..6b53995af 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp@@ -528,6 +528,11 @@ void GameClient::reset( void )// need to reset the in game UI to clear drawables before they are destroyedTheInGameUI->reset();+ // the team keys pressed in the match we are leaving will never land, and the next one counts+ // its frames from zero again (init attaches no translators without a message stream)+ if (TheSelectionTranslator)+ TheSelectionTranslator->forgetPendingSquads();+// destroy all Drawablesfor( draw = m_drawableList; draw; draw = nextDraw ){diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cppindex b95fddc0f..622aadb43 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp@@ -10929,17 +10929,6 @@ static void putPowerBar( HtmlValues &values, std::vector< HtmlValues > &cells )values[ "power.state" ] = "green";}-/** How far `player` is from this rank to the next, 0 to 100. A script can disable a level, which- * leaves its points required at -1: a rank with no way on counts as full, where the bar's own- * drawing divided by it. */-static Int experiencePercent( const Player *player )-{- enum { FULL = 100 };- const Int span = player->getSkillPointsLevelUp() - player->getSkillPointsLevelDown();- const Int progress = span > 0 ? ( player->getSkillPoints() - player->getSkillPointsLevelDown() ) * FULL / span : FULL;- return min( (Int)FULL, max( 0, progress ) );-}-//-------------------------------------------------------------------------------------------------/** The general's experience as the page draws it, in the groove {{expframe.x}} ... puts down the* right panel: `cells` from the bottom up, each {{lit}} "lit" up to the way from this rank to the@@ -10964,7 +10953,7 @@ static void putExperienceBar( HtmlValues &values, std::vector< HtmlValues > &celif( player == NULL )return;- const Int lit = experiencePercent( player ) * EXPERIENCE_CELLS / FULL;+ const Int lit = player->getRankProgressPercent() * EXPERIENCE_CELLS / FULL;const Int column = height - 2 * FRAME_LIP;for( Int cell = 0; cell < EXPERIENCE_CELLS && column > 0; cell++ ){@@ -12102,7 +12091,7 @@ void InGameUI::drawPromotionPage( GameWindow *parent, Bool front ): ThePlayerList->getLocalPlayer();// its rungs cut from the bar's width in page pixels so they add up to it exactly, as the power// bar's cells are- const Int lit = player ? experiencePercent( player ) * EXPERIENCE_RUNGS / FULL : 0;+ const Int lit = player ? player->getRankProgressPercent() * EXPERIENCE_RUNGS / FULL : 0;const Int barWidth = atoi( values[ "ProgressBarExperience.w" ].c_str() );std::vector< HtmlValues > &rungs = lists[ "exprungs" ];for( Int rung = 0; rung < EXPERIENCE_RUNGS && barWidth > 0; rung++ )diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Keyboard.cppindex a3c6c0aec..cb944b1cc 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Keyboard.cpp@@ -148,6 +148,9 @@ void Keyboard::updateKeys( void )/** @todo -- if we don't have focus, we could destroy all the keys retrievedhere so that we don't process anything */+ // what this key was last pressed with, read before its new state overwrites it+ const UnsignedShort pressState = m_keyStatus[ m_keys[ index ].key ].state;+m_keyStatus[ m_keys[ index ].key ].state = m_keys[ index ].state;m_keyStatus[ m_keys[ index ].key ].status = m_keys[ index ].status;m_keyStatus[ m_keys[ index ].key ].sequence = timeGetTime();@@ -179,6 +182,18 @@ void Keyboard::updateKeys( void )} // end else if+ //+ // the modifiers held at this point of the batch, not at its end: Ctrl down, F down, Ctrl up+ // read in one frame used to hand the F its press without the Ctrl. A press keeps them in+ // the key's status, and its release says so, because a player who lets go of Ctrl before F+ // has still pressed Ctrl+F, not F (the command bar's F hotkey fired on that release).+ //+ BitSet( m_keys[ index ].state, m_modifiers );+ if( BitTest( m_keys[ index ].state, KEY_STATE_DOWN ) )+ m_keyStatus[ m_keys[ index ].key ].state = m_keys[ index ].state;+ else if( pressState & ( KEY_STATE_CONTROL | KEY_STATE_ALT ) )+ BitSet( m_keys[ index ].state, KEY_STATE_PRESSED_WITH_CTRL_ALT );+index++;} // end while@@ -186,22 +201,6 @@ void Keyboard::updateKeys( void )// check for key repeatscheckKeyRepeat();- if( m_modifiers )- {- index = 0;- while( m_keys[ index ].key != KEY_NONE )- {-- // set in the modifier data into the already existing up/down state- BitSet( m_keys[ index ].state, m_modifiers );-- // next key- index++;-- } // end while-- } // end if-} // end updateKeys//-------------------------------------------------------------------------------------------------@@ -236,7 +235,7 @@ Bool Keyboard::checkKeyRepeat( void ){// Add key to this framem_keys[ index ].key = (UnsignedByte)key;- m_keys[ index ].state = KEY_STATE_DOWN | KEY_STATE_AUTOREPEAT; // note: not a bitset; this is an assignment+ m_keys[ index ].state = KEY_STATE_DOWN | KEY_STATE_AUTOREPEAT | m_modifiers; // note: not a bitset; this is an assignmentm_keys[ index ].status = KeyboardIO::STATUS_UNUSED;// Set End Flag@@ -763,6 +762,24 @@ void Keyboard::update( void )void Keyboard::resetKeys( void ){+ //+ // A modifier held when focus went away comes up in another window, and its release never+ // reaches the game. Wiping the state here was not enough: the translators downstream still+ // had Alt held, so after an Alt+Tab the first key pressed went to ending an Alt that was long+ // gone, and a fresh Alt could not start waypoints because nothing had changed. Let them see+ // the release. There is no stream yet, or any more, while the window starts and closes.+ //+ static const KeyDefType modifierKeys[] = { KEY_LCTRL, KEY_RCTRL, KEY_LSHIFT, KEY_RSHIFT, KEY_LALT, KEY_RALT };+ for( Int i = 0; TheMessageStream && i < (Int)ARRAY_SIZE( modifierKeys ); ++i )+ {+ if( BitTest( m_keyStatus[ modifierKeys[ i ] ].state, KEY_STATE_DOWN ) )+ {+ GameMessage *msg = TheMessageStream->appendMessage( GameMessage::MSG_RAW_KEY_UP );+ msg->appendIntegerArgument( modifierKeys[ i ] );+ msg->appendIntegerArgument( KEY_STATE_UP );+ }+ }+memset( m_keys, 0, sizeof( m_keys ) );memset( m_keyStatus, 0, sizeof( m_keyStatus ) );m_modifiers = KEY_STATE_NONE;diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cppindex 4cd395ddf..4c2bb43c0 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/CommandXlat.cpp@@ -615,7 +615,12 @@ void pickAndPlayUnitVoiceResponse( const DrawableList *list, GameMessage::Type mcase GameMessage::MSG_DO_ATTACK_OBJECT:case GameMessage::MSG_DO_WEAPON_AT_OBJECT:{- if( !soundToPlayPtr )+ // The first unit in the selection answered for all of it, even one that cannot shoot the+ // target: a Chinook grouped with a Humvee called out its combat drop. The voice comes from+ // a unit that can take the shot; a command-button weapon is judged in its own branch below.+ const Bool canAnswer = msgType == GameMessage::MSG_DO_WEAPON_AT_OBJECT || target == NULL+ || canObjectForceAttack( obj, target, NULL ) != ATTACKRESULT_NOT_POSSIBLE;+ if( !soundToPlayPtr && canAnswer ){//Low priority sounds -- only do this if uninitialized.if( info && info->m_air )@@ -929,7 +934,8 @@ void amIAHero(Object* obj, void* heroHolder)return;}- if (obj->isKindOf( KINDOF_HERO ))+ // a hero in his death animation is still on the player's list until the body is removed+ if (obj->isKindOf( KINDOF_HERO ) && !obj->isEffectivelyDead()){((HeroHolder*)heroHolder)->hero = obj;}diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cppindex e9478c814..df3241774 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/HotKey.cpp@@ -100,6 +100,9 @@ GameMessageDisposition HotKeyTranslator::translateGameMessage(const GameMessage// the label hotkey is meant to be that click's equal. Ctrl and alt still block the hotkey.if(newModState & ~SHIFT)return disp;+ // Ctrl+F let go of Ctrl first ends on a bare F release; it is still Ctrl+F+ if( keyState & KEY_STATE_PRESSED_WITH_CTRL_ALT )+ return disp;// NUL-terminate it: UnicodeString::set() runs wcslen over what it is given, and this used// to hand it a single un-terminated WideChar on the stack.WideChar key[2];diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cppindex 9c5b12bbc..fecdb8089 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/SelectionXlat.cpp@@ -56,6 +56,7 @@#include "GameClient/SelectionPriority.h"#include "GameClient/SelectionXlat.h"#include "GameClient/TerrainVisual.h"+#include "GameNetwork/NetworkInterface.h"#ifdef _INTERNAL// for occasional debugging...@@ -289,6 +290,7 @@ SelectionTranslator::SelectionTranslator()m_rightDownTime = 0;m_rightDownCamera.zero();m_selectCountMap.clear();+ forgetPendingSquads();TheSelectionTranslator = this;@@ -1250,15 +1252,21 @@ GameMessageDisposition SelectionTranslator::translateGameMessage(const GameMessaDEBUG_LOG(("META: create team %d\n",group));// Assign selected items to a groupGameMessage *newmsg = TheMessageStream->appendMessage((GameMessage::Type)(GameMessage::MSG_CREATE_TEAM0 + group));+ m_pendingSquad[ group ].clear();Drawable *drawable = TheGameClient->getDrawableList();while (drawable != NULL){if (drawable->isSelected() && drawable->getObject() && drawable->getObject()->isLocallyControlled()){newmsg->appendObjectIDArgument(drawable->getObject()->getID());+ m_pendingSquad[ group ].push_back(drawable->getObject()->getID());}drawable = drawable->getNextDrawable();}+ // A game on one machine runs it on the next logic frame, before any select could see the old+ // squad. One frame over in a network game, for a message the network sends out a frame late:+ // the list stands in for the squad it becomes, so reading it once too often costs nothing.+ m_pendingSquadLands[ group ] = TheNetwork ? (UnsignedInt)TheNetwork->getExecutionFrame() + 1 : 0;}disp = DESTROY_MESSAGE;break;@@ -1331,19 +1339,7 @@ GameMessageDisposition SelectionTranslator::translateGameMessage(const GameMessaPlayer *player = ThePlayerList->getLocalPlayer();if (player){- Squad *selectedSquad = player->getHotkeySquad(group);- if (selectedSquad != NULL)- {- VecObjectPtr objlist = selectedSquad->getLiveObjects();- Int numObjs = objlist.size();- for (Int i = 0; i < numObjs; ++i)- {- if( objlist[i]->getControllingPlayer() == player )- {- TheInGameUI->selectDrawable(objlist[i]->getDrawable());- }- }- }+ selectHotkeySquad( player, group, TRUE );}}m_lastGroupSelTime = now;@@ -1414,16 +1410,7 @@ GameMessageDisposition SelectionTranslator::translateGameMessage(const GameMessaPlayer *player = ThePlayerList->getLocalPlayer();if (player){- Squad *selectedSquad = player->getHotkeySquad(group);- if (selectedSquad != NULL)- {- VecObjectPtr objlist = selectedSquad->getLiveObjects();- Int numObjs = objlist.size();- for (Int i = 0; i < numObjs; ++i)- {- TheInGameUI->selectDrawable(objlist[i]->getDrawable());- }- }+ selectHotkeySquad( player, group, FALSE );}}m_lastGroupSelTime = now;@@ -1557,3 +1544,65 @@ void SelectionTranslator::setLeftMouseButton(Bool state){m_leftMouseButtonIsDown = state;}++//-----------------------------------------------------------------------------+void SelectionTranslator::forgetPendingSquads()+{+ for( Int group = 0; group < NUM_HOTKEY_SQUADS; ++group )+ {+ m_pendingSquad[ group ].clear();+ m_pendingSquadLands[ group ] = 0;+ }+}++//-----------------------------------------------------------------------------+Bool SelectionTranslator::isSquadPending( Int group ) const+{+ return m_pendingSquadLands[ group ] != 0 && TheGameLogic->getFrame() <= m_pendingSquadLands[ group ];+}++//-----------------------------------------------------------------------------+/** Select on screen what the logic will hold in this squad by the time a select sent now lands:+ * the members a team key sent for it if they are still on the way, and never a unit that a key+ * on the way takes into another squad, which the logic removes from every squad but its new one. */+//-----------------------------------------------------------------------------+void SelectionTranslator::selectHotkeySquad( Player *player, Int group, Bool ownOnly )+{+ VecObjectPtr objlist;+ const UnsignedInt groupLands = isSquadPending( group ) ? m_pendingSquadLands[ group ] : 0;+ if( groupLands != 0 )+ {+ for( size_t i = 0; i < m_pendingSquad[ group ].size(); ++i )+ {+ Object *obj = TheGameLogic->findObjectByID( m_pendingSquad[ group ][ i ] );+ if( obj && obj->isSelectable() )+ objlist.push_back( obj );+ }+ }+ else+ {+ Squad *selectedSquad = player->getHotkeySquad( group );+ if( selectedSquad == NULL )+ return;+ objlist = selectedSquad->getLiveObjects();+ }++ for( size_t i = 0; i < objlist.size(); ++i )+ {+ Object *obj = objlist[ i ];+ if( ownOnly && obj->getControllingPlayer() != player )+ continue;++ Bool movedAway = FALSE;+ for( Int other = 0; other < NUM_HOTKEY_SQUADS && !movedAway; ++other )+ {+ // only a key that lands after this squad's own can still take a member out of it+ if( other == group || !isSquadPending( other ) || m_pendingSquadLands[ other ] <= groupLands )+ continue;+ const std::vector<ObjectID> &sent = m_pendingSquad[ other ];+ movedAway = std::find( sent.begin(), sent.end(), obj->getID() ) != sent.end();+ }+ if( !movedAway )+ TheInGameUI->selectDrawable( obj->getDrawable() );+ }+}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cppindex 4a8e46fbc..d3f2c2d07 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGroup.cpp@@ -3644,8 +3644,31 @@ void AIGroup::groupCheer( CommandSourceType cmdSource )}}+/** The checks ControlBar makes before it shows the sell button. The order lands on whatever is+ * selected when the logic frame runs, and a selection hotkey pressed in the same frame as the+ * button used to sell a tech building, a scaffold or a garrisoned civilian building. */+static Bool mayPlayerSell( const Object *obj )+{+ if( obj->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION ) )+ return FALSE;+ if( obj->testScriptStatusBit( OBJECT_STATUS_SCRIPT_UNSELLABLE ) || obj->isDisabledByType( DISABLED_SUBDUED ) )+ return FALSE;++ const CommandSet *commandSet = TheControlBar->findCommandSet( obj->getCommandSetString() );+ if( commandSet == NULL )+ return FALSE;++ for( Int buttonIndex = 0; buttonIndex < MAX_COMMANDS_PER_SET; buttonIndex++ )+ {+ const CommandButton *button = commandSet->getCommandButton( buttonIndex );+ if( button && button->getCommandType() == GUI_COMMAND_SELL )+ return TRUE;+ }+ return FALSE;+}+/**- * Sell all things in the group ... if possible+ * Sell all things in the group ... if possible*/void AIGroup::groupSell( CommandSourceType cmdSource ){@@ -3662,6 +3685,9 @@ void AIGroup::groupSell( CommandSourceType cmdSource )// get objectobj = *thisIterator;+ if( cmdSource == CMD_FROM_PLAYER && !mayPlayerSell( obj ) )+ continue;+// try to sell objectTheBuildAssistant->sellObject( obj );@@ -3887,6 +3913,9 @@ Bool AIGroup::setWeaponLockForGroup( WeaponSlotType weaponSlot, WeaponLockType lstd::list<Object *>::iterator i;for( i = m_memberList.begin(); i != m_memberList.end(); ++i ){+ // a permanent lock is the switch-weapon button, and only members that have the button take it+ if( lockType == LOCKED_PERMANENTLY && !(*i)->canSwitchToWeapon( weaponSlot ) )+ continue;if ((*i)->setWeaponLock( weaponSlot, lockType ))any = true;}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuard.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuard.cppindex d3937eda0..0a12a3fd8 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuard.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIGuard.cpp@@ -40,6 +40,7 @@#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine#include "Common/PerfTimer.h"+#include "Common/Player.h"#include "Common/Team.h"#include "Common/Xfer.h"#include "Common/ThingTemplate.h"@@ -242,6 +243,7 @@ Bool AIGuardMachine::lookForInnerTarget(void)PartitionFilterRelationship f5(owner, PartitionFilterRelationship::ALLOW_NEUTRAL);PartitionFilterPossibleToEnter f6(owner, CMD_FROM_AI);PartitionFilterPossibleToHijack f7(owner, CMD_FROM_AI);+ PartitionFilterFreeOfFog filterFogged(owner->getControllingPlayer()->getPlayerIndex());PartitionFilter *filters[16];Int count = 0;@@ -270,6 +272,9 @@ Bool AIGuardMachine::lookForInnerTarget(void)}filters[count++] = &filterMapStatus;+ // A guard used to lock onto enemies standing in fog, which every other auto-target refuses+ // (getNextMoodTarget's UNFOGGED). It picks from what its player can see now.+ filters[count++] = &filterFogged;Real visionRange = AIGuardMachine::getStdGuardRange(owner);diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cppindex 056642234..b006a6ee2 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp@@ -615,14 +615,15 @@ void AISkirmishPlayer::acquireEnemy(void)// distance to half the map, which reads as "ignore the one you are about to beat".//Bool alreadyTargeted = FALSE;- Bool attackingMe = FALSE;+ // The candidate itself has to have picked us. EA asked this of every other AI in the loop+ // below, which skips the candidate, so the bonus went to anyone but the aggressor.+ Bool attackingMe = curPlayer->isSkirmishAIPlayer() && curPlayer->getCurrentEnemy()==m_player;Int k;for (k=0; k<ThePlayerList->getPlayerCount(); k++) {if (k==i) continue; // don't count self.Player *somePlayer = ThePlayerList->getNthPlayer(k);if (!somePlayer->isSkirmishAIPlayer()) continue;if (somePlayer->getCurrentEnemy()==curPlayer) alreadyTargeted = TRUE;- if (somePlayer->getCurrentEnemy()==m_player) attackingMe = TRUE;}const Real share = (estateTotal > 0.0f && i < MAX_PLAYER_COUNT) ? (estate[i] / estateTotal) : 0.0f;diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cppindex e11d7c4f1..e636a9e2e 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIStates.cpp@@ -5908,6 +5908,16 @@ StateReturnType AIAttackFireWeaponState::update()return STATE_FAILURE;}+ // The victim can leave range between the aim and the shot: a vehicle driving off while Jarmen Kell+ // turns to snipe it. fireWeaponTemplate then refuses the shot, but the round is already off the+ // clip, so a one-round ability went on cooldown with nothing hit. Back to aiming instead, which+ // closes the distance. A contained shooter is left alone, its range comes from a fire point.+ if (m_att->isAttackingObject() && !weapon->getTemplate()->isLeechRangeWeapon() && !obj->isContained()+ && !weapon->isWithinAttackRange(obj, victim))+ {+ return STATE_FAILURE;+ }+// must adjust the state BEFORE calling fireWeapon, for FX to work correctly...obj->setFiringConditionForCurrentWeapon();diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AITNGuard.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AITNGuard.cppindex 2d7d9492d..b4d4539c5 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AITNGuard.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AITNGuard.cpp@@ -364,6 +364,7 @@ static Object *TunnelNetworkScan(Object *owner)PartitionFilterRelationship f1(owner, PartitionFilterRelationship::ALLOW_ENEMIES);PartitionFilterPossibleToAttack f2(ATTACK_NEW_TARGET, owner, CMD_FROM_AI);PartitionFilterSameMapStatus filterMapStatus(owner);+ PartitionFilterFreeOfFog filterFogged(owner->getControllingPlayer()->getPlayerIndex());PartitionFilter *filters[16];Int count = 0;@@ -371,6 +372,7 @@ static Object *TunnelNetworkScan(Object *owner)filters[count++] = &f1;filters[count++] = &f2;filters[count++] = &filterMapStatus;+ filters[count++] = &filterFogged; // guard picks what its player can see, as every other auto-target doesReal visionRange = AITNGuardMachine::getStdGuardRange(owner);diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cppindex 2ecaacbfe..23793304a 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/PolygonTrigger.cpp@@ -285,7 +285,7 @@ void PolygonTrigger::updateBounds(void) const}m_boundsNeedsUpdate = 0;Real halfWidth = (m_bounds.hi.x - m_bounds.lo.x) / 2.0f;- Real halfHeight = (m_bounds.hi.y + m_bounds.lo.y) / 2.0f;+ Real halfHeight = (m_bounds.hi.y - m_bounds.lo.y) / 2.0f;m_radius = sqrt(halfHeight*halfHeight + halfWidth*halfWidth);}@@ -554,6 +554,10 @@ void PolygonTrigger::xfer( Xfer *xfer )// bounds need updatexfer->xferBool( &m_boundsNeedsUpdate );+ // the radius is derived from the points, and a save from before the half-height fix holds a wrong one+ if( xfer->getXferMode() == XFER_LOAD )+ m_boundsNeedsUpdate = TRUE;+} // end xfer// ------------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cppindex bc6546ae5..990a11dc6 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Map/TerrainLogic.cpp@@ -2665,7 +2665,11 @@ void TerrainLogic::setActiveBoundary(Int newActiveBoundary)ThePartitionManager->reset();ThePartitionManager->init();+ // newMap resets the radar, and a reset stops forcing it on: a replay, an observer or a beaten+ // player lost the minimap for the rest of the match the moment a script moved the border+ const Bool radarForced = TheRadar->isRadarForced();TheRadar->newMap(TheTerrainLogic);+ TheRadar->forceOn(radarForced);ThePartitionManager->restoreFoggedCells(partitionStore, FALSE);diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/AutoHealBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/AutoHealBehavior.cppindex 5ecaa5317..affdc152d 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/AutoHealBehavior.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/AutoHealBehavior.cpp@@ -304,7 +304,10 @@ void AutoHealBehavior::pulseHealObject( Object *obj )const AutoHealBehaviorModuleData *data = getAutoHealBehaviorModuleData();- if ( data->m_radius == 0.0f )+ // A single burst is one heal, not a source that could stack pulse on pulse, so it skips the+ // one-healer-at-a-time rule. Under it an Emergency Repair landing on vehicles an Ambulance or a+ // Propaganda Tower was already tending healed nothing, and the burst never comes again.+ if ( data->m_radius == 0.0f || data->m_singleBurst )obj->attemptHealing(data->m_healingAmount, getObject());elseobj->attemptHealingFromSoleBenefactor( data->m_healingAmount, getObject(), data->m_healingDelay );diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cppindex 4b5337d7c..34b6d1b72 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Behavior/SpawnBehavior.cpp@@ -847,6 +847,10 @@ Bool SpawnBehavior::shouldTryToSpawn()// Not if we are turned offif( !m_active )return FALSE;+ // Not once we are dead: a spawner killed earlier in the frame still runs this update before it is+ // destroyed, and whatever it made then was never in the list onDie walked, so it lived on alone.+ if( getObject()->isEffectivelyDead() )+ return FALSE;if( getObject()->getStatusBits().test( OBJECT_STATUS_RECONSTRUCTING ) && modData->m_isOneShotData ){// If we are a Hole rebuild, not only should we not, but we should never ask again.diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Body/UndeadBody.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Body/UndeadBody.cppindex 9cfab244c..6020d4395 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Body/UndeadBody.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Body/UndeadBody.cpp@@ -71,6 +71,28 @@ UndeadBody::~UndeadBody( void )}+// ------------------------------------------------------------------------------------------------+/** A death type that only ordinary slow deaths take is a real death, not a first one. The Battle+ * Bus leaves SUICIDED and EXTRA_4 to a plain SlowDeathBehavior on purpose, but the second life+ * started that module straight from here, without onDie, so a detonated Demo bus vanished a frame+ * later without its death weapon. With no slow death at all the second life still happens. */+// ------------------------------------------------------------------------------------------------+static Bool isSecondLifeDeath( Object *obj, const DamageInfo *damageInfo )+{+ Bool anyApplies = FALSE;+ for( BehaviorModule** update = obj->getBehaviorModules(); *update; ++update )+ {+ SlowDeathBehaviorInterface* sdu = (*update)->getSlowDeathBehaviorInterface();+ if( sdu != NULL && sdu->isDieApplicable( damageInfo ) )+ {+ if( sdu->canBeginSecondLife() )+ return TRUE;+ anyApplies = TRUE;+ }+ }+ return !anyApplies;+}+// ------------------------------------------------------------------------------------------------// ------------------------------------------------------------------------------------------------void UndeadBody::attemptDamage( DamageInfo *damageInfo )@@ -87,6 +109,7 @@ void UndeadBody::attemptDamage( DamageInfo *damageInfo )&& !m_isSecondLife&& estimateDamage( damageInfo->in ) >= getHealth()&& IsHealthDamagingDamage(damageInfo->in.m_damageType)+ && isSecondLifeDeath( getObject(), damageInfo )){// clamp what lands, for the same reason as the test above: armour applied after a raw clamp@@ -126,7 +149,7 @@ void UndeadBody::startSecondLife(DamageInfo *damageInfo)for( update = getObject()->getBehaviorModules(); *update; ++update ){SlowDeathBehaviorInterface* sdu = (*update)->getSlowDeathBehaviorInterface();- if (sdu != NULL && sdu->isDieApplicable(damageInfo) )+ if (sdu != NULL && sdu->isDieApplicable(damageInfo) && sdu->canBeginSecondLife() ){total += sdu->getProbabilityModifier( damageInfo );}@@ -140,7 +163,7 @@ void UndeadBody::startSecondLife(DamageInfo *damageInfo)for( update = getObject()->getBehaviorModules(); *update; ++update){SlowDeathBehaviorInterface* sdu = (*update)->getSlowDeathBehaviorInterface();- if (sdu != NULL && sdu->isDieApplicable(damageInfo))+ if (sdu != NULL && sdu->isDieApplicable(damageInfo) && sdu->canBeginSecondLife()){roll -= sdu->getProbabilityModifier( damageInfo );if (roll <= 0)diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/CrateCollide.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/CrateCollide.cppindex 27657b1aa..755bc5ef6 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/CrateCollide.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Collide/CrateCollide/CrateCollide.cpp@@ -185,6 +185,12 @@ Bool CrateCollide::isValidToExecute( const Object *other ) constif( !md->m_allowMultiplePickup && getObject()->isDestroyed() )return FALSE;+ // A unit that works as a crate (hijacker, saboteur, pilot) and was killed earlier in the same frame+ // still touched its target before it was gone: a Paladin's laser shot the hijacker, and he left a+ // corpse and took the Paladin as well.+ if( getObject()->isEffectivelyDead() )+ return FALSE;+if( md->m_isForbidOwnerPlayer && (getObject()->getControllingPlayer() == other->getControllingPlayer()) )return FALSE; // Design has decreed this to not be picked up by the dead guy's team.diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/HelixContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/HelixContain.cppindex e15359841..90443a4ec 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/HelixContain.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/HelixContain.cpp@@ -241,10 +241,14 @@ void HelixContain::onDelete( void )// ------------------------------------------------------------------------------------------------void HelixContain::onCapture( Player *oldOwner, Player *newOwner ){-// Need to setteam() the portable structure, that's all;+// Need to setteam() the portable structureObject *portable = getPortableStructure();if ( portable )portable->setTeam( newOwner->getDefaultTeam() );++ // and the passengers go the way every transport's do: a Helix sniped on the ground skipped this,+ // so its infantry sat on in a neutral hulk while an Overlord's or a Humvee's got out+ TransportContain::onCapture( oldOwner, newOwner );}//-------------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cppindex b7027fa81..cadba1aea 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/OpenContain.cpp@@ -505,26 +505,20 @@ void OpenContain::killAllContained( void )//--------------------------------------------------------------------------------------------------------void OpenContain::harmAndForceExitAllContained( DamageInfo *info ){- ContainedItemsList::iterator it = m_containList.begin();-- while ( it != m_containList.end() )- {- Object *rider = *it;-- if ( rider )- {- removeFromContain( rider, true );- rider->attemptDamage( info );- }-- //Kris: Patch 1.03 -- Crash fix when neutral bunker on Alpine Assault is occupied with 10 demo general- //infantry units with the suicide upgrade and US stealth fighters with bunker busters kill the guys inside.- //Causes recursive damage where a bunker buster destroys an infantry, the infantry explodes and blows up- //another missile which kills everyone inside while the first missile is killing everyone. And the game blows up.- //Fix is to reset the list.- it = m_containList.begin();+ // Everyone is out before anyone is harmed. Harming a rider can bring the container down (a demo+ // rider's suicide blast), and the container's death then put the riders still inside out without the+ // damage they were owed. Patch 1.03 restarted the walk after every rider to survive that recursion;+ // emptying the list first makes the recursion find nothing.+ std::vector<Object*> exited;+ while ( !m_containList.empty() )+ {+ Object *rider = m_containList.front();+ removeFromContain( rider, true );+ exited.push_back( rider );+ }- } // end while+ for ( std::vector<Object*>::iterator it = exited.begin(); it != exited.end(); ++it )+ (*it)->attemptDamage( info );DEBUG_ASSERTCRASH( m_containListSize == 0, ("harmAndForceExitAllContained just made a booboo, list size != zero.") );diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TunnelContain.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TunnelContain.cppindex a39836c49..c45076e49 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TunnelContain.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Contain/TunnelContain.cpp@@ -131,27 +131,26 @@ void TunnelContain::harmAndForceExitAllContained( DamageInfo *info )if( tunnelTracker == NULL )return;- const ContainedItemsList *fullList = tunnelTracker->getContainedItemsList();+ // A tunnel still being built joins the network the moment it is placed, but nobody can be inside+ // it: a Bunker Buster on the scaffold threw out and hurt everyone in every tunnel on the map.+ if( getObject()->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION ) )+ return;- Object *obj;- ContainedItemsList::const_iterator it;+ const ContainedItemsList *fullList = tunnelTracker->getContainedItemsList();- //Kris: Patch 1.01 -- November 6, 2003- //No longer advances the iterator and saves it. The iterator is fetched from the beginning after- //each loop. This is to prevent a crash where dropping a bunker buster on a tunnel network containing- //multiple units (if they have the suicide bomb upgrade - demo general). In this case, multiple bunker- //busters would hit the tunnel network in close succession. Missile #1 would iterate the list, killing- //infantry #1. Infantry #1 would explode and destroy Missile #2. Missile #2 would start iterating the- //same list, killing the remaining units. When Missile #1 picked up and continued processing the list- //it would crash because it's iterator was deleted from under it.- it = (*fullList).begin();- while( it != (*fullList).end() )+ // Everyone is out before anyone is harmed, as in OpenContain. A demo rider's blast can kill the last+ // tunnel, whose death kills everyone still inside instead of putting them out harmed, and a second+ // bunker buster set off by that blast finds the list already empty instead of walking it under the first.+ std::vector<Object*> exited;+ while( !fullList->empty() ){- obj = *it;+ Object *obj = fullList->front();removeFromContain( obj, true );- obj->attemptDamage( info );- it = (*fullList).begin();- } // end while+ exited.push_back( obj );+ }++ for( std::vector<Object*>::iterator it = exited.begin(); it != exited.end(); ++it )+ (*it)->attemptDamage( info );} // end removeAllContained@@ -170,6 +169,10 @@ void TunnelContain::killAllContained( void )if( tunnelTracker == NULL )return;+ // the scaffold holds nobody; Neutron Shells on one killed the whole network (see above)+ if( getObject()->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION ) )+ return;+ContainedItemsList list;tunnelTracker->swapContainedItemsList( list );diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/FiringTracker.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/FiringTracker.cppindex 4457981c6..9205558b1 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/FiringTracker.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/FiringTracker.cpp@@ -167,6 +167,10 @@ void FiringTracker::shotFired(const Weapon* weaponFired, ObjectID victimID){AudioEventRTS audio = weaponFired->getFireSound();audio.setObjectID(getObject()->getID());+ // Still firing but no longer playing: the audio manager dropped the loop, usually because the+ // camera moved out of its range. Picking it up again replayed the Attack part as if the+ // weapon had just opened fire (an ECM tank's jammer, upstream #166).+ audio.setSkipAttack(m_frameToStopLoopingSound != 0 && now < m_frameToStopLoopingSound);m_audioHandle = TheAudio->addAudioEvent( &audio );}m_frameToStopLoopingSound = now + fireSoundLoopTime;diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Locomotor.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Locomotor.cppindex 8695fd5dc..a101dcb53 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Locomotor.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Locomotor.cpp@@ -648,7 +648,10 @@ void LocomotorStore::reset()Overridable *locoTemp = it->second->deleteOverrides();if (!locoTemp){- m_locomotorTemplates.erase(it);+ // a locomotor a map.ini made from nothing goes whole. erase() leaves 'it' dangling, and the+ // loop went on comparing it - the heap damage that crashed loading a save of such a map,+ // since every load resets the engine first.+ it = m_locomotorTemplates.erase(it);}else{diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cppindex 59707b1e2..65579eec4 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Object.cpp@@ -5894,7 +5894,8 @@ void Object::doCommandButton( const CommandButton *commandButton, CommandSourceT{WeaponSlotType weaponSlot = commandButton->getWeaponSlot();// GUI_COMMAND_SWITCH_WEAPON switches until un-switched, or switched to something else.- setWeaponLock( weaponSlot, LOCKED_PERMANENTLY );+ if( canSwitchToWeapon( weaponSlot ) )+ setWeaponLock( weaponSlot, LOCKED_PERMANENTLY );return;}@@ -6595,6 +6596,26 @@ Bool Object::canProduceUpgrade( const UpgradeTemplate *upgrade )return FALSE;// Cheatin' punk.}+//=============================================================================+/** A switch-weapon order goes to a whole selection or a whole team, and every member used to take+ * the lock. A Missile Defender in a group with a Ranger took the flashbang switch as a permanent+ * lock on its laser-guided missiles and fired them at anything, as fast as they reload. */+Bool Object::canSwitchToWeapon( WeaponSlotType weaponSlot ) const+{+ const CommandSet *set = TheControlBar->findCommandSet(getCommandSetString());+ if( set == NULL )+ return FALSE; // an object with no command set has no buttons at all++ for( Int buttonIndex = 0; buttonIndex < MAX_COMMANDS_PER_SET; buttonIndex++ )+ {+ const CommandButton *button = set->getCommandButton(buttonIndex);+ if( button && button->getCommandType() == GUI_COMMAND_SWITCH_WEAPON && button->getWeaponSlot() == weaponSlot )+ return TRUE;+ }++ return FALSE;+}+//-------------------------------------------------------------------------------------------------/** An infantryman reaching an unmanned vehicle becomes its driver: the vehicle is his side's and* he is gone. The collision that brings him to it can arrive on either object first, so bothdiff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cppindex 8872a64b4..d1af22301 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/ObjectCreationList.cpp@@ -1406,6 +1406,10 @@ protected:fpOptions.minRadius = GameLogicRandomValueReal(m_minDistanceAFormation, m_minDistanceBFormation);fpOptions.maxRadius = m_maxDistanceFormation;fpOptions.flags = FPF_USE_HIGHEST_LAYER;+ // DiesOnBadLand kills on the pathfind cell's type, and the search's own cliff and water+ // tests read the terrain, which disagree at a shoreline: take only cells it accepts+ if (m_diesOnBadLand)+ fpOptions.flags = (FindPositionFlags)(fpOptions.flags | FPF_CLEAR_CELLS_ONLY);ThePartitionManager->findPositionAround(pos, &fpOptions, &resultPos);doStuffToObj( debris, m_names[pick], &resultPos, mtx, orientation, sourceObj, lifetimeFrames );}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cppindex 3e1cbc1fe..bc279df67 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/PartitionManager.cpp@@ -3986,6 +3986,13 @@ Bool PartitionManager::tryPosition( const Coord3D *center,them->isKindOf( KINDOF_STRUCTURE ) )continue;+ // A friendly mine is no obstacle: nothing walks around it and it never goes off under us.+ // Its geometry is the 30-unit trigger circle, though, so a supply center with the mine+ // upgrade ringed itself with rejected spots and sent its trucks to dock beyond them.+ if( them->isKindOf( KINDOF_MINE ) &&+ options->relationshipObject->getRelationship( them ) == ALLIES )+ continue;+} // end if, relationship checks//diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cppindex a44a8564b..832dc295f 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate.cpp@@ -620,10 +620,11 @@ void AIUpdateInterface::requestPath( Coord3D *destination, Bool isFinalGoal )}m_waitingForPath = TRUE;if (m_pathTimestamp > TheGameLogic->getFrame()-3) {- /* Requesting path very quickly. Can cause a spin. */- //DEBUG_LOG(("%d Pathfind - repathing in less than 3 frames. Waiting 1 second\n",- //TheGameLogic->getFrame()));- setQueueForPathTime(LOGICFRAMES_PER_SECOND);+ /* Requesting path very quickly. Can cause a spin. The spin needs a gap between two+ paths, not the one or two seconds EA waited here, which left a unit that had just been+ given a second order standing still or walking the old path until the timer ran out. So+ the request waits out the rest of the three frames and no longer. */+ setQueueForPathTime(repathDebounceFrames());// See if it has been too soon.// jba intense debug//DEBUG_LOG(("Info - RePathing very quickly %d, %d.\n", m_pathTimestamp, TheGameLogic->getFrame()));@@ -654,8 +655,7 @@ void AIUpdateInterface::requestAttackPath( ObjectID victimID, const Coord3D* vicm_waitingForPath = TRUE;if (m_pathTimestamp > TheGameLogic->getFrame()-3) {/* Requesting path very quickly. Can cause a spin. */- //DEBUG_LOG(("%d Pathfind - repathing in less than 3 frames. Waiting 2 second\n",TheGameLogic->getFrame()));- setQueueForPathTime(2*LOGICFRAMES_PER_SECOND);+ setQueueForPathTime(repathDebounceFrames());setLocomotorGoalNone();return;}@@ -678,8 +678,7 @@ void AIUpdateInterface::requestApproachPath( Coord3D *destination )m_waitingForPath = TRUE;if (m_pathTimestamp > TheGameLogic->getFrame()-3) {/* Requesting path very quickly. Can cause a spin. */- //DEBUG_LOG(("%d Pathfind - repathing in less than 3 frames. Waiting 2 second\n",TheGameLogic->getFrame()));- setQueueForPathTime(2*LOGICFRAMES_PER_SECOND);+ setQueueForPathTime(repathDebounceFrames());return;}queueForPathOrRetry();@@ -702,8 +701,7 @@ void AIUpdateInterface::requestSafePath( ObjectID repulsor )m_waitingForPath = TRUE;if (m_pathTimestamp > TheGameLogic->getFrame()-3) {/* Requesting path very quickly. Can cause a spin. */- //DEBUG_LOG(("%d Pathfind - repathing in less than 3 frames. Waiting 2 second\n",TheGameLogic->getFrame()));- setQueueForPathTime(2*LOGICFRAMES_PER_SECOND);+ setQueueForPathTime(repathDebounceFrames());return;}queueForPathOrRetry();@@ -5956,6 +5954,10 @@ void AIUpdateInterface::privateGuardPosition( const Coord3D *pos, GuardMode guarm_guardMode = guardMode;getStateMachine()->clear();+ // The guard machine moves on its own goal, so the outer one kept whatever the last order left+ // in it, (0,0,0) on a fresh unit. An ALT-queued move appends after the goal position and so+ // started its path from the map's corner.+ setGoalPositionClipped( &adjPos, cmdSource );setLastCommandSource( cmdSource );getStateMachine()->setState( AI_GUARD );}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cppindex 7952545cd..ed3fe240e 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/ChinookAIUpdate.cpp@@ -1074,12 +1074,14 @@ UpdateSleepTime ChinookAIUpdate::update()!m_hasPendingCommand &&getObject()->getBodyModule()->getHealth() == getObject()->getBodyModule()->getMaxHealth()){- // we're completely healed, so take off again+ // we're completely healed, so take off again. Let go of the pad too, or a later order to+ // repair at it would read as "already repairing there" and be ignored.pp->setHealee(getObject(), false);+ Object *airfield = TheGameLogic->findObjectByID( m_airfieldForHealing );+ setAirfieldForHealing(INVALID_ID);setMyState(TAKING_OFF, NULL, NULL, CMD_FROM_AI);// and then go where the airfield's rally point says, instead of hovering over the pad- Object *airfield = TheGameLogic->findObjectByID( m_airfieldForHealing );if (airfield){ExitInterface *exitInterface = airfield->getObjectExitInterface();@@ -1098,11 +1100,16 @@ UpdateSleepTime ChinookAIUpdate::update()}else{+ // The airfield we were flying to for repairs is gone: stop there, the way a unit driving to a+ // dead war factory does, instead of flying on and landing on the rubble.+ const Bool lostRepairAirfield = m_airfieldForHealing != INVALID_ID && m_flightStatus == CHINOOK_FLYING;setAirfieldForHealing(INVALID_ID);+ if (lostRepairAirfield)+ aiIdle(CMD_FROM_AI);}-+// have to call our parent's isIdle, because we override it to never return true// when we have a pending command...ContainModuleInterface* contain = getObject()->getContain();@@ -1127,6 +1134,16 @@ UpdateSleepTime ChinookAIUpdate::update()setMyState(TAKING_OFF, NULL, NULL, CMD_FROM_AI);}}+ else if (m_flightStatus == CHINOOK_FLYING && !m_hasPendingCommand && contain->hasObjectsWantingToEnterOrExit())+ {+ // A Helix guarding, or shooting at something, never went idle, so infantry sent to board it+ // stood underneath until the player pressed Stop, and a passenger told to get out stayed in.+ // Neither order has anywhere to be, so the newer one wins and it comes down. A move still+ // finishes first; the idle branch above lands at the end of it.+ StateID state = getCurrentStateID();+ if (state == AI_GUARD || state == AI_GUARD_RETALIATE || state == AI_ATTACK_OBJECT || state == AI_ATTACK_POSITION)+ setMyState(LANDING, NULL, NULL, CMD_FROM_AI);+ }if ( TheGameLogic->getFrame()%10 == 1 )@@ -1273,8 +1290,15 @@ void ChinookAIUpdate::privateCombatDrop( Object* target, const Coord3D& pos, Com//-------------------------------------------------------------------------------------------------void ChinookAIUpdate::aiDoCommand(const AICommandParms* parms){- // this gets reset every time a command is issued.- setAirfieldForHealing(INVALID_ID);+ // Already on the way to this pad or sitting on it: a second order to repair there used to drop the+ // healing, take off and fly a circuit back to the same pad.+ if (parms->m_cmd == AICMD_GET_REPAIRED && parms->m_obj != NULL && parms->m_obj->getID() == m_airfieldForHealing)+ return;++ // this gets reset every time a command is issued, except an unload: dropping the passengers+ // on the pad is no reason to stop being repaired there.+ if (parms->m_cmd != AICMD_EVACUATE && parms->m_cmd != AICMD_EXIT)+ setAirfieldForHealing(INVALID_ID);if (!isAllowedToRespondToAiCommands(parms))return;diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cppindex a00ef2834..8c651ac11 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/DozerAIUpdate.cpp@@ -1204,6 +1204,18 @@ StateReturnType DozerPrimaryIdleState::update( void )if( !ai->isIdle() )m_idleTooLongTimestamp = TheGameLogic->getFrame();+ //+ // Inside a tunnel, a transport or a garrison a builder can reach nothing. It used to look for work+ // from in there all the same: a Worker sent into a tunnel on its way to a foundation took that+ // foundation back up a second later, and one loaded into a truck beside a site went on building it.+ // The idle clock starts again when it comes out.+ //+ if( dozer->getContainedBy() )+ {+ m_idleTooLongTimestamp = TheGameLogic->getFrame();+ return STATE_CONTINUE;+ }+//// a builder that has just gone idle next to an unfinished structure nobody is working on// (its own next one, an abandoned one, a dead dozer's) picks that job up. A second's@@ -1728,7 +1740,12 @@ UpdateSleepTime DozerAIUpdate::update( void )if( currentTask == DOZER_TASK_REPAIR &&TheActionManager->canRepairObject( getObject(), targetObject, getLastCommandSource() ) == FALSE )invalidTask = TRUE;-++ // a job cannot be done from inside a container; the build step took "not moving" for "arrived"+ // and went on building from wherever the container stood+ if( getObject()->getContainedBy() )+ invalidTask = TRUE;+// cancel the task if it's now invalidif( invalidTask == TRUE )cancelTask( currentTask );@@ -2258,18 +2275,25 @@ void DozerAIUpdate::internalCancelTask( DozerTask task )// call the single method that gets called for completing and canceling tasksinternalTaskCompleteOrCancelled( task );+ const ObjectID cancelledTargetID = m_task[ task ].m_targetObjectID;+// remove the info for this taskm_task[ task ].m_targetObjectID = INVALID_ID;m_task[ task ].m_taskOrderFrame = 0;-+// remove dock point info for this taskfor( Int i = 0; i < DOZER_NUM_DOCK_POINTS; i++ )m_dockPoint[ task ][ i ].valid = FALSE;-+// stop the dozer from movingAIUpdateInterface *ai = getObject()->getAIUpdateInterface();ai->aiIdle( CMD_FROM_AI );+ // The walk to the building ignored it as an obstacle, and only arriving cleared that. A move+ // ordered before arriving would path straight through the building.+ if( ai->getIgnoredObstacleID() == cancelledTargetID )+ ai->ignoreObstacle( NULL );+} // end internalCancelTask// ------------------------------------------------------------------------------------------------@@ -2296,6 +2320,10 @@ void DozerAIUpdate::internalTaskCompleteOrCancelled( DozerTask task )// the builder is no longer actively building somethinggetObject()->clearModelConditionState( MODELCONDITION_ACTIVELY_CONSTRUCTING );+ // and the site's construction loop goes with it: a builder stopped halfway left it playing,+ // and resuming the build stacked a second one on top+ finishBuildingSound();+// And the thing we were working on is no longer being actively built///@todo This would be correct except that we don't have idle crane animations and it is December.@@ -2560,6 +2588,8 @@ void DozerAIUpdate::aiDoCommand(const AICommandParms* parms)//------------------------------------------------------------------------------------------------void DozerAIUpdate::startBuildingSound( const AudioEventRTS *sound, ObjectID constructionSiteID ){+ // the handle is the only way to stop the loop, so drop the last one before it is overwritten+ TheAudio->removeAudioEvent( m_buildingSound.getPlayingHandle() );m_buildingSound = *sound;m_buildingSound.setObjectID( constructionSiteID );m_buildingSound.setPlayingHandle( TheAudio->addAudioEvent( &m_buildingSound ) );diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cppindex bb434b113..e30560cc6 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/JetAIUpdate.cpp@@ -2442,8 +2442,9 @@ void JetAIUpdate::privateGetRepaired( Object *repairDepot, CommandSourceType cmd//-------------------------------------------------------------------------------------------------Bool JetAIUpdate::isParkedAt(const Object* obj) const{+ // Helipad units count too: a Comanche on the pad has that airfield as its producer, and one told+ // to repair at the pad it was already repairing on took off and flew a circuit back to it.if (!getFlag(ALLOW_AIR_LOCO) &&- !getObject()->isKindOf(KINDOF_PRODUCED_AT_HELIPAD) &&obj != NULL){Object* airfield;diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/MissileAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/MissileAIUpdate.cppindex 3898d9378..66d402aa5 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/MissileAIUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/MissileAIUpdate.cpp@@ -247,7 +247,15 @@ void MissileAIUpdate::projectileFireAtObjectOrPosition( const Object *victim, coVector3 dir = getObject()->getTransformMatrix()->Get_X_Vector();dir.Normalize();- dir.Z += 2*zFactor;+ // A target above us gets a loft of twice its slope. The launch direction already carries a+ // pitched turret's aim, though, and the loft went on top of it: a Dragon Tank flaming a bunker+ // up a slope sent the flames over the roof, and a flame that never touches the building clears+ // nobody out of it. The loft now makes up only the climb the launch still lacks, which is all+ // of it for a barrel that does not pitch.+ const Real launchRun = sqrtf(sqr(dir.X) + sqr(dir.Y));+ const Real launchSlope = (launchRun > 0.0f) ? dir.Z / launchRun : zFactor;+ if (zFactor > launchSlope)+ dir.Z += 2*(zFactor - (launchSlope > 0.0f ? launchSlope : 0.0f));dir.Normalize();PhysicsBehavior* physics = getObject()->getPhysics();if (physics && initialVelToUse > 0)diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/RailroadGuideAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/RailroadGuideAIUpdate.cppindex c7fdc7103..e3d8af5d5 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/RailroadGuideAIUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/RailroadGuideAIUpdate.cpp@@ -571,6 +571,9 @@ void RailroadBehavior::loadTrackData( void )m_track->m_length = 0.0f;Waypoint *scanner = anchorWaypoint;Real distFromTo = 0.0f;+ std::set<WaypointID> visited; // every waypoint already on the track+ if ( scanner )+ visited.insert( scanner->getID() );//Let's start buliding our own track data from the waypoint data we find@@ -639,6 +642,12 @@ void RailroadBehavior::loadTrackData( void )m_track->m_isLooping = TRUE;break; // it must be a looping track. Cool.}++ // A path that loops back to some waypoint other than the anchor never met the test above and+ // grew the track until memory ran out: the map attached to upstream #1324 crashed on load.+ // The track ends where it would start repeating.+ if ( scanner && !visited.insert( scanner->getID() ).second )+ break;}} // end loadTrackDatadiff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cppindex 9b0308e7b..4e8298751 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/AIUpdate/WorkerAIUpdate.cpp@@ -315,7 +315,11 @@ UpdateSleepTime WorkerAIUpdate::update( void )if( currentTask == DOZER_TASK_REPAIR &&TheActionManager->canRepairObject( getObject(), targetObject, getLastCommandSource() ) == FALSE )invalidTask = TRUE;-++ // as in DozerAIUpdate::update: no job is done from inside a tunnel, a transport or a garrison+ if( getObject()->getContainedBy() )+ invalidTask = TRUE;+// cancel the task if it's now invalidif( invalidTask == TRUE )cancelTask( currentTask );@@ -824,14 +828,16 @@ void WorkerAIUpdate::internalCancelTask( DozerTask task )// call the single method that gets called for completing and canceling tasksinternalTaskCompleteOrCancelled( task );+ const ObjectID cancelledTargetID = m_task[ task ].m_targetObjectID;+// remove the info for this taskm_task[ task ].m_targetObjectID = INVALID_ID;m_task[ task ].m_taskOrderFrame = 0;-+// remove dock point info for this taskfor( Int i = 0; i < DOZER_NUM_DOCK_POINTS; i++ )m_dockPoint[ task ][ i ].valid = FALSE;-+// stop the dozer from movingAIUpdateInterface *ai = getObject()->getAIUpdateInterface();if( !ai )@@ -841,6 +847,10 @@ void WorkerAIUpdate::internalCancelTask( DozerTask task )/// @todo we really need a stop command instead of making it move to it's current locationai->aiMoveToPosition( getObject()->getPosition(), CMD_FROM_AI );+ // see DozerAIUpdate::internalCancelTask: the building stays an obstacle once the walk to it is off+ if( ai->getIgnoredObstacleID() == cancelledTargetID )+ ai->ignoreObstacle( NULL );+}// ------------------------------------------------------------------------------------------------@@ -866,6 +876,9 @@ void WorkerAIUpdate::internalTaskCompleteOrCancelled( DozerTask task )// the builder is no longer actively building somethinggetObject()->clearModelConditionState( MODELCONDITION_ACTIVELY_CONSTRUCTING );+ // see DozerAIUpdate::internalTaskCompleteOrCancelled+ finishBuildingSound();+//// WorkersReturnToSupply: a worker pulled off a supply run to put up a building used to// just stand there when it finished. Send it back to the dock it came from, if that@@ -1446,6 +1459,8 @@ void WorkerAIUpdate::removeBridgeScaffolding( Object *bridgeTower )//------------------------------------------------------------------------------------------------void WorkerAIUpdate::startBuildingSound( const AudioEventRTS *sound, ObjectID constructionSiteID ){+ // the handle is the only way to stop the loop, so drop the last one before it is overwritten+ TheAudio->removeAudioEvent( m_buildingSound.getPlayingHandle() );m_buildingSound = *sound;m_buildingSound.setObjectID( constructionSiteID );m_buildingSound.setPlayingHandle( TheAudio->addAudioEvent( &m_buildingSound ) );diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/DockUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/DockUpdate.cppindex c28377a59..cf9371342 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/DockUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/DockUpdate/DockUpdate.cpp@@ -506,6 +506,7 @@ Coord3D DockUpdate::computeApproachPosition( Int positionIndex, Object *forWhomfpOptions.minRadius = 0.0f;fpOptions.maxRadius = 100.0f;fpOptions.sourceToPathToDest = forWhom;// This makes it find a place forWhom can get to.+ fpOptions.relationshipObject = forWhom;// ... and one its own side's mines do not rule outif( forWhom->isUsingAirborneLocomotor() )fpOptions.ignoreObject = getObject();// Flyers can ignore us, so they can approach right over us if they want.diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cppindex b3c6d041a..1cc90cc2a 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HelicopterSlowDeathUpdate.cpp@@ -455,6 +455,15 @@ UpdateSleepTime HelicopterSlowDeathBehavior::update( void )// mark the frame we hit the ground onm_hitGroundFrame = TheGameLogic->getFrame();+ // A copter down before its blades flew off never reached the ejection above, which only+ // runs in the air: a veteran Comanche shot down low lost its pilot (upstream #175).+ if( m_bladeFlyOffFrame > 0 )+ {+ m_bladeFlyOffFrame = 0;+ if( modData->m_oclEjectPilot && copter->getVeterancyLevel() > LEVEL_REGULAR )+ EjectPilotDie::ejectPilot( modData->m_oclEjectPilot, copter, NULL );+ }+// make hit ground effectFXList::doFXObj( modData->m_fxHitGround, copter );ObjectCreationList::create( modData->m_oclHitGround, copter, NULL );diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cppindex 34e9eb94c..0dc5c8c05 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/HordeUpdate.cpp@@ -269,10 +269,22 @@ UpdateSleepTime HordeUpdate::update( void )PartitionFilterHordeMember hmFilter(getObject(), md);PartitionFilter *filters[] = { &hmFilter, NULL };- SimpleObjectIterator *iter = ThePartitionManager->iterateObjectsInRange(getObject(), md->m_minDist, FROM_BOUNDINGSPHERE_3D, filters);+ // RubOffRadius reaches further than Radius (150 against 75 on the Battlemaster), but the+ // honorary-member test below only ever saw the units inside Radius, so a tank that close to a+ // true member never got the horde. Walk the larger of the two, count only inside Radius.+ const Real scanRadius = max( md->m_minDist, md->m_rubOffRadius );+ SimpleObjectIterator *iter = ThePartitionManager->iterateObjectsInRange(getObject(), scanRadius, FROM_BOUNDINGSPHERE_3D, filters);MemoryPoolObjectHolder hold(iter);- if ((iter->getCount() >= md->m_minCount - 1) )//we really are in the thick part of the horde+ const Real minDistSq = sqr( md->m_minDist );+ Int nearby = 0;+ for (Object* other = iter->first(); other; other = iter->next())+ {+ if (ThePartitionManager->getDistanceSquared(getObject(), other, FROM_BOUNDINGSPHERE_3D) <= minDistSq)+ ++nearby;+ }++ if ((nearby >= md->m_minCount - 1) )//we really are in the thick part of the horde{m_inHorde = TRUE;m_trueHordeMember = TRUE;diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/LaserUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/LaserUpdate.cppindex bc3806189..fd1af0fcf 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/LaserUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/LaserUpdate.cpp@@ -202,6 +202,15 @@ void LaserUpdate::clientUpdate( void )updateStartPos();updateEndPos();+ // The muzzle flare and the target burst were placed once, in initLaser, and never moved again,+ // so on a moving Avenger or Laser Crusader they were left a frame behind the beam they belong to.+ ParticleSystem *system = TheParticleSystemManager->findParticleSystem( m_particleSystemID );+ if( system )+ system->setPosition( &m_startPos );+ system = TheParticleSystemManager->findParticleSystem( m_targetParticleSystemID );+ if( system )+ system->setPosition( &m_endPos );+if( m_decaying || m_widening ){m_currentWidthScalar = computeWidthScalar( TheGameLogic->getFrame() );diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cppindex 4045f09f4..b6479f60e 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/ProductionUpdate.cpp@@ -162,6 +162,7 @@ ProductionEntry::ProductionEntry( void )m_productionID = (ProductionID)1;m_percentComplete = 0.0f;m_framesUnderConstruction = 0;+ m_totalProductionFrames = 0;m_next = NULL;m_prev = NULL;//Added By Sadullah Nader@@ -805,9 +806,6 @@ UpdateSleepTime ProductionUpdate::update( void )} // end if- // increase the frames we've been under production for- production->m_framesUnderConstruction++;-// how many total logic frames does it take to produce this unitInt totalProductionFrames;if( production->m_type == PRODUCTION_UNIT )@@ -815,6 +813,19 @@ UpdateSleepTime ProductionUpdate::update( void )elsetotalProductionFrames = production->m_upgradeToResearch->calcTimeToBuild( player );+ //+ // The build time moves with power, the factory count and the rest. Rescale the frames already+ // done to the new time so the fraction finished carries over. Measuring the old count against+ // the new time applied the new rate to the whole build: a first power plant finished a half-built+ // dozer on the spot, and losing power sent a progress bar backwards.+ //+ if( production->m_totalProductionFrames > 0 && totalProductionFrames != production->m_totalProductionFrames )+ production->m_framesUnderConstruction = production->m_framesUnderConstruction * totalProductionFrames / production->m_totalProductionFrames;+ production->m_totalProductionFrames = totalProductionFrames;++ // increase the frames we've been under production for+ production->m_framesUnderConstruction++;+// figure out our percent completeproduction->m_percentComplete = INT_TO_REAL( production->m_framesUnderConstruction ) /INT_TO_REAL( totalProductionFrames ) *@@ -1350,7 +1361,8 @@ void ProductionUpdate::xfer( Xfer *xfer )// version// 2: each entry carries what was paid for it- XferVersion currentVersion = 2;+ // 3: each entry carries the build time its frame count was measured against+ XferVersion currentVersion = 3;XferVersion version = currentVersion;xfer->xferVersion( &version, currentVersion );@@ -1404,6 +1416,9 @@ void ProductionUpdate::xfer( Xfer *xfer )// cost paidxfer->xferUnsignedInt( &production->m_costPaid );+ // build time the frame count was measured against+ xfer->xferInt( &production->m_totalProductionFrames );+} // end for} // end if, save@@ -1501,6 +1516,10 @@ void ProductionUpdate::xfer( Xfer *xfer )elseproduction->m_costPaid = production->m_upgradeToResearch->calcCostToBuild( getObject()->getControllingPlayer() );+ // an older save leaves it 0, and the first update measures against whatever it finds+ if( version >= 3 )+ xfer->xferInt( &production->m_totalProductionFrames );+} // end for, i} // end else, loaddiff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpectreGunshipUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpectreGunshipUpdate.cppindex 73b7fc1bf..91dfb8a2f 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpectreGunshipUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/SpectreGunshipUpdate.cpp@@ -336,8 +336,10 @@ public:if (objOther->isEffectivelyDead())return false;- // this is also way fast (bit test) so do it next.- if (objOther->isOffMap() != m_obj->isOffMap())+ // this is also way fast (bit test) so do it next. The targets are on the map whatever the+ // ship is: it orbits past the edge, and comparing its own off-map bit with the target's+ // left the gattling with nothing to shoot for as long as the orbit was outside.+ if (objOther->isOffMap())return false;Relationship r = m_obj->getRelationship(objOther);diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthDetectorUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthDetectorUpdate.cppindex b03784bbb..44f049dbd 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthDetectorUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthDetectorUpdate.cpp@@ -134,6 +134,10 @@ Bool PartitionFilterStealthedOrStealthGarrisoned::allow( Object *objOther)if( objOther->getStatusBits().test( OBJECT_STATUS_STEALTHED ) )return TRUE;+ // visible for now (firing, moving), but it will stealth again; see the loop in update()+ if( objOther->getStatusBits().test( OBJECT_STATUS_CAN_STEALTH ) )+ return TRUE;+ContainModuleInterface *contain = objOther->getContain();if( contain && contain->isGarrisonable() && contain->getStealthUnitsContained() )return TRUE;@@ -209,7 +213,16 @@ UpdateSleepTime StealthDetectorUpdate::update( void )continue;StealthUpdate* stealth = them->getStealth();- if ( stealth )+ if ( stealth && !them->testStatus( OBJECT_STATUS_STEALTHED ) )+ {+ // A stealth unit in plain sight (a GPS-scrambled Quad firing) keeps its detection running,+ // quietly. Skipped until it stealthed again, it came back stealthed and undetected until+ // this detector's next scan, invisible for those frames, and every attack on it dropped.+ stealth->keepDetected( data->m_updateRate + 1 );+ continue;+ }++ if ( stealth ){// we have found someonediff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cppindex 34613880f..da7536b38 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Update/StealthUpdate.cpp@@ -954,6 +954,14 @@ void StealthUpdate::markAsDetected(UnsignedInt numFrames)}}+//-------------------------------------------------------------------------------------------------+void StealthUpdate::keepDetected( UnsignedInt numFrames )+{+ const UnsignedInt expires = TheGameLogic->getFrame() + numFrames;+ if( m_detectionExpiresFrame < expires )+ m_detectionExpiresFrame = expires;+}+//-------------------------------------------------------------------------------------------------void StealthUpdate::disguiseAsObject( const Object *target ){diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/MaxHealthUpgrade.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/MaxHealthUpgrade.cppindex 59015144e..c69179f61 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/MaxHealthUpgrade.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/MaxHealthUpgrade.cpp@@ -81,13 +81,16 @@ void MaxHealthUpgrade::upgradeImplementation( ){const MaxHealthUpgradeModuleData *data = getMaxHealthUpgradeModuleData();- //Simply add the xp scalar to the xp tracker!Object *obj = getObject();BodyModuleInterface *body = obj->getBodyModule();if( body ){- body->setMaxHealth( body->getMaxHealth() + data->m_addMaxHealth, data->m_maxHealthChangeType );+ // Veterancy multiplies max health when it arrives, so an addition made after a promotion has+ // to carry the promotion's bonus too. Without it an Elite Paladin that researched Composite+ // Armor ended on 750 where one armored first and promoted later ended on 780.+ Real add = data->m_addMaxHealth * TheGlobalData->m_healthBonus[ obj->getVeterancyLevel() ];+ body->setMaxHealth( body->getMaxHealth() + add, data->m_maxHealthChangeType );}}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/ReplaceObjectUpgrade.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/ReplaceObjectUpgrade.cppindex 91ec4ee4b..df03a4dee 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/ReplaceObjectUpgrade.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Upgrade/ReplaceObjectUpgrade.cpp@@ -104,6 +104,8 @@ void ReplaceObjectUpgrade::upgradeImplementation( )if( replacementObject->getControllingPlayer() ){+ // made finished, so joining the team already counted its power; the completion counts it again+ replacementObject->friend_adjustPowerForPlayer(FALSE);replacementObject->getControllingPlayer()->onStructureConstructionComplete(me, replacementObject, FALSE);}}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cppindex bfed8cdea..278e06984 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/Weapon.cpp@@ -457,14 +457,13 @@ void WeaponTemplate::postProcessLoad()DEBUG_ASSERTCRASH(m_projectileTmpl, ("projectile %s not found!",m_projectileName.str()));}+ // The OCL names are cleared once they are resolved, so a name that is empty here was either never+ // given (the pointer is still NULL from the constructor) or resolved by an earlier pass. A map.ini+ // runs this pass again after the game's own, and it must not drop the OCLs it did not name.for (Int i = LEVEL_FIRST; i <= LEVEL_LAST; ++i){// And the OCL if there is one- if (m_fireOCLNames[i].isEmpty())- {- m_fireOCLs[i] = NULL;- }- else+ if (m_fireOCLNames[i].isNotEmpty()){m_fireOCLs[i] = TheObjectCreationListStore->findObjectCreationList(m_fireOCLNames[i].str() );DEBUG_ASSERTCRASH(m_fireOCLs[i], ("OCL %s not found in a weapon!",m_fireOCLNames[i].str()));@@ -472,11 +471,7 @@ void WeaponTemplate::postProcessLoad()m_fireOCLNames[i].clear();// And the other OCL if there is one- if (m_projectileDetonationOCLNames[i].isEmpty() )- {- m_projectileDetonationOCLs[i] = NULL;- }- else+ if (m_projectileDetonationOCLNames[i].isNotEmpty() ){m_projectileDetonationOCLs[i] = TheObjectCreationListStore->findObjectCreationList(m_projectileDetonationOCLNames[i].str() );DEBUG_ASSERTCRASH(m_projectileDetonationOCLs[i], ("OCL %s not found in a weapon!",m_projectileDetonationOCLNames[i].str()));@@ -1601,6 +1596,7 @@ WeaponStore::WeaponStore()WeaponStore::~WeaponStore(){deleteAllDelayedDamage();+ deleteWeaponsNow();for (Int i = 0; i < m_weaponTemplateVector.size(); i++){@@ -1686,22 +1682,34 @@ WeaponTemplate *WeaponStore::newWeaponTemplate(AsciiString name)}//-------------------------------------------------------------------------------------------------+/* A map.ini block for a weapon that already exists. EA parsed it into a copy that nothing ever+ pointed at - not the store, not the object templates, which hold the original by pointer - so a+ map could add weapons but every change to an existing one was lost. The block now edits the+ original, and the original's first state is kept aside for reset() to put back after the match. */WeaponTemplate *WeaponStore::newOverride(WeaponTemplate *weaponTemplate){- if (!weaponTemplate)- return NULL;-- // allocate a new weapon- WeaponTemplate *wt = newInstance(WeaponTemplate);- (*wt) = (*weaponTemplate);- (wt)->friend_setNextTemplate(weaponTemplate);-- return wt;-}+ if (!weaponTemplate->isOverride())+ {+ WeaponTemplate *pristine = newInstance(WeaponTemplate);+ (*pristine) = (*weaponTemplate);+ weaponTemplate->friend_setNextTemplate(pristine);+ // the copy shares the extra-bonus set, and a WeaponBonus line edits that set in place+ if (pristine->m_extraBonus)+ {+ weaponTemplate->m_extraBonus = newInstance(WeaponBonusSet);+ (*weaponTemplate->m_extraBonus) = (*pristine->m_extraBonus);+ }+ }++ return weaponTemplate;+}//-------------------------------------------------------------------------------------------------void WeaponStore::update(){+ // end of the logic frame: nothing is firing any more+ deleteWeaponsNow();+for (std::list<WeaponDelayedDamageInfo>::iterator ddi = m_weaponDDI.begin(); ddi != m_weaponDDI.end(); ){UnsignedInt curFrame = TheGameLogic->getFrame();@@ -1727,6 +1735,14 @@ void WeaponStore::deleteAllDelayedDamage()m_weaponDDI.clear();}+//-------------------------------------------------------------------------------------------------+void WeaponStore::deleteWeaponsNow()+{+ for (size_t i = 0; i < m_weaponsToDelete.size(); ++i)+ m_weaponsToDelete[i]->deleteInstance();+ m_weaponsToDelete.clear();+}+// ------------------------------------------------------------------------------------------------void WeaponStore::resetWeaponTemplates( void ){@@ -1742,19 +1758,23 @@ void WeaponStore::resetWeaponTemplates( void )//-------------------------------------------------------------------------------------------------void WeaponStore::reset(){- // clean up any overriddes.+ // put back every weapon a map.ini edited (see newOverride)for (Int i = 0; i < m_weaponTemplateVector.size(); ++i){WeaponTemplate *wt = m_weaponTemplateVector[i];- if (wt->isOverride())+ if (wt->isOverride()){- WeaponTemplate *override = wt;- wt = wt->friend_clearNextTemplate();- override->deleteInstance();+ WeaponTemplate *pristine = wt->friend_clearNextTemplate();+ if (wt->m_extraBonus)+ wt->m_extraBonus->deleteInstance();+ (*wt) = (*pristine);+ pristine->m_extraBonus = NULL; // wt owns it again+ pristine->deleteInstance();}}deleteAllDelayedDamage();+ deleteWeaponsNow();IncomingDamageTracker::reset();resetWeaponTemplates();}@@ -1772,6 +1792,117 @@ void WeaponStore::setDelayedDamage(const WeaponTemplate *weapon, const Coord3D*m_weaponDDI.push_back(wi);}+//-------------------------------------------------------------------------------------------------+/** Weapons are named the way Weapon::xfer names them, and found again the way it finds them. */+static WeaponTemplate *xferWeaponTemplateName( Xfer *xfer, const WeaponTemplate *wt )+{+ AsciiString name;+ if( xfer->getXferMode() == XFER_SAVE )+ name = wt->getName();+ xfer->xferAsciiString( &name );+ if( xfer->getXferMode() == XFER_SAVE )+ return NULL;++ WeaponTemplate *found = (WeaponTemplate *)TheWeaponStore->findWeaponTemplate( name );+ if( found == NULL )+ {+ DEBUG_CRASH(( "WeaponStore::xfer - weapon '%s' in the save is not defined\n", name.str() ));+ throw INI_INVALID_DATA;+ }+ return found;+}++//-------------------------------------------------------------------------------------------------+void WeaponStore::xfer( Xfer *xfer )+{+ const XferVersion currentVersion = 1;+ XferVersion version = currentVersion;+ xfer->xferVersion( &version, currentVersion );++ // the historic hits of every weapon that has any+ UnsignedShort historyCount = 0;+ if( xfer->getXferMode() == XFER_SAVE )+ {+ for( size_t i = 0; i < m_weaponTemplateVector.size(); ++i )+ if( !m_weaponTemplateVector[i]->m_historicDamage.empty() )+ ++historyCount;+ }+ xfer->xferUnsignedShort( &historyCount );++ size_t next = 0;+ for( UnsignedShort h = 0; h < historyCount; ++h )+ {+ WeaponTemplate *wt = NULL;+ if( xfer->getXferMode() == XFER_SAVE )+ {+ while( m_weaponTemplateVector[next]->m_historicDamage.empty() )+ ++next;+ wt = m_weaponTemplateVector[next++];+ xferWeaponTemplateName( xfer, wt );+ }+ else+ {+ wt = xferWeaponTemplateName( xfer, NULL );+ wt->m_historicDamage.clear();+ }++ xfer->xferUnsignedInt( &wt->m_historicDamageTriggerId );++ UnsignedShort hitCount = (UnsignedShort)wt->m_historicDamage.size();+ xfer->xferUnsignedShort( &hitCount );+ if( xfer->getXferMode() == XFER_SAVE )+ {+ for( HistoricWeaponDamageList::iterator it = wt->m_historicDamage.begin(); it != wt->m_historicDamage.end(); ++it )+ {+ xfer->xferUnsignedInt( &it->frame );+ xfer->xferCoord3D( &it->location );+ xfer->xferUnsignedInt( &it->triggerId );+ }+ }+ else+ {+ for( UnsignedShort n = 0; n < hitCount; ++n )+ {+ HistoricWeaponDamageInfo hit( 0, Coord3D() );+ xfer->xferUnsignedInt( &hit.frame );+ xfer->xferCoord3D( &hit.location );+ xfer->xferUnsignedInt( &hit.triggerId );+ wt->m_historicDamage.push_back( hit );+ }+ }+ }++ // the delayed damage still in flight+ UnsignedShort delayedCount = (UnsignedShort)m_weaponDDI.size();+ xfer->xferUnsignedShort( &delayedCount );+ if( xfer->getXferMode() != XFER_SAVE )+ m_weaponDDI.clear();++ std::list<WeaponDelayedDamageInfo>::iterator ddi = m_weaponDDI.begin();+ for( UnsignedShort d = 0; d < delayedCount; ++d )+ {+ WeaponDelayedDamageInfo loaded;+ WeaponDelayedDamageInfo &info = ( xfer->getXferMode() == XFER_SAVE ) ? *ddi++ : loaded;++ WeaponTemplate *wt = xferWeaponTemplateName( xfer, info.m_delayedWeapon );+ if( xfer->getXferMode() != XFER_SAVE )+ info.m_delayedWeapon = wt;+ xfer->xferCoord3D( &info.m_delayDamagePos );+ xfer->xferUnsignedInt( &info.m_delayDamageFrame );+ xfer->xferObjectID( &info.m_delaySourceID );+ xfer->xferObjectID( &info.m_delayIntendedVictimID );+ for( Int f = 0; f < WeaponBonus::FIELD_COUNT; ++f )+ {+ Real value = info.m_bonus.getField( (WeaponBonus::Field)f );+ xfer->xferReal( &value );+ info.m_bonus.setField( (WeaponBonus::Field)f, value );+ }++ if( xfer->getXferMode() != XFER_SAVE )+ m_weaponDDI.push_back( info );+ }+}+//-------------------------------------------------------------------------------------------------void WeaponStore::postProcessLoad(){diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/WeaponSet.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/WeaponSet.cppindex 2a6df01a1..18f2b9c51 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/WeaponSet.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/WeaponSet.cpp@@ -331,7 +331,10 @@ void WeaponSet::updateWeaponSet(const Object* obj){if (m_weapons[i] != NULL){- m_weapons[i]->deleteInstance();+ // Not deleted here: this runs inside the weapon's own fire when the shot kills, the kill+ // promotes the shooter and the promotion swaps the weapon set (an Angry Mob member on+ // its way to Veteran). privateFireWeapon then wrote into the freed Weapon.+ TheWeaponStore->deleteWeaponLater(m_weapons[i]);m_weapons[i] = NULL;}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cppindex b3075e7ac..802fb9946 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/ScriptActions.cpp@@ -3021,12 +3021,13 @@ void ScriptActions::doCameraMotionBlur(Bool zoomIn, Bool saturate)static PlayerMaskType getHumanPlayerMask( void ){- PlayerMaskType mask;+ // was uninitialised and and-ed, so the set came off the stack and differed per machine+ PlayerMaskType mask = 0;for (Int i=0; i<ThePlayerList->getPlayerCount(); ++i){const Player *player = ThePlayerList->getNthPlayer(i);if (player->getPlayerType() == PLAYER_HUMAN)- mask &= player->getPlayerMask();+ mask |= player->getPlayerMask();}//DEBUG_LOG(("getHumanPlayerMask(): mask was %4.4X\n", mask));diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cppindex af6c403dd..deb2d7ffd 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp@@ -575,6 +575,10 @@ static void placeNetworkBuildingsForPlayer(Int slotNum, const GameSlot *pSlot, Preturn;pPlayer->onStructureCreated(NULL, conYard);+ // placeObjectAtPosition made it finished, so joining the team already counted its power, and+ // onStructureConstructionComplete counts it again: a command center given EnergyProduction+ // started every player at twice that, and the spare half stayed after it was sold+ conYard->friend_adjustPowerForPlayer(FALSE);pPlayer->onStructureConstructionComplete(NULL, conYard, FALSE);//pos.x -= conYard->getGeometryInfo().getBoundingSphereRadius()/2;@@ -2571,7 +2575,14 @@ void GameLogic::loadMapINI( AsciiString mapName )DEBUG_LOG(("%s does not parse, the rest of it is ignored\n", fullFledgeFilename));}}-++ // A weapon's projectile and OCLs are names until the store's post-process pass turns them into+ // pointers, and that pass ran once at startup, before any map. A weapon a map.ini made or edited+ // kept the names only, and every unit carrying it refused to fire.+ TheWeaponStore->postProcessLoad();+ // the same for a command button's picture, which the bar looked up once at startup+ TheControlBar->postProcessCommands();+// No error here. There could've just *not* been a map.ini file.// now look for a string file@@ -5371,7 +5382,10 @@ void GameLogic::initTimeOutValues( void ){if (!TheNetwork)return;- for(Int i = 0; i < TheNetwork->getNumPlayers(); ++i)+ // every slot: these are indexed by slot, and counting players left a human in a slot past the+ // head count at 0, timed out before his first progress message, so whoever loaded first could+ // start the match without him+ for(Int i = 0; i < MAX_SLOTS; ++i){m_progressCompleteTimeout[i] = timeGetTime();}diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Connection.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Connection.cppindex 393021d10..4b515fd78 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Connection.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Connection.cpp@@ -29,7 +29,11 @@#include "GameNetwork/NetworkUtil.h"#include "GameLogic/GameLogic.h"-enum { MaxQuitFlushTime = 30000 }; // wait this many milliseconds at most to retry things before quitting+// wait this many milliseconds at most to retry things before quitting. EA's 30 seconds held the+// victory screen that long whenever the last opponent had already left: nobody acks the commands+// still queued for a player who is gone, so the queue only ever empties on this timeout. Five+// seconds is still some twenty round trips at 250 ms for our own leave to get through.+enum { MaxQuitFlushTime = 5000 };/*** Jacobson/Karels. See the comment on CONNECTION_MIN_RETRY_TIME in Connection.h for why the flatdiff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GUIUtil.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GUIUtil.cppindex a4769147b..556667590 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/GUIUtil.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/GUIUtil.cpp@@ -406,10 +406,11 @@ void PopulateStartingCashComboBox(GameWindow *comboBox, GameInfo *myGame)if ( currentSelectionIndex == -1 ){- DEBUG_CRASH( ("Current selection for starting cash not found in list") );- currentSelectionIndex = GadgetComboBoxAddEntry(comboBox, formatMoneyForStartingCashComboBox( myGame->getStartingCash() ),+ // a StartingCash from the player's own INI that Multiplayer.ini does not list: show it as an+ // entry of its own. The item data read the loop's end iterator here.+ currentSelectionIndex = GadgetComboBoxAddEntry(comboBox, formatMoneyForStartingCashComboBox( myGame->getStartingCash() ),comboBox->winGetEnabled() ? comboBox->winGetEnabledTextColor() : comboBox->winGetDisabledTextColor());- GadgetComboBoxSetItemData(comboBox, currentSelectionIndex, (void *)it->countMoney() );+ GadgetComboBoxSetItemData(comboBox, currentSelectionIndex, (void *)myGame->getStartingCash().countMoney() );}GadgetComboBoxSetSelectedPos(comboBox, currentSelectionIndex);diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/NetworkUtil.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/NetworkUtil.cppindex dc4b0ba59..664cee712 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/NetworkUtil.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/NetworkUtil.cpp@@ -418,11 +418,30 @@ Bool IsValidTransferFileContent(const AsciiString &filePath, const UnsignedBytereturn FALSE;}const UnsignedByte *sig = data + dataSize - (TGA2_SIGNATURE_LEN + 2);- if (memcmp(sig, TGA2_SIGNATURE, TGA2_SIGNATURE_LEN) != 0- || sig[TGA2_SIGNATURE_LEN] != '.'- || sig[TGA2_SIGNATURE_LEN + 1] != '\0')+ if (memcmp(sig, TGA2_SIGNATURE, TGA2_SIGNATURE_LEN) == 0+ && sig[TGA2_SIGNATURE_LEN] == '.'+ && sig[TGA2_SIGNATURE_LEN + 1] == '\0'){- DEBUG_LOG(("TGA file '%s' has no TRUEVISION-XFILE footer\n", filePath.str()));+ break;+ }++ // The footer is Targa 2.0 and a 1.0 file has none, which is every preview a paint program+ // saves that way. Refusing those sent no progress back, and the host sat out the whole+ // two minute timeout and called the map transfer failed. Without a footer the header has+ // to hold up instead: a real image type, a size, a pixel depth, and for an uncompressed+ // image the pixels it promises. Read by offset, the struct is not packed.+ const UnsignedByte imageType = data[2];+ const UnsignedInt width = data[12] | (data[13] << 8);+ const UnsignedInt height = data[14] | (data[15] << 8);+ const UnsignedByte pixelDepth = data[16];+ const Bool knownType = imageType == TGA_CMAPPED || imageType == TGA_TRUECOLOR || imageType == TGA_MONO+ || imageType == TGA_CMAPPED_ENCODED || imageType == TGA_TRUECOLOR_ENCODED || imageType == TGA_MONO_ENCODED;+ const Bool knownDepth = pixelDepth == 8 || pixelDepth == 15 || pixelDepth == 16 || pixelDepth == 24 || pixelDepth == 32;+ const Bool encoded = imageType >= TGA_CMAPPED_ENCODED;+ if (!knownType || !knownDepth || width == 0 || height == 0+ || (!encoded && 18 + data[0] + (Int64)width * height * ((pixelDepth + 7) / 8) > (Int64)dataSize))+ {+ DEBUG_LOG(("TGA file '%s' has no TRUEVISION-XFILE footer and no header that holds up\n", filePath.str()));return FALSE;}break;diff --git a/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp b/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cppindex 459238c4c..06d2a7151 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp@@ -58,10 +58,12 @@#include "GameClient/DebugDisplay.h"#include "GameClient/Drawable.h"#include "GameClient/GameClient.h"+#include "GameClient/ObserverCamera.h"#include "GameClient/VideoPlayer.h"#include "GameClient/View.h"#include "GameLogic/GameLogic.h"+#include "GameLogic/PartitionManager.h"#include "GameLogic/TerrainLogic.h"#include "Common/File.h"@@ -2550,13 +2552,26 @@ void MilesAudioManager::processPlayingList( void )Real volForConsideration = getEffectiveVolume(playing->m_audioEventRTS);volForConsideration /= (m_sound3DVolume > 0.0f ? m_soundVolume : 1.0f);Bool playAnyways = BitTest( playing->m_audioEventRTS->getAudioEventInfo()->m_type, ST_GLOBAL) || playing->m_audioEventRTS->getAudioEventInfo()->m_priority == AP_CRITICAL;- if( volForConsideration < m_audioSettings->m_minVolume && !playAnyways )+ if( volForConsideration < m_audioSettings->m_minVolume && !playAnyways ){// don't want to get an additional callback for this sampleAIL_register_3D_EOS_callback(playing->m_3DSample, NULL);stopPlayingAudio( playing );continue;}+ // canPlayNow keeps a shrouded sound from starting in the fog, but a loop that started+ // in the open played on after its source flew into the fog: an enemy Helix or Comanche+ // could be heard, and followed, where it could not be seen. Stopped like one out of+ // range, and the drawable starts it again once the spot is clear.+ else if( !playAnyways+ && BitTest( playing->m_audioEventRTS->getAudioEventInfo()->m_type, ST_SHROUDED )+ && playing->m_audioEventRTS->getAudioEventInfo()->isPermanentSound()+ && ThePartitionManager->getShroudStatusForPlayer( TheObserverCamera.getShroudPlayerIndex(), pos ) != CELLSHROUD_CLEAR )+ {+ AIL_register_3D_EOS_callback(playing->m_3DSample, NULL);+ stopPlayingAudio( playing );+ continue;+ }else{Real x = pos->x;@@ -3358,6 +3373,11 @@ void *AudioFileCache::openFile( AudioEventRTS *eventToOpenFrom )if (it != m_openFiles.end()) {++it->second.m_openCount;+ // A cached file keeps the info of whoever opened it first, and a map's customised sound+ // shares its file with the stock one. That info is deleted with the level+ // (removeLevelSpecificAudioEventInfos), and freeEnoughSpaceForSample went on reading the+ // priority out of it for the file's next user. The event opening it now is alive.+ it->second.m_eventInfo = eventToOpenFrom->getAudioEventInfo();return it->second.m_file;}diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cppindex 42de020b6..d98be7fa7 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp@@ -1504,7 +1504,15 @@ RenderObjClass * BaseHeightMapRenderObjClass::Clone(void) const/** Loads the roads from the map objects. *///=============================================================================void BaseHeightMapRenderObjClass::loadRoadsAndBridges(W3DTerrainLogic *pTerrainLogic, Bool saveGame)-{+{+ // Bridges first and whatever the device says: loading them is what hands each bridge to the+ // terrain logic, and nothing loads them again. Behind the device test below, a game alt-tabbed+ // out of fullscreen while the map loaded started with no bridges to cross at all, and in a+ // network game with a map the other machines did not have. Their buffers fill when drawn.+ if (m_bridgeBuffer) {+ m_bridgeBuffer->loadBridges(pTerrainLogic, saveGame);+ }+if (DX8Wrapper::_Get_D3D_Device() && (DX8Wrapper::_Get_D3D_Device()->TestCooperativeLevel()) != D3D_OK)return; //device not ready to render anything@@ -1513,9 +1521,6 @@ void BaseHeightMapRenderObjClass::loadRoadsAndBridges(W3DTerrainLogic *pTerrainLm_roadBuffer->loadRoads();}#endif- if (m_bridgeBuffer) {- m_bridgeBuffer->loadBridges(pTerrainLogic, saveGame);- }}// ============================================================================diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cppindex 229614e12..57ee4701b 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp@@ -2484,7 +2484,10 @@ void W3DModelDraw::adjustAnimation(const ModelConditionInfo* prevState, Real preisCommonMaintainFrameFlagSet(m_curState->m_flags, prevState->m_flags) &&prevAnimFraction >= 0.0){- startFrame = REAL_TO_INT(prevAnimFraction * animHandle->Get_Num_Frames()-1);+ // getCurrentAnimFraction is frame / (frames - 1), so this is its inverse. EA wrote+ // fraction * frames - 1, which put every carried-over animation a frame back (upstream #157)+ // rounded, since frame 5 of 11 comes back as 4.9999995+ startFrame = REAL_TO_INT(prevAnimFraction * (animHandle->Get_Num_Frames()-1) + 0.5f);}m_renderObject->Set_Animation(animHandle, startFrame, m_curState->m_mode);diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DOverlordTankDraw.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DOverlordTankDraw.cppindex 801e1b370..a196ba201 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DOverlordTankDraw.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DOverlordTankDraw.cpp@@ -85,7 +85,11 @@ void W3DOverlordTankDraw::doDrawModule(const Matrix3D* transformMtx)){Drawable *riderDraw = me->getContain()->friend_getRider()->getDrawable();- riderDraw->setColorTintEnvelope( *getDrawable()->getColorTintEnvelope() );+ // the envelope is made on a drawable's first tint, so an untinted Overlord has none; a rider+ // tinted on its own (a POWERED turret losing power) read through that null and crashed+ TintEnvelope *env = getDrawable()->getColorTintEnvelope();+ if( env )+ riderDraw->setColorTintEnvelope( *env );riderDraw->notifyDrawableDependencyCleared();riderDraw->draw( NULL );// What the hell? This param isn't used for anythingdiff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DOverlordTruckDraw.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DOverlordTruckDraw.cppindex c4ec294f5..c8cba672a 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DOverlordTruckDraw.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DOverlordTruckDraw.cpp@@ -85,7 +85,11 @@ void W3DOverlordTruckDraw::doDrawModule(const Matrix3D* transformMtx)){Drawable *riderDraw = me->getContain()->friend_getRider()->getDrawable();- riderDraw->setColorTintEnvelope( *getDrawable()->getColorTintEnvelope() );+ // the envelope is made on a drawable's first tint, so an untinted Avenger has none; a rider+ // tinted on its own (a POWERED turret losing power) read through that null and crashed+ TintEnvelope *env = getDrawable()->getColorTintEnvelope();+ if( env )+ riderDraw->setColorTintEnvelope( *env );riderDraw->notifyDrawableDependencyCleared();riderDraw->draw( NULL );// What the hell? This param isn't used for anythingdiff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DControlBar.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DControlBar.cppindex 9795d99a9..883fe0f11 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DControlBar.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GUI/GUICallbacks/W3DControlBar.cpp@@ -498,18 +498,11 @@ void W3DCommandBarGenExpDraw( GameWindow *window, WinInstanceData *instData )static const Image *endBar = TheMappedImageCollection->findImageByName("GenExpBarTop1");static const Image *beginBar = TheMappedImageCollection->findImageByName("GenExpBarBottom1");static const Image *centerBar = TheMappedImageCollection->findImageByName("GenExpBar1");- Int progress;- progress = ((player->getSkillPoints() - player->getSkillPointsLevelDown()) * 100) /(player->getSkillPointsLevelUp() - player->getSkillPointsLevelDown());-+ const Int progress = player->getRankProgressPercent();+if(progress <= 0)return;- // GS This should never be necessary, but scripts can change the points required or even disable a level.- // A disabled level will be -1 for points required. Just be totally safe and bind to 100, and we will- // fix the scripts to bind the points gained later.- if( progress > 100 )- progress = 100;-ICoord2D pos, size;window->winGetScreenPosition( &pos.x, &pos.y );window->winGetSize( &size.x, &size.y );diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cppindex 13f671a80..e42fd80b6 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp@@ -1383,6 +1383,10 @@ void WaterRenderObjClass::update( void )if (elapsedSec > 0.1f)elapsedSec = 0.1f; // a level load must not jump the surface forward+ // a pause or a script's time freeze stops every unit and particle; the water stops with them+ if (TheGameLogic->isGamePaused() || TheScriptEngine->isTimeFrozenScript() || TheScriptEngine->isTimeFrozenDebug())+ elapsedSec = 0.0f;+const Real step = elapsedSec * AUTHORED_FPS * WATER_SCROLL_SPEED;m_riverVOrigin += 0.002f * step;diff --git a/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32GameEngine.cpp b/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32GameEngine.cppindex 4994465ac..9a06c6f09 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32GameEngine.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/Win32Device/Common/Win32GameEngine.cpp@@ -37,6 +37,9 @@extern DWORD TheMessageTime;+class GameSpyInfoInterface;+extern GameSpyInfoInterface *TheGameSpyInfo; // GameNetwork/GameSpy/PeerDefs.h, not NULL while logged in online+//-------------------------------------------------------------------------------------------------/** Constructor for Win32GameEngine *///-------------------------------------------------------------------------------------------------@@ -105,9 +108,14 @@ void Win32GameEngine::update( void )}// If we are running a multiplayer game, keep running the logic.- // There is code in the client to skip client redraw if we are+ // There is code in the client to skip client redraw if we are// iconic. jba.- if (TheGameEngine->getQuitting() || TheGameLogic->isInInternetGame() || TheGameLogic->isInLanGame()) {+ // The same goes for a lobby or staging room, online or LAN: their menus answer joins, chat+ // and slot changes from their own update, and only TheLAN above was kept alive. A host+ // minimized in an online room left nobody able to join until the window came back, when+ // everything that had queued up played out at once.+ if (TheGameEngine->getQuitting() || TheGameLogic->isInInternetGame() || TheGameLogic->isInLanGame() ||+ TheLAN != NULL || TheGameSpyInfo != NULL) {break; // keep running.}}diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.cppindex b42941c38..ccb07158e 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.cpp@@ -892,8 +892,11 @@ void Render2DSentenceClass::Build_Sentence_Centered (const WCHAR *text, int *hkXch = *text++;}float char_spacing = Font->Get_Char_Spacing (ch);-- bool exceeded_texture_width = ((TextureOffset.I + char_spacing) >= CurrTextureSize);++ // Blit_Char writes the glyph's whole width, overlap and overhang columns included, so+ // that is what has to fit: tested on the spacing alone, the last few columns of a glyph+ // near the edge ran on into the next texel row and wiped the first letter of the line.+ bool exceeded_texture_width = ((TextureOffset.I + Font->Get_Char_Width (ch)) >= CurrTextureSize);bool encountered_break_char = (ch == L' ' || ch == L'\n' || ch == 0);//@@ -1032,7 +1035,8 @@ Vector2 Render2DSentenceClass::Build_Sentence_Not_Centered (const WCHAR *text, i}float char_spacing = Font->Get_Char_Spacing (ch);- bool exceeded_texture_width = ((TextureOffset.I + char_spacing) >= CurrTextureSize);+ // the whole width Blit_Char writes, as in Build_Sentence_Centered+ bool exceeded_texture_width = ((TextureOffset.I + Font->Get_Char_Width (ch)) >= CurrTextureSize);bool encountered_break_char = (ch == L' ' || ch == L'\n' || ch == 0);bool wordBiggerThenLine = ((useHardWordWrap) && ( WrapWidth != 0 ) &&((Cursor.X + TextureOffset.I -TextureStartX + char_spacing) >= WrapWidth));//diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex c41a400b5..cc52a8ab5 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -5279,6 +5279,17 @@ TEST(a_transferred_file_has_to_be_what_its_name_says_it_is)CHECK( IsValidTransferFileContent( "maps\\foo\\foo.tga", makeTga( 128, TRUE ), 128 ) );CHECK( !IsValidTransferFileContent( "maps\\foo\\foo.tga", makeTga( 128, FALSE ), 128 ) );CHECK( !IsValidTransferFileContent( "maps\\foo\\foo.tga", text, 8 ) );++ // a Targa 1.0 has no footer at all, and a header that holds up does instead: an 8 by 8+ // truecolor at 32 bits, and one byte short of the pixels it promises+ static const Int PLAIN_BYTES = 18 + 8 * 8 * 4;+ UnsignedByte *plain = makeTga( PLAIN_BYTES, FALSE );+ plain[2] = 2;+ plain[12] = 8;+ plain[14] = 8;+ plain[16] = 32;+ CHECK( IsValidTransferFileContent( "maps\\foo\\foo.tga", plain, PLAIN_BYTES ) );+ CHECK( !IsValidTransferFileContent( "maps\\foo\\foo.tga", plain, PLAIN_BYTES - 1 ) );}/* The name a joining player sends goes into the game state string the lobby passes around, and thatdiff --git a/ai-batch.ps1 b/ai-batch.ps1index bd7657911..f6d966f98 100644--- a/ai-batch.ps1+++ b/ai-batch.ps1@@ -64,7 +64,12 @@ param(# (e.g. -ExtraArgs "-unitlimit") without a rebuild between batches[string[]] $ExtraArgs = @(),# minutes before a wedged run is killed rather than waited on forever- [int] $TimeoutMinutes = 20+ [int] $TimeoutMinutes = 20,+ # matches played at once. A headless match is one logic thread, so one a core runs the batch+ # that many times faster and the results are the same: the logic does not read the clock. The+ # frame-time and stutter lines are the exception, every copy slows the others, so a batch that is+ # asked about frame time passes -Parallel 1+ [int] $Parallel = [Environment]::ProcessorCount)$ErrorActionPreference = "Stop"@@ -79,6 +84,9 @@ if (-not (Test-Path $exePath)) {# One row per match. Slot results are kept as a hashtable per row so the summary can pivot on them.$rows = @()+# Every match is started first, $Parallel at a time, and read back afterwards in seed order.+$started = @()+for ($i = 0; $i -lt $Runs; $i++) {$seed = $SeedStart + $i@@ -120,22 +128,41 @@ for ($i = 0; $i -lt $Runs; $i++) {if ($Teams -gt 1) { $args += "-teams"; $args += $Teams }if ($ExtraArgs.Count) { $args += $ExtraArgs }- $where = if ($Map) { $Map } else { "$cells cells" }- Write-Host ("[{0,3}/{1}] seed {2} {3} ... " -f ($i + 1), $Runs, $seed, $where) -NoNewline- $sw = [Diagnostics.Stopwatch]::StartNew()+ while (@($started | Where-Object { -not $_.Proc.HasExited }).Count -ge $Parallel) {+ Start-Sleep -Milliseconds 200+ }$proc = Start-Process -FilePath $exePath -ArgumentList $args -WorkingDirectory $RunDir -PassThru$proc.PriorityClass = 'AboveNormal'- if (-not $proc.WaitForExit($TimeoutMinutes * 60 * 1000)) {+ $started += [pscustomobject]@{+ Index = $i; Seed = $seed; Cells = $cells; Log = $log; Proc = $proc+ Clock = [Diagnostics.Stopwatch]::StartNew()+ }+}++foreach ($run in $started) {++ $seed = $run.Seed+ $cells = $run.Cells+ $log = $run.Log+ $proc = $run.Proc+ $sw = $run.Clock++ $where = if ($Map) { $Map } else { "$cells cells" }+ Write-Host ("[{0,3}/{1}] seed {2} {3} ... " -f ($run.Index + 1), $Runs, $seed, $where) -NoNewline+ $timeLeft = [Math]::Max(0, $TimeoutMinutes * 60 * 1000 - $sw.ElapsedMilliseconds)+ if (-not $proc.WaitForExit([int]$timeLeft)) {$proc.Kill()Write-Host "KILLED (wedged past $TimeoutMinutes min)"$rows += [pscustomobject]@{ Seed = $seed; Cells = $cells; Why = "wedged"; Frames = 0; Wall = $sw.Elapsed.TotalSeconds; Slots = @{}; Pf = $null }continue}+ # the wall time is the process's own; this loop may reach a run long after it finished$sw.Stop()+ $wall = ($proc.ExitTime - $proc.StartTime).TotalSecondsif (-not (Test-Path $log)) {Write-Host "NO LOG (exit $($proc.ExitCode))"- $rows += [pscustomobject]@{ Seed = $seed; Cells = $cells; Why = "no log"; Frames = 0; Wall = $sw.Elapsed.TotalSeconds; Slots = @{}; Pf = $null }+ $rows += [pscustomobject]@{ Seed = $seed; Cells = $cells; Why = "no log"; Frames = 0; Wall = $wall; Slots = @{}; Pf = $null }continue}@@ -219,9 +246,9 @@ for ($i = 0; $i -lt $Runs; $i++) {$winner = ($slots.Keys | Where-Object { $slots[$_].Status -eq "WON" } | Select-Object -First 1)$winnerText = if ($null -ne $winner) { "player $winner" } else { "no winner" }- Write-Host ("{0}, {1}, frame {2}, {3:n0}s" -f $why, $winnerText, $frames, $sw.Elapsed.TotalSeconds)+ Write-Host ("{0}, {1}, frame {2}, {3:n0}s" -f $why, $winnerText, $frames, $wall)- $rows += [pscustomobject]@{ Seed = $seed; Cells = $cells; Why = $why; Frames = $frames; Wall = $sw.Elapsed.TotalSeconds; Slots = $slots; Pf = $pf; Perf = $perf; Jobs = $jobs; Ft = $ft; Spikes = $spikes }+ $rows += [pscustomobject]@{ Seed = $seed; Cells = $cells; Why = $why; Frames = $frames; Wall = $wall; Slots = $slots; Pf = $pf; Perf = $perf; Jobs = $jobs; Ft = $ft; Spikes = $spikes }}# ---------------------------------------------------------------------------------------------