Skip to content

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

fix(gameengine): three reported bugs - startup, command bar, tooltips

Olcay Seyganc3666a0f3133
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b3059f516..603bafc0c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -437,6 +437,13 @@ found and fixed — EA's own, not port damage.**
- The clock counts down in red in the top right corner, above the game clock, for as long as it runs. You are also told when it starts, at a minute, thirty seconds and ten seconds left, and when it is over.
- Put a computer player in the room and the truce switches itself off, whatever the host had picked. A computer opponent does not honour a truce - it stands still for five minutes and then plays exactly the game it was going to play - so all peace time buys against one is a handicap for the person who is not a computer. The box greys out and reads off while a bot is in a seat, and remembers the host's choice for when the bot leaves. That is also why the skirmish lobby has no such box: a skirmish is played against computer players.
+## Two windows, one machine, a real LAN game
+
+- You can start the game twice on one computer and play the two copies against each other over the LAN screen, the ordinary way: one hosts, picks a map and starts, the other finds the game in the list and joins. Faction, colour and team per slot as always. It is how a network change gets tested here, and it is how two people sharing a desk can play a match without a second machine.
+- The second copy used to come up with a socket error and an empty game list, because the lobby's one network port was already taken by the first. Each copy now takes an address of its own on the machine's own loopback range and they announce themselves to each other across it.
+- The second copy also used to be thrown out on the way in. It arrived carrying the same player name, which a host refuses, and the same serial number, which a host refuses harder - a rule written against two people sharing one bought copy, and two windows on one desk are not that. Both copies get their own name now, and the serial rule is waived only between two addresses on the same machine. Anything that could be a second computer still answers to it.
+- `lan-play.ps1` starts as many copies as you ask for, gives each its own name, address and log, opens each on the LAN screen instead of the main menu, and lays the windows out side by side so they are not stacked on top of one another.
+
## The options screen has pages
- Display, audio, controls, gameplay and network, behind five buttons across the top. The original screen was one panel with everything on it at once, and it was already full the day it shipped: the language filter, the keyboard button and four camera checkboxes are all still in there, parked off the right edge where nobody can reach them, because there was nowhere left to put them.
@@ -470,6 +477,10 @@ found and fixed — EA's own, not port damage.**
- The command bar stops changing under you while you are using it. With nothing selected the bar shows one of your builders so you can place a structure without picking a dozer first, and it showed whichever one happened to be idle - so a dozer finishing a building on the far side of the base took the bar over, dropping a half-typed build hotkey and taking the structure off your cursor. The builder you are working with keeps the bar.
- The command bar's artwork moves with the command bar. Minimising it slid the buttons off the bottom of the screen and left the metal they sit on painted over the battlefield; the same painting stood still through the slide the bar makes when a match opens. It travels with the bar and goes with it.
- Widescreen resolutions are back in the options menu, and the list works during a match. It was greyed out the moment a game started, because changing it rebuilt the menus and then pushed the main menu over whatever you were playing. It rebuilds the menus for later and leaves you on the battlefield with the command bar back up.
+- Changing the resolution during a match no longer takes the game down. Two things were behind it. The old command bar's windows were handed back while the menu system still had them on its list, so the next thing that painted a button read whatever had since been written over it. And the bar itself was thrown away and built from scratch, which handed out fresh copies of every build button while your factories, your repair crews and the promotion screen went on pointing at the old ones. The bar's windows are rebuilt now and the bar keeps everything that is not a window.
+- The command bar stays on the bottom edge of the screen. Minimising it and bringing it back lifted a few pieces that had never gone down in the first place, and every rebuild of the layout lifted them a little further, so over a long match the bar climbed off its own strip and the build tooltip, which is placed against it, ended up above the top of the screen. Each piece is now put back by exactly the amount it was moved by.
+- The other half of that had the money readout, the general's tabs and the column of small buttons stranded a couple of hundred pixels above the bar, floating over the battlefield with the bar itself still sitting where it belongs. The bar takes a fifth of a second to slide back up when you un-minimise it, and anything that redrew the panel artwork during that fifth of a second measured every one of those pieces against a bar that had not arrived yet, then wrote the wrong answer down as if it were the right one. Switching general, changing faction colours and a resolution change all redraw it, so in a long match it happened sooner or later. The bar is put where it belongs before any of that is measured. Over six thousand frames of a match that minimises and rebuilds the bar every second, the top edge of everything it owns now reads the same number every single time.
+- Tooltips stay on the screen. A tooltip is drawn to the right of the pointer, and near the right or bottom edge it jumps to the other side to make room, which was all the original code did about edges - the man who wrote it left a note saying so. Nothing then checked where it had jumped to. A wide one, and the game will wrap a tooltip to the full width of the screen when the text asks for it, jumped clean off the left edge with the first half of the sentence outside the monitor; a long narrow one hovered near the top went off the top. Both are put back on the screen now, and the pointer sits over the corner of the box rather than the words going where nobody can read them.
- The rank screen is one painting instead of a stretched one. It is sized from that painting at the same scale as everything else and centred on the screen, rather than multiplied out separately across and down from the corner it was authored in - which on a widescreen monitor made it a third too wide and pushed it off centre.
- Borderless fullscreen: start with `-borderless` and the game fills the screen at your desktop resolution with no frame and no display mode change, so alt-tab is instant, nothing on the desktop gets shuffled around behind it, and a second monitor stays usable. Screen-edge scrolling works there, the way it does in fullscreen. The loading picture still opens as its own small window with your desktop around it, and the game only takes the screen once it has something to draw.
- Fullscreen, borderless and windowed are one saved setting now, so borderless no longer means adding a switch to your shortcut every time. `WindowMode` in `Options.ini` takes 0, 1 or 2 in that order; a switch on the command line still wins for that one run. Picking a different one applies when you press Accept instead of the next time you start the game: the window loses or gains its frame and the display device is rebuilt on the spot. Borderless takes your desktop resolution and nothing else, so while it is selected the resolution list greys out and the other two modes hand it straight back.
@@ -571,6 +582,7 @@ found and fixed — EA's own, not port damage.**
- Two blocks of 2003 assembly destroyed registers and took down the main menu.
- Quitting faulted twice every time; it now takes about half a second.
- A long chat message or an unusual map name could kill the process.
+- A map name the game cannot make sense of is refused as you start, instead of taking the game down later. A path with a space in it and no quotes around it left the loader walking the same step of that path forever, growing a string until it ran out of room, and the game then went on starting with half of itself missing. What you saw was a crash a second later, in the part of the game that runs a match, naming nothing that had anything to do with it. Any failure during start-up now stops the game there and says which one it was.
- Nor can a map handed to you over the network, however long a name the other machine gives it.
- An order too big for one packet arrives in pieces, and a piece that claims to belong outside the order is dropped instead of landing there.
- A chat line too long for a packet is dropped rather than arriving as a different, shorter line.
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/CommandLine.h b/GeneralsMD/Code/GameEngine/Include/Common/CommandLine.h
index 6e8997c7d..c5bc97235 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/CommandLine.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/CommandLine.h
@@ -31,6 +31,12 @@
#ifndef _COMMAND_LINE_H_
#define _COMMAND_LINE_H_
+class AsciiString;
+
void parseCommandLine(int argc, char *argv[]); ///< Parse command-line parameters
+/// "maps\foo.map" -> "maps\foo\foo.map". Exposed so a test can hand it a path with no map file
+/// in it; that used to run until AsciiString's length ceiling threw out of parseCommandLine.
+void ConvertShortMapPathToLongMapPath(AsciiString &mapName);
+
#endif // _COMMAND_LINE_H_
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
index 2b28bfe7d..6ca632eb5 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
@@ -395,8 +395,14 @@ public:
Bool m_showLanes; ///< -showlanes: draw every moving unit's route, the lane it was handed and the offset it kept
Bool m_crowdModel; ///< -crowd: the sandbox crowd model - corridor, absolute lanes, right of way, give way, fan out
Int m_groupDrill; ///< -groupdrill <n>: every n frames, order each player's army corner to corner as one group (0 = off)
+ Int m_uiDrill; ///< -uidrill <n>: every n frames, minimise the command bar and re-apply its scheme, logging where it landed (0 = off)
+ Int m_resDrillFrame; ///< -resdrill <frame> [w] [h]: change the resolution at that logic frame, from inside a running match (0 = off)
+ Int m_resDrillX; ///< the width -resdrill asks for (0 = the next mode the device offers)
+ Int m_resDrillY; ///< the height -resdrill asks for
AsciiString m_netGameHosts; ///< -netgame <ip>[,<ip>...]: the slot list of a LAN game started from the command line (empty = off)
Int m_netGameLocalSlot; ///< -netslot <n>: which of those addresses this copy of the game is
+ AsciiString m_lanPlayerName; ///< -lanname <name>: the name this copy takes in the LAN lobby (empty = the one in the preferences)
+ Bool m_lanLobbyOnStart; ///< -lanlobby: open the LAN lobby instead of stopping at the main menu
Int m_maxParticleCount; ///< maximum number of particles that can exist
Int m_maxFieldParticleCount; ///< maximum number of field-type particles that can exist (roughly)
diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h
index c7203a9e3..8c6d7de3b 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ControlBar.h
@@ -677,6 +677,15 @@ public:
virtual void reset( void ); ///< from subsystem interface
virtual void update( void ); ///< from subsystem interface
+ //
+ // The window half of init, on its own, because a resolution change throws every window away and
+ // builds it again while the bar's command buttons and command sets have to stay where they are:
+ // an object holding a const CommandButton * would be left pointing at a freed one. initWindows
+ // drops what it is holding (shutdownWindows) and looks the new windows up.
+ //
+ void initWindows( void );
+ void shutdownWindows( void );
+
/// mark the UI as dirty so the context of everything is re-evaluated
void markUIDirty( void );
@@ -900,6 +909,18 @@ public:
* set - because it remembers both the authored rectangle and the one it last handed out. */
void layoutPanels( void );
+ /** Take the slide off and declare all three panels home. Anything that reads a window's screen
+ * position and writes another window's position from it has to run after this, or it writes
+ * the answer for a bar that is on its way down and layoutPanels then reads that as the
+ * rectangle the window was authored at. ControlBarScheme::init is that caller. */
+ void clearPanelSlide( void );
+
+ /// top edge of the highest visible window the bar owns, and where MoneyDisplay is; see -uidrill
+ void forEachPlacedWindow( Int *topOut, Int *moneyOut );
+
+ /// the window every other one on the bar hangs off, so -uidrill can walk it looking for a button
+ GameWindow *getMasterParent( void ) { return m_contextParent[ CP_MASTER ]; }
+
/** Send one whole panel off the bottom of the screen, or bring it back. It slides: the panel is
* a picture of a thing, and a thing that is going away should be seen going. 'immediate' puts
* it where it is going this instant, which is what a rebuild wants. */
@@ -911,6 +932,13 @@ public:
/// how far down that panel has slid, in pixels - the plate art travels with its windows
Int getPanelSlideOffset( Int panel ) const;
+ /// the same journey as a fraction, 0 home and 1 gone. Needs no display, which is why the test
+ /// for the rebuild ordering asks this one; see clearPanelSlide
+ Real getPanelSlideFraction( Int panel ) const
+ {
+ return ( panel < 0 || panel >= CB_PANEL_COUNT ) ? 0.0f : m_panelSlide[ panel ];
+ }
+
protected:
/// place one window and its descendants inside 'panel'; see layoutPanels
void placeInPanel( GameWindow *win, Int panel,
@@ -1232,6 +1260,9 @@ public:
Bool getShowBuildTooltipLayout( void ){return m_showBuildToolTipLayout; }
void populateBuildTooltipLayout( const CommandButton *commandButton, GameWindow *tooltipWin = NULL );
void repopulateBuildTooltipLayout( void );
+ /// where the popup lives, so -uidrill can read the rectangle it landed in. The tooltip is placed
+ /// against BackgroundMarker's screen position, so it goes wherever the bar's windows went
+ WindowLayout *getBuildTooltipLayout( void ) { return m_buildToolTipLayout; }
private:
@@ -1298,6 +1329,10 @@ private:
// EXTERNALS //////////////////////////////////////////////////////////////////////////////////////
extern ControlBar *TheControlBar;
+/// -uidrill: write one line saying where the bar's windows actually are, so a long run says whether
+/// they hold still. See ControlBar::clearPanelSlide for what they used to do instead.
+extern void ControlBar_logPlacement( const char *tag, Int frame );
+
//-------------------------------------------------------------------------------------------------
/** The plate one panel wears.
*
diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/GUICallbacks.h b/GeneralsMD/Code/GameEngine/Include/GameClient/GUICallbacks.h
index 1da9e870f..40198439c 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameClient/GUICallbacks.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/GUICallbacks.h
@@ -61,6 +61,10 @@ extern void OptionsMenuUpdate( WindowLayout *layout, void *userData );
extern void OptionsMenuShutdown( WindowLayout *layout, void *userData );
extern WindowMsgHandledType OptionsMenuSystem( GameWindow *window, UnsignedInt msg, WindowMsgData mData1, WindowMsgData mData2 );
extern WindowMsgHandledType OptionsMenuInput( GameWindow *window, UnsignedInt msg, WindowMsgData mData1, WindowMsgData mData2 );
+/// -resdrill: the options menu's own in-match resolution change, driven from the update loop
+extern void ResolutionDrillApply( Int xres, Int yres );
+/// and the answer to the box it leaves behind, a few frames later, the way a player answers it
+extern void ResolutionDrillDismiss( Bool accept );
// Map Select Menu --------------------------------------------------------------------------------
extern void MapSelectMenuInit( WindowLayout *layout, void *userData );
diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/Mouse.h b/GeneralsMD/Code/GameEngine/Include/GameClient/Mouse.h
index d11ac2879..ed857a9c9 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameClient/Mouse.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/Mouse.h
@@ -274,6 +274,14 @@ public:
inline Bool getVisibility(void) { return m_visible; } // get visibility state
void drawTooltip( void ); ///< draw the tooltip text
+
+ /** Where a tooltip box of this size goes for a pointer here: beside it, flipped to the other
+ * side at the right or bottom edge, and then held inside the screen. Static and free of every
+ * member so the placement can be checked without a display; drawTooltip is its only caller. */
+ static void placeTooltip( Int mouseX, Int mouseY, Int width, Int height,
+ Int minX, Int minY, Int maxX, Int maxY,
+ Int *xOut, Int *yOut );
+
void drawCursorText( void ); ///< draw the mouse cursor text
Int getCursorIndex( const AsciiString& name );
void resetTooltipDelay( void );
diff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/networkutil.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/networkutil.h
index 9e04ecbe6..6e2d5d6d2 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameNetwork/networkutil.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/networkutil.h
@@ -39,6 +39,12 @@ UnsignedInt ResolveIP(AsciiString host);
address. ResolveIP() answers INADDR_NONE for a malformed dotted quad and 0 for a name it
cannot look up; neither is a player, so both are refused here. */
Int ResolveHostList(AsciiString hosts, UnsignedInt *addresses, Int maxAddresses);
+
+/** True for the whole of 127.0.0.0/8, which Windows routes to loopback and which is therefore the
+ range two copies of the game on one machine take an address each out of. Host order, the same
+ order ResolveIP() answers in. */
+inline Bool IsLoopbackIP(UnsignedInt hostOrderIP) { return (hostOrderIP & 0xFF000000) == 0x7F000000; }
+
UnsignedShort GenerateNextCommandID();
Bool DoesCommandRequireACommandID(NetCommandType type);
Bool CommandRequiresAck(NetCommandMsg *msg);
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
index 51bb60e22..0d8025a0a 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
@@ -34,6 +34,7 @@
#include "GameClient/TerrainVisual.h" // for TERRAIN_LOD_MIN definition
#include "GameClient/GameText.h"
#include "GameNetwork/GameInfo.h" // for the SlotState -autoskirmish hands the AI slots
+#include "GameNetwork/NetworkUtil.h" // for ResolveIP, which -lanip parses its address with
#include "Common/FileSystem.h"
#include "Common/RandomMapGenerator.h" // for -randommap
@@ -74,7 +75,7 @@ struct CommandLineParam
FuncPtr func;
};
-static void ConvertShortMapPathToLongMapPath(AsciiString &mapName)
+void ConvertShortMapPathToLongMapPath(AsciiString &mapName)
{
AsciiString path = mapName;
AsciiString token;
@@ -85,17 +86,21 @@ static void ConvertShortMapPathToLongMapPath(AsciiString &mapName)
DEBUG_CRASH(("Invalid map name %s", mapName.str()));
return;
}
- path.nextToken(&token, "\\/");
- while (!token.endsWithNoCase(".map") && (token.getLength() > 0))
+ /* Drive the walk on nextToken's own answer rather than on the token being non-empty: a path
+ that never names a .map file must leave this loop, and leave mapName as the player typed it
+ rather than half-rewritten. */
+ Bool haveToken = path.nextToken(&token, "\\/");
+ while (haveToken && !token.endsWithNoCase(".map"))
{
actualpath.concat(token);
actualpath.concat('\\');
- path.nextToken(&token, "\\/");
+ haveToken = path.nextToken(&token, "\\/");
}
if (!token.endsWithNoCase(".map"))
{
DEBUG_CRASH(("Invalid map name %s", mapName.str()));
+ return;
}
// remove the .map from the end.
token.removeLastChar();
@@ -1521,6 +1526,65 @@ Int parseGroupDrill(char *args[], int num)
return 1;
}
+/* -uidrill <n> works the command bar the way a player does, from a script.
+
+ The bar is laid out again every time its scheme is set, and a panel that was minimised at that
+ moment used to come back a little higher than it went down - a few pixels a rebuild, until the
+ build tooltip anchored to it was off the top of the screen. Nothing in an unattended run ever
+ presses the minimise button or changes the player's scheme, so the drift could only be found by
+ hand. This does both every n frames and logs where the bar actually landed, so a long run turns
+ the bug into a column of numbers that either holds still or climbs. */
+Int parseUIDrill(char *args[], int num)
+{
+ if (TheWritableGlobalData)
+ {
+ Int frames = 120;
+ Int eaten = 1;
+ if (num > 1 && args[1] && args[1][0] >= '0' && args[1][0] <= '9')
+ {
+ frames = atoi(args[1]);
+ eaten = 2;
+ }
+ if (frames < 2)
+ frames = 2; // the bar slides; give it a frame to arrive before measuring it again
+ TheWritableGlobalData->m_uiDrill = frames;
+ return eaten;
+ }
+ return 1;
+}
+
+/* -resdrill <frame> [w] [h] changes the resolution from inside a running match.
+
+ That is the one path the options menu has that no switch could reach: the device is reset, the
+ shell is thrown away and rebuilt, and the command bar is built again while the match it belongs
+ to keeps running. It crashed, and reproducing it meant a person in the options menu of a live
+ game. With no width given it takes the next mode the device offers that is not the one already
+ on screen, so the drill needs to know nothing about the monitor it runs on. */
+Int parseResDrill(char *args[], int num)
+{
+ if (TheWritableGlobalData)
+ {
+ Int frame = 600;
+ Int eaten = 1;
+ if (num > 1 && args[1] && args[1][0] >= '0' && args[1][0] <= '9')
+ {
+ frame = atoi(args[1]);
+ eaten = 2;
+ if (num > 3 && args[2] && args[3] && args[2][0] >= '0' && args[2][0] <= '9' && args[3][0] >= '0' && args[3][0] <= '9')
+ {
+ TheWritableGlobalData->m_resDrillX = atoi(args[2]);
+ TheWritableGlobalData->m_resDrillY = atoi(args[3]);
+ eaten = 4;
+ }
+ }
+ if (frame < 1)
+ frame = 1;
+ TheWritableGlobalData->m_resDrillFrame = frame;
+ return eaten;
+ }
+ return 1;
+}
+
/* -teams <n> splits an -autoskirmish lobby into n allied teams instead of a free-for-all.
Free-for-all and 4v4 are not the same load and not the same game. Eight players each fighting
@@ -1599,6 +1663,54 @@ Int parseNetGame(char *args[], int num)
return 2;
}
+/* -lanip <ip> is the same idea one level up, for the LAN lobby rather than for a game started
+ without one. The lobby socket is a single UDP port (8086) and nothing sets SO_REUSEADDR, so the
+ first copy on a machine binds it on every address and the second copy's LAN screen comes up with
+ a socket error and an empty game list. The address here is what LanLobbyMenu binds instead, so
+ two copies want two addresses out of 127.0.0.0/8 - Windows routes that range to loopback in its
+ entirety, and a broadcast sent from one of them is delivered to the others.
+
+ Options.ini carries the same setting, and both copies read the same file, which is why this is a
+ switch and not a preference: the whole point is that the two copies disagree about it. */
+Int parseLanIP(char *args[], int num)
+{
+ if (TheWritableGlobalData && num > 1)
+ {
+ UnsignedInt ip = ResolveIP( AsciiString( args[1] ) );
+ if (ip != 0 && ip != INADDR_NONE)
+ TheWritableGlobalData->m_defaultIP = ip;
+ }
+ return 2;
+}
+
+/* -lanname <name> is the other half of it. The lobby name comes out of the preferences, both
+ copies read the same preferences, and a host denies a join whose name it already has in a slot
+ (RET_DUPLICATE_NAME) - so without this the second copy is refused until somebody retypes the
+ name by hand every session. */
+Int parseLanName(char *args[], int num)
+{
+ if (TheWritableGlobalData && num > 1)
+ {
+ TheWritableGlobalData->m_lanPlayerName = args[1];
+ }
+ return 2;
+}
+
+/* -lanlobby starts on the LAN screen rather than the main menu. Two copies on one machine are
+ started by a script and the first thing both of them do is the same four clicks; this is those
+ clicks. It turns the shell map off with it: Shell::showShell only puts the main menu on the
+ stack when there is no shell map, and the lobby has to go on top of something or backing out of
+ it leaves an empty shell. */
+Int parseLanLobby(char *args[], int num)
+{
+ if (TheWritableGlobalData)
+ {
+ TheWritableGlobalData->m_lanLobbyOnStart = TRUE;
+ TheWritableGlobalData->m_shellMapOn = FALSE;
+ }
+ return 1;
+}
+
Int parseNetSlot(char *args[], int num)
{
if (TheWritableGlobalData && num > 1)
@@ -1855,10 +1967,15 @@ static CommandLineParam params[] =
{ "-showlanes", parseShowLanes },
{ "-crowd", parseCrowdModel },
{ "-groupdrill", parseGroupDrill },
+ { "-uidrill", parseUIDrill },
+ { "-resdrill", parseResDrill },
{ "-replay", parseReplay },
{ "-loadsave", parseLoadSave },
{ "-netgame", parseNetGame },
{ "-netslot", parseNetSlot },
+ { "-lanip", parseLanIP },
+ { "-lanname", parseLanName },
+ { "-lanlobby", parseLanLobby },
//-allAdvice feature
//{ "-allAdvice", parseAllAdvice },
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
index 07c8a1ca4..47f189111 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
@@ -104,6 +104,9 @@
#include "GameClient/GlobalLanguage.h"
#include "GameClient/Drawable.h"
#include "GameClient/GUICallbacks.h"
+#include "GameClient/ControlBar.h" // -uidrill works the command bar the way a player does
+#include "GameClient/InGameUI.h" // -resdrill selects a building before it changes the mode
+#include "GameLogic/Object.h"
#include "GameNetwork/GameInfo.h"
#include "GameNetwork/NetworkInterface.h"
@@ -1001,6 +1004,12 @@ void GameEngine::init( int argc, char *argv[] )
{
RELEASE_CRASHLOCALIZED("ERROR:D3DFailurePrompt", "ERROR:D3DFailureMessage");
}
+ /* Anything else stops here as well. Running on means running frames against subsystems that
+ were never built, and the access violation that follows names update() instead of the real
+ failure - which is how a bad -map argument came to read as "the game crashed on quit". */
+ AsciiString why;
+ why.format("GameEngine::init failed with ErrorCode 0x%08x.", (UnsignedInt)ec);
+ RELEASE_CRASH((why.str()));
}
catch (INIException e)
{
@@ -1400,6 +1409,129 @@ static void updateFixedCamera( void )
}
}
+/** -----------------------------------------------------------------------------------------------
+ * -uidrill <n>: minimise the command bar, put it back, and re-apply its scheme, over and over.
+ *
+ * The bar drifted up the screen a few pixels at a time and only under a sequence no unattended run
+ * performs: a panel that is away when its layout is rebuilt. Nothing the AI does touches the bar,
+ * -groupdrill gives orders and never opens a menu, and the drift is small enough per rebuild that
+ * one cycle by hand looks like nothing. So the drill does the two halves on alternate ticks - a
+ * toggle, then a rebuild once the slide has arrived - and writes where the bar landed each time.
+ * A run that holds one pair of numbers for its whole life is a bar that stays put; a run whose
+ * numbers walk is the bug.
+ */
+static void updateUIDrill( void )
+{
+ if( TheGlobalData->m_uiDrill <= 0 || TheControlBar == NULL || TheGameLogic == NULL )
+ return;
+ if( !TheGameLogic->isInGame() || TheGameLogic->isInShellGame() )
+ return;
+
+ // once per logic frame, not once per render frame: the renderer is uncapped and would run the
+ // whole cycle several times over on the one frame it is due
+ static UnsignedInt lastTickFrame = 0xffffffff;
+ const UnsignedInt frame = TheGameLogic->getFrame();
+ if( frame < (UnsignedInt)TheGlobalData->m_uiDrill || frame == lastTickFrame )
+ return;
+ if( ( frame % (UnsignedInt)TheGlobalData->m_uiDrill ) != 0 )
+ return;
+ lastTickFrame = frame;
+
+ static Int tick = 0;
+ const Bool toggling = ( ( tick++ & 1 ) == 0 );
+
+ if( toggling )
+ {
+ TheControlBar->toggleControlBarStage();
+ }
+ else if( ThePlayerList )
+ {
+ // what setControlBarSchemeByPlayer reaches: ControlBarScheme::init, which calls layoutPanels
+ TheControlBar->setControlBarSchemeByPlayer( ThePlayerList->getLocalPlayer() );
+ }
+
+ ControlBar_logPlacement( toggling ? "toggle" : "relayout", (Int)frame );
+}
+
+/** -----------------------------------------------------------------------------------------------
+ * -resdrill <frame> [w] [h]: change the resolution from inside a running match.
+ *
+ * The options menu is the only way a player reaches this, and a script cannot open a menu. What
+ * happens after the device resets - the shell thrown away and rebuilt, the command bar built again
+ * while the match that owns it is still running - is where it crashed, and the whole sequence lives
+ * in OptionsMenu.cpp so that this drill runs the real one rather than a copy of it.
+ */
+/* The rebuild frees the CommandButton table and builds a new one. Nothing dereferences the old
+ entries unless the bar is showing a command set, and the bar shows one only while something is
+ selected - so a drill that selects nothing walks straight past the defect this is here to catch.
+ Pick a structure: its command set is the one with production buttons on it. */
+static void resDrillSelectObject( Object *obj, void *userData )
+{
+ Drawable **found = (Drawable **)userData;
+ if( *found != NULL || obj == NULL || !obj->isKindOf( KINDOF_STRUCTURE ) )
+ return;
+ *found = obj->getDrawable();
+}
+
+static void updateResDrill( void )
+{
+ if( TheGlobalData->m_resDrillFrame <= 0 || TheGameLogic == NULL )
+ return;
+ if( !TheGameLogic->isInGame() || TheGameLogic->isInShellGame() )
+ return;
+ if( TheGameLogic->getFrame() < (UnsignedInt)TheGlobalData->m_resDrillFrame )
+ return;
+
+ /* Two stages, sixty frames apart. The first presses Accept, which leaves the "keep this
+ resolution?" box on screen; the second answers it with Cancel, which is DeclineResolution -
+ the mode goes back and the shell and the command bar are built a second time, from inside the
+ box's own handler, over what the first rebuild left. Answering in the same breath as Accept
+ would be a sequence no player can perform. */
+ static Bool applied = FALSE;
+ static Bool dismissed = FALSE;
+ static UnsignedInt appliedFrame = 0;
+
+ if( applied )
+ {
+ if( dismissed || TheGameLogic->getFrame() < appliedFrame + 60 )
+ return;
+ dismissed = TRUE;
+ ResolutionDrillDismiss( FALSE );
+ return;
+ }
+ applied = TRUE;
+ appliedFrame = TheGameLogic->getFrame();
+
+ if( TheGlobalData->m_headless )
+ {
+ // a headless run has a 100x100 device it never draws to; resetting it proves nothing
+ DEBUG_LOG(("RESDRILL: refused, this run is headless\n"));
+ dismissed = TRUE;
+ return;
+ }
+
+ Drawable *pick = NULL;
+ if( ThePlayerList && TheInGameUI )
+ {
+ Player *local = ThePlayerList->getLocalPlayer();
+ if( local )
+ local->iterateObjects( resDrillSelectObject, &pick );
+ if( pick )
+ {
+ TheInGameUI->deselectAllDrawables();
+ TheInGameUI->selectDrawable( pick );
+ DEBUG_LOG(("RESDRILL: selected drawable %d so the bar is showing a command set\n",
+ (Int)pick->getID()));
+ }
+ else
+ {
+ DEBUG_LOG(("RESDRILL: nothing to select, the bar will be empty\n"));
+ }
+ }
+
+ ResolutionDrillApply( TheGlobalData->m_resDrillX, TheGlobalData->m_resDrillY );
+}
+
static void updateAutoCamera( void )
{
if( TheGlobalData->m_autoCameraSeconds <= 0 || TheTacticalView == NULL || TheTerrainLogic == NULL )
@@ -1824,6 +1956,8 @@ void GameEngine::update( void )
updateHeadlessRun();
updateFixedCamera();
updateAutoCamera();
+ updateUIDrill();
+ updateResDrill();
#ifdef DEBUG_LOGGING
fpsFrames++;
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
index a154d7b2e..f3660bc30 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
@@ -701,8 +701,14 @@ GlobalData::GlobalData()
m_showLanes = FALSE; // the lane overlay is a diagnostic, off unless -showlanes asks for it
m_crowdModel = FALSE; // the crowd model is the change under test; without -crowd this is the old build
m_groupDrill = 0; // no group orders are faked; -groupdrill is a measuring tool and ruins the match it runs in
+ m_uiDrill = 0; // nobody presses the minimise button; -uidrill is how a script presses it
+ m_resDrillFrame = 0; // the resolution stays where it started unless -resdrill changes it mid-match
+ m_resDrillX = 0;
+ m_resDrillY = 0;
m_netGameHosts.clear(); // no network game from the command line
m_netGameLocalSlot = 0;
+ m_lanPlayerName.clear(); // the lobby name comes out of the preferences unless -lanname says otherwise
+ m_lanLobbyOnStart = FALSE;
m_horizontalScrollSpeedFactor = 1.0;
m_verticalScrollSpeedFactor = 1.0;
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/AsciiString.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/AsciiString.cpp
index c2bc9c0e7..81bdfc9ec 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/System/AsciiString.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/AsciiString.cpp
@@ -375,9 +375,20 @@ Bool AsciiString::isNone() const
//-----------------------------------------------------------------------------
Bool AsciiString::nextToken(AsciiString* tok, const char* seps)
{
- if (this->isEmpty() || tok == this)
+ if (tok == this)
return false;
+ /* An exhausted source used to return false with the caller's token left holding the *previous*
+ token. Every loop of the form "while (token.getLength() > 0) nextToken(&token)" then never
+ ends, because the token never empties - see ConvertShortMapPathToLongMapPath, where it grew
+ a string until AsciiString's 32767-byte ceiling threw ERROR_OUT_OF_MEMORY out of
+ parseCommandLine. Failing to produce a token means the token is empty. */
+ if (this->isEmpty())
+ {
+ tok->clear();
+ return false;
+ }
+
if (seps == NULL)
seps = " \n\r\t";
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp
index f9c704649..ad5551045 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBar.cpp
@@ -1221,28 +1221,13 @@ ControlBar::ControlBar( void )
ControlBar::~ControlBar( void )
{
- if(m_scienceLayout)
- {
- m_scienceLayout->destroyWindows();
- m_scienceLayout->deleteInstance();
- }
- m_scienceLayout = NULL;
- m_genArrow = NULL;
- if(m_videoManager)
- delete m_videoManager;
- m_videoManager = NULL;
+ if (m_rightHUDCameoWindow && m_rightHUDCameoWindow->winGetUserData())
+ delete m_rightHUDCameoWindow->winGetUserData();
+ // the layouts, the animation managers and every window pointer, in one place
+ shutdownWindows();
- if(m_animateWindowManagerForGenShortcuts)
- delete m_animateWindowManagerForGenShortcuts;
- m_animateWindowManagerForGenShortcuts = NULL;
- if(m_animateWindowManager)
- delete m_animateWindowManager;
- m_animateWindowManager = NULL;
-
- if(m_generalsScreenAnimate)
- delete m_generalsScreenAnimate;
- m_generalsScreenAnimate = NULL;
+ m_genArrow = NULL;
if( m_controlBarSchemeManager )
delete m_controlBarSchemeManager;
@@ -1267,24 +1252,6 @@ ControlBar::~ControlBar( void )
m_commandButtons = button;
} // end while
- if(m_buildToolTipLayout)
- {
- m_buildToolTipLayout->destroyWindows();
- m_buildToolTipLayout->deleteInstance();
- m_buildToolTipLayout = NULL;
- }
-
- if(m_specialPowerLayout)
- {
- m_specialPowerLayout->destroyWindows();
- m_specialPowerLayout->deleteInstance();
- m_specialPowerLayout = NULL;
- }
-
- m_radarAttackGlowWindow = NULL;
-
- if (m_rightHUDCameoWindow && m_rightHUDCameoWindow->winGetUserData())
- delete m_rightHUDCameoWindow->winGetUserData();
} // end ~ControlBar
void ControlBarPopupDescriptionUpdateFunc( WindowLayout *layout, void *param );
@@ -1492,10 +1459,25 @@ struct ControlBarPanelPlacement
Bool weHid; ///< TRUE while the minimised bar is what is hiding it, and not the context
Real designX, designY, designW, designH;
Int placedX, placedY, placedW, placedH;
+ Int slideApplied; ///< how far down applyPanelSlide has actually moved this one, in pixels
};
typedef std::map< GameWindow *, ControlBarPanelPlacement > ControlBarPanelPlacementMap;
static ControlBarPanelPlacementMap theControlBarPlacement;
+//-------------------------------------------------------------------------------------------------
+/** How far layoutPanels has to lift a window to put it back where applyPanelSlide found it. It is
+ * what was recorded on the window, never what the panel's slide says now: applyPanelSlide leaves
+ * windows behind - a plate marker is never moved, and a panel minimised with immediate = TRUE is
+ * marked hidden before anything moves - and taking the panel's offset off one of those lifts a
+ * window that never went down. The bar then climbed a little further off the bottom of the
+ * screen every time the layout was rebuilt, and the tooltip, placed against BackgroundMarker,
+ * climbed with it until it left the screen. Not static: the test calls it. */
+//-------------------------------------------------------------------------------------------------
+Int ControlBar_slideToUndo( Int slideAppliedToWindow, Int panelSlideOffsetNow )
+{
+ return slideAppliedToWindow;
+}
+
//-------------------------------------------------------------------------------------------------
/** Which panel a direct child of ControlBarParent belongs to. Everything not named here rides in
* the middle, which is where the .wnd already puts the money, power and command windows - and
@@ -1737,6 +1719,7 @@ void ControlBar::placeInPanel( GameWindow *win, Int panel,
place.known = TRUE;
place.panel = panel;
place.weHid = FALSE;
+ place.slideApplied = 0;
place.placedX = newX;
place.placedY = newY;
place.placedW = newW;
@@ -1847,6 +1830,18 @@ void ControlBar::applyPanelSlide( void )
const Int wantY = place.placedY - m_panelOrigin.y + offset[ panel ];
if( pos.y != wantY )
child->winSetPosition( pos.x, wantY );
+
+ //
+ // What the window is actually carrying, which is not the same as what its panel's slide says.
+ // The two continues above leave windows behind - a plate marker never moves at all, and a
+ // panel minimised with immediate = TRUE is marked hidden before anything is moved - and
+ // layoutPanels used to take the panel's offset back off every one of them. A window that
+ // never went down came back up, and placeInPanel then read that position as the rectangle it
+ // was authored at: the bar climbed a little further off the bottom of the screen every time
+ // the layout was rebuilt, and the tooltip, which is placed relative to BackgroundMarker,
+ // climbed with it until it left the screen.
+ //
+ place.slideApplied = offset[ panel ];
}
}
@@ -1921,38 +1916,132 @@ void ControlBar::showPanel( Int panel, Bool show, Bool immediate )
} // end showPanel
//-------------------------------------------------------------------------------------------------
-/** Re-anchor the control bar as three panels at one uniform scale. */
+/** Where the command bar's windows actually are, for -uidrill to write down.
+ *
+ * The frame's own position is not the measurement: when the bar drifted, the frame held still and
+ * the money readout, the toolbar column and the general's tabs climbed out of it one rebuild at a
+ * time. So this is the top edge of the highest visible thing the bar owns, which is a single
+ * number that stays put on a bar that stays put. MoneyDisplay is named as well because it is the
+ * one that moved first and furthest. */
//-------------------------------------------------------------------------------------------------
-void ControlBar::layoutPanels( void )
+static void controlBarHighestTop( GameWindow *win, Int *topOut, Int *moneyOut )
{
- GameWindow *parent = m_contextParent[ CP_MASTER ];
- if( parent == NULL || TheDisplay == NULL )
- return;
+ for( GameWindow *child = win->winGetChild(); child; child = child->winGetNext() )
+ {
+ if( !child->winIsHidden() )
+ {
+ Int sx, sy;
+ child->winGetScreenPosition( &sx, &sy );
+ if( sy < *topOut )
+ *topOut = sy;
+ if( strcmp( shortWindowName( child ), "MoneyDisplay" ) == 0 )
+ *moneyOut = sy;
+ }
+ controlBarHighestTop( child, topOut, moneyOut );
+ }
+}
- //
- // A panel that is away, or on its way, is not where this function last put it - and this
- // function reads a window's position to work out what it was authored at. So the slide is
- // taken off first and put back at the end, and a bar that was minimised when the side changed
- // is minimised again without the trip down.
- //
- // Taken off by moving each panel back up by however far it had travelled, not by calling
- // applyPanelSlide - that puts every window back where this function last put it, and
- // ControlBarScheme::init writes the money readout, the two tabs and the toolbar column their
- // own positions immediately before calling us. Restoring the cached y threw every one of
- // those away, so the bar wore ControlBarScheme.ini's x and size with ControlBar.wnd's y: the
- // GLA money sat six units high in its box, and the minimise button drew its tab eleven units
- // below the one its plate paints, which is where the two arrows came from.
- //
- Bool wasAway[ CB_PANEL_COUNT ];
- Int slideOff[ CB_PANEL_COUNT ];
- Int q;
- for( q = 0; q < CB_PANEL_COUNT; q++ )
+/** The first command button on the bar that has a CommandButton behind it - the thing a player's
+ * pointer lands on, and the only kind of window the build tooltip is populated from. */
+static GameWindow *controlBarFirstCommandButton( GameWindow *win )
+{
+ for( GameWindow *child = win->winGetChild(); child; child = child->winGetNext() )
{
- wasAway[ q ] = ( m_panelSlideTo[ q ] > 0.0f );
- slideOff[ q ] = getPanelSlideOffset( q );
+ if( BitTest( child->winGetStyle(), GWS_PUSH_BUTTON ) && GadgetButtonGetData( child ) != NULL )
+ return child;
+ GameWindow *found = controlBarFirstCommandButton( child );
+ if( found )
+ return found;
}
+ return NULL;
+}
+
+void ControlBar_logPlacement( const char *tag, Int frame )
+{
+ if( TheControlBar == NULL || TheDisplay == NULL )
+ return;
+
+ Int top = TheDisplay->getHeight();
+ Int money = -1;
+ TheControlBar->forEachPlacedWindow( &top, &money );
+
+ Int markX, markY;
+ TheControlBar->getBackgroundMarkerPos( &markX, &markY );
+ const ICoord2D *origin = TheControlBar->getPanelOrigin();
+
+ /* Both halves of the shift, because only their difference moves anything: the marker position
+ recorded when the bar was built, and where that same window is on screen right now. */
+ Int liveX = -1, liveY = -1;
+ GameWindow *markerWin = TheWindowManager->winGetWindowFromId(
+ NULL, TheNameKeyGenerator->nameToKey( AsciiString( "ControlBar.wnd:BackgroundMarker" ) ) );
+ if( markerWin )
+ markerWin->winGetScreenPosition( &liveX, &liveY );
+
+ /* The other half of the complaint was tooltips off the screen, so put a real one up - the same
+ call hovering a build button makes - and write down the rectangle it landed in. This is what
+ cleared the build popup: it is placed against BackgroundMarker's *live* screen position, and
+ the drift never moves that window, so with the bar's children two hundred pixels high the
+ popup was measured in exactly the same place as with them home. Kept because it is the only
+ thing that says so. */
+ Int tipX = -1, tipY = -1, tipW = 0, tipH = 0;
+ GameWindow *master = TheControlBar->getMasterParent();
+ GameWindow *button = master ? controlBarFirstCommandButton( master ) : NULL;
+ if( button )
+ {
+ TheControlBar->populateBuildTooltipLayout( (const CommandButton *)GadgetButtonGetData( button ) );
+ WindowLayout *tip = TheControlBar->getBuildTooltipLayout();
+ GameWindow *tipWin = tip ? tip->getFirstWindow() : NULL;
+ if( tipWin )
+ {
+ tipWin->winGetScreenPosition( &tipX, &tipY );
+ tipWin->winGetSize( &tipW, &tipH );
+ }
+ if( tip )
+ tip->hide( TRUE );
+ }
+
+ DEBUG_LOG(("UIDRILL: frame %d %s top %d money %d origin (%d,%d) marker (%d,%d) live (%d,%d) tip (%d,%d %dx%d) screen %dx%d\n",
+ frame, tag, top, money, origin->x, origin->y, markX, markY, liveX, liveY,
+ tipX, tipY, tipW, tipH,
+ TheDisplay->getWidth(), TheDisplay->getHeight()));
+}
+
+void ControlBar::forEachPlacedWindow( Int *topOut, Int *moneyOut )
+{
+ GameWindow *parent = m_contextParent[ CP_MASTER ];
+ if( parent == NULL )
+ return;
+ controlBarHighestTop( parent, topOut, moneyOut );
+}
+
+//-------------------------------------------------------------------------------------------------
+/** Put the slide away: every window back up by however far it actually travelled, and all three
+ * panels declared home.
+ *
+ * Anything that reads a window's screen position has to run after this. ControlBarScheme::init
+ * is the one that does - it asks each parent where it is on screen and writes the money readout,
+ * the two tabs and the toolbar column their own positions relative to that answer - and it used
+ * to ask while the bar was still on its way down. The answer was the slid position, so the
+ * children came out right for a slid parent; then layoutPanels lifted the parent and every one of
+ * those children rode up with it, and placeInPanel read the lifted position as the rectangle they
+ * were authored at. A few pixels a rebuild. Toggle the bar and change side a dozen times and
+ * the money box, the toolbar column and the general's tabs are stranded a third of the way up an
+ * empty screen with the plates still painted at the bottom, and the build tooltip - which is
+ * placed against BackgroundMarker - has left the top of the picture.
+ *
+ * Taken off per window rather than per panel, and by what each window is actually carrying:
+ * applyPanelSlide leaves windows behind (a plate marker never moves, a panel minimised with
+ * immediate = TRUE is marked hidden before anything moves), and lifting one of those lifts a
+ * window that never went down. Not by calling applyPanelSlide with the slide zeroed either -
+ * that puts every window back at the y layoutPanels last handed out, which throws away exactly
+ * the ControlBarScheme.ini positions the bar is being rebuilt to wear.
+ */
+//-------------------------------------------------------------------------------------------------
+void ControlBar::clearPanelSlide( void )
+{
+ GameWindow *parent = m_contextParent[ CP_MASTER ];
- for( GameWindow *slid = parent->winGetChild(); slid; slid = slid->winGetNext() )
+ for( GameWindow *slid = parent ? parent->winGetChild() : NULL; slid; slid = slid->winGetNext() )
{
ControlBarPanelPlacementMap::iterator it = theControlBarPlacement.find( slid );
if( it == theControlBarPlacement.end() || it->second.known == FALSE )
@@ -1965,20 +2054,44 @@ void ControlBar::layoutPanels( void )
slid->winHide( FALSE );
place.weHid = FALSE;
}
- if( slideOff[ place.panel ] != 0 )
+ const Int undo = ControlBar_slideToUndo( place.slideApplied, getPanelSlideOffset( place.panel ) );
+ if( undo != 0 )
{
ICoord2D pos;
slid->winGetPosition( &pos.x, &pos.y );
- slid->winSetPosition( pos.x, pos.y - slideOff[ place.panel ] );
+ slid->winSetPosition( pos.x, pos.y - undo );
+ place.slideApplied = 0;
}
}
- for( q = 0; q < CB_PANEL_COUNT; q++ )
+ for( Int q = 0; q < CB_PANEL_COUNT; q++ )
{
m_panelSlide[ q ] = 0.0f;
m_panelSlideTo[ q ] = 0.0f;
m_panelHidden[ q ] = FALSE;
}
+}
+
+//-------------------------------------------------------------------------------------------------
+/** Re-anchor the control bar as three panels at one uniform scale.
+ *
+ * A panel that is away, or on its way, is not where this function last put it - and this function
+ * reads a window's position to work out what it was authored at. So the slide comes off first
+ * and goes back on at the end, and a bar that was minimised when the side changed is minimised
+ * again without the trip down. */
+//-------------------------------------------------------------------------------------------------
+void ControlBar::layoutPanels( void )
+{
+ GameWindow *parent = m_contextParent[ CP_MASTER ];
+ if( parent == NULL || TheDisplay == NULL )
+ return;
+
+ Bool wasAway[ CB_PANEL_COUNT ];
+ Int q;
+ for( q = 0; q < CB_PANEL_COUNT; q++ )
+ wasAway[ q ] = ( m_panelSlideTo[ q ] > 0.0f );
+
+ clearPanelSlide();
const Real dispW = (Real)TheDisplay->getWidth();
const Real dispH = (Real)TheDisplay->getHeight();
@@ -2087,7 +2200,97 @@ void ControlBar::init( void )
//Added this check because the builder uses the ControlBar, but doesn't care about
//the GUI.
if( TheWindowManager )
+ initWindows();
+
+} // end init
+
+//-------------------------------------------------------------------------------------------------
+/** Drop every window the bar is holding. Called before the windows are looked up again, and it is
+ * the layouts that matter: they own windows built against the old screen size, and the animation
+ * managers hold pointers into them. */
+//-------------------------------------------------------------------------------------------------
+void ControlBar::shutdownWindows( void )
+{
+ Int i;
+
+ if( m_scienceLayout )
+ {
+ m_scienceLayout->destroyWindows();
+ m_scienceLayout->deleteInstance();
+ }
+ m_scienceLayout = NULL;
+
+ if( m_buildToolTipLayout )
{
+ m_buildToolTipLayout->destroyWindows();
+ m_buildToolTipLayout->deleteInstance();
+ }
+ m_buildToolTipLayout = NULL;
+ m_showBuildToolTipLayout = FALSE;
+
+ if( m_specialPowerLayout )
+ {
+ m_specialPowerLayout->destroyWindows();
+ m_specialPowerLayout->deleteInstance();
+ }
+ m_specialPowerLayout = NULL;
+
+ //
+ // Each of these remembers the windows it is animating, so a manager that outlived its windows
+ // would walk freed memory on its next update.
+ //
+ if( m_videoManager )
+ delete m_videoManager;
+ m_videoManager = NULL;
+ if( m_animateWindowManager )
+ delete m_animateWindowManager;
+ m_animateWindowManager = NULL;
+ if( m_generalsScreenAnimate )
+ delete m_generalsScreenAnimate;
+ m_generalsScreenAnimate = NULL;
+ if( m_animateWindowManagerForGenShortcuts )
+ delete m_animateWindowManagerForGenShortcuts;
+ m_animateWindowManagerForGenShortcuts = NULL;
+
+ for( i = 0; i < NUM_CONTEXT_PARENTS; i++ )
+ m_contextParent[ i ] = NULL;
+ for( i = 0; i < MAX_COMMANDS_PER_SET; i++ )
+ m_commandWindows[ i ] = NULL;
+ for( i = 0; i < MAX_PURCHASE_SCIENCE_RANK_1; i++ )
+ m_sciencePurchaseWindowsRank1[ i ] = NULL;
+ for( i = 0; i < MAX_PURCHASE_SCIENCE_RANK_3; i++ )
+ m_sciencePurchaseWindowsRank3[ i ] = NULL;
+ for( i = 0; i < MAX_PURCHASE_SCIENCE_RANK_8; i++ )
+ m_sciencePurchaseWindowsRank8[ i ] = NULL;
+ for( i = 0; i < MAX_RIGHT_HUD_UPGRADE_CAMEOS; i++ )
+ m_rightHUDUpgradeCameos[ i ] = NULL;
+ for( i = 0; i < MAX_SPECIAL_POWER_SHORTCUTS; i++ )
+ {
+ m_specialPowerShortcutButtons[ i ] = NULL;
+ m_specialPowerShortcutButtonParents[ i ] = NULL;
+ }
+ m_specialPowerShortcutParent = NULL;
+ m_currentlyUsedSpecialPowersButtons = 0;
+ m_rightHUDWindow = NULL;
+ m_rightHUDCameoWindow = NULL;
+ m_rightHUDUnitSelectParent = NULL;
+ m_communicatorButton = NULL;
+ m_radarAttackGlowWindow = NULL;
+ m_animateDownWindow = NULL;
+ m_multiSelectTiles.clear();
+ m_sideSelectAnimateDown = FALSE;
+
+} // end shutdownWindows
+
+//-------------------------------------------------------------------------------------------------
+/** Look up every window the bar drives, and lay the bar out. Re-callable: a resolution change
+ * rebuilds ControlBar.wnd and then calls this instead of replacing the whole ControlBar. */
+//-------------------------------------------------------------------------------------------------
+void ControlBar::initWindows( void )
+{
+ {
+ shutdownWindows();
+
//
// the control bar has several windows that make up our context sensitive interface, we
// want those parent windows so that we can easily hide and show them to make the
@@ -2335,7 +2538,7 @@ void ControlBar::init( void )
switchToContext( CB_CONTEXT_NONE, NULL );
}
-} // end init
+} // end initWindows
//-------------------------------------------------------------------------------------------------
/** Reset the context sensitive control bar GUI */
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp
index c88b15d29..02f2850e7 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarScheme.cpp
@@ -430,6 +430,14 @@ void ControlBarScheme::init(void)
{
if(TheControlBar)
{
+ //
+ // Before anything below asks a window where it is on screen. switchControlBarStage sends
+ // the panels home but they travel there over a fifth of a second, so on its own it leaves
+ // every screen position read in this function reading a bar that is still on its way - and
+ // the money readout, the two tabs and the toolbar column are all placed from those reads.
+ // See ControlBar::clearPanelSlide.
+ //
+ TheControlBar->clearPanelSlide();
TheControlBar->switchControlBarStage(CONTROL_BAR_STAGE_DEFAULT);
TheControlBar->updateBuildQueueDisabledImages( m_buttonQueueImage );
TheControlBar->updateRightHUDImage(m_rightHUDImage);
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp
index a0dd09c18..fe94949f8 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/LanLobbyMenu.cpp
@@ -444,7 +444,12 @@ void LanLobbyMenuInit( WindowLayout *layout, void *userData )
//UnicodeString txtInput;
//txtInput.translate(IPs.getMachineName());
LANPreferences prefs;
- defaultName = prefs.getUserName();
+ /* -lanname beats the preferences file, because two copies on one machine share that file and a
+ host denies the second one as a duplicate name. See parseLanName in CommandLine.cpp. */
+ if (TheGlobalData->m_lanPlayerName.isNotEmpty())
+ defaultName.translate( TheGlobalData->m_lanPlayerName );
+ else
+ defaultName = prefs.getUserName();
while (defaultName.getLength() > g_lanPlayerNameLength)
defaultName.removeLastChar();
GadgetTextEntrySetText( textEntryPlayerName, defaultName);
@@ -534,9 +539,14 @@ static void shutdownComplete( WindowLayout *layout )
//-------------------------------------------------------------------------------------------------
void LanLobbyMenuShutdown( WindowLayout *layout, void *userData )
{
- LANPreferences prefs;
- prefs["UserName"] = UnicodeStringToQuotedPrintable(GadgetTextEntryGetText( textEntryPlayerName ));
- prefs.write();
+ /* A name that came from -lanname is this copy's, not this machine's: writing it back would put
+ the second copy's name in the preferences both copies read. */
+ if (TheGlobalData->m_lanPlayerName.isEmpty())
+ {
+ LANPreferences prefs;
+ prefs["UserName"] = UnicodeStringToQuotedPrintable(GadgetTextEntryGetText( textEntryPlayerName ));
+ prefs.write();
+ }
DestroyGameInfoWindow();
// hide menu
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp
index 41ca16bb2..8d244c854 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/MainMenu.cpp
@@ -60,6 +60,7 @@
#include "GameClient/CampaignManager.h"
#include "GameClient/HotKey.h"
#include "GameClient/GameClient.h"
+#include "GameClient/GUICallbacks.h"
#include "GameLogic/GameLogic.h"
#include "GameLogic/ScriptEngine.h"
#include "GameNetwork/GameSpyOverlay.h"
@@ -777,7 +778,15 @@ void DeclineResolution()
TheInGameUI->recreateControlBar();
- TheShell->push( AsciiString("Menus/MainMenu.wnd") );
+ //
+ // Same rule as accepting the change: in a match the thing on screen is the battlefield, and
+ // the command bar comes back hidden from its layouts. Pushing the main menu here put the
+ // menu over a running game.
+ //
+ if( TheGameLogic->isInGame() && !TheGameLogic->isInShellGame() )
+ ShowControlBar( TRUE );
+ else
+ TheShell->push( AsciiString("Menus/MainMenu.wnd") );
}
}
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp
index aa344eb1e..b6d191442 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/OptionsMenu.cpp
@@ -215,6 +215,12 @@ DisplaySettings oldDispSettings, newDispSettings;
Bool dispChanged = FALSE;
extern Int timer;
extern void DoResolutionDialog();
+
+//
+// Set by saveOptions when the resolution really changed, acted on by applyPendingShellRebuild once
+// the options layout has been taken down and nothing is reading a window out of it any more.
+//
+static Bool pendingShellRebuild = FALSE;
//
static Bool ignoreSelected = FALSE;
@@ -1343,28 +1349,15 @@ static void saveOptions( void )
newDispSettings.bitDepth = bitDepth;
newDispSettings.windowed = TheDisplay->getWindowed();
- // delete the shell
- delete TheShell;
- TheShell = NULL;
-
- // create the shell
- TheShell = MSGNEW("GameClientSubsystem") Shell;
- if( TheShell )
- TheShell->init();
-
- TheInGameUI->recreateControlBar();
-
//
- // Out of a match the shell is what you are looking at, so it opens on the main menu.
- // In one, the menus were rebuilt for the next time you want them and the thing on
- // screen is the battlefield: pushing the main menu over a running game is why the
- // resolution list used to be greyed out in-game at all. The command bar has just been
- // built from its layouts and comes up hidden, so it is put back.
+ // The shell and the command bar are rebuilt after this function returns, not here.
+ // Every static GameWindow * in this file points into the options layout, the options
+ // layout belongs to the shell, and the rest of saveOptions goes on reading those
+ // pointers - the volume sliders and the gamma slider are all below this block.
+ // Deleting the shell in the middle of it read four windows back out of freed pool
+ // blocks.
//
- if( TheGameLogic->isInGame() && !TheGameLogic->isInShellGame() )
- ShowControlBar( TRUE );
- else
- TheShell->push( AsciiString("Menus/MainMenu.wnd") );
+ pendingShellRebuild = TRUE;
}
}
}
@@ -1548,6 +1541,181 @@ static void DestroyOptionsLayout() {
OptionsLayout = NULL;
}
+//
+// Every window on screen was laid out against the old size, so the shell is rebuilt from the
+// layouts. This runs after the options layout is gone: it deletes the shell those windows belong
+// to, so nothing that still holds one of them may run afterwards. A mode change that keeps the
+// resolution - fullscreen to borderless on a screen the game was already filling - changes no
+// rectangle and never gets here.
+//
+static void applyPendingShellRebuild( void )
+{
+ if( !pendingShellRebuild )
+ return;
+ pendingShellRebuild = FALSE;
+
+ delete TheShell;
+ TheShell = NULL;
+
+ TheShell = MSGNEW("GameClientSubsystem") Shell;
+ TheShell->init();
+
+ TheInGameUI->recreateControlBar();
+
+ //
+ // Out of a match the shell is what you are looking at, so it opens on the main menu. In one,
+ // the menus were rebuilt for the next time you want them and the thing on screen is the
+ // battlefield: pushing the main menu over a running game is why the resolution list used to be
+ // greyed out in-game at all. The command bar has just been built from its layouts and comes up
+ // hidden, so it is put back.
+ //
+ if( TheGameLogic->isInGame() && !TheGameLogic->isInShellGame() )
+ ShowControlBar( TRUE );
+ else
+ TheShell->push( AsciiString("Menus/MainMenu.wnd") );
+}
+
+//
+// -resdrill: the resolution change a player makes in the middle of a match, made from a script.
+//
+// It lives here rather than in the drill's own file because the sequence is the thing under test -
+// reset the device, throw the shell away, build the command bar again while the match that owns it
+// keeps running - and a copy of that sequence somewhere else would be a copy that can go right
+// while the real one goes wrong. Everything below the mode change is applyPendingShellRebuild,
+// which is what the options menu itself reaches on its way out.
+//
+void ResolutionDrillApply( Int xres, Int yres )
+{
+ if( TheDisplay == NULL )
+ return;
+
+ const Int wasX = TheDisplay->getWidth();
+ const Int wasY = TheDisplay->getHeight();
+ const Int bitDepth = TheDisplay->getBitDepth();
+
+ // With no size asked for, take the first mode the device offers that is not the one on screen.
+ // A drill that had to be told the monitor's modes would be a drill nobody runs on a new machine.
+ if( xres <= 0 || yres <= 0 )
+ {
+ xres = yres = 0;
+ for( Int i = 0; i < TheDisplay->getDisplayModeCount(); i++ )
+ {
+ Int mx, my, mb;
+ TheDisplay->getDisplayModeDescription( i, &mx, &my, &mb );
+ if( mx >= 800 && my >= 600 && ( mx != wasX || my != wasY ) )
+ {
+ xres = mx;
+ yres = my;
+ break;
+ }
+ }
+ }
+
+ if( xres <= 0 || yres <= 0 || ( xres == wasX && yres == wasY ) )
+ {
+ DEBUG_LOG(("RESDRILL: no second mode to switch to, still %dx%d\n", wasX, wasY));
+ return;
+ }
+
+ // which entry of the dropdown that is: the combo is filled straight off the device's mode list,
+ // so the entry index and the mode index are the same number
+ Int modeIndex = -1;
+ for( Int m = 0; m < TheDisplay->getDisplayModeCount(); m++ )
+ {
+ Int mx, my, mb;
+ TheDisplay->getDisplayModeDescription( m, &mx, &my, &mb );
+ if( mx == xres && my == yres )
+ {
+ modeIndex = m;
+ break;
+ }
+ }
+ if( modeIndex < 0 )
+ {
+ DEBUG_LOG(("RESDRILL: %dx%d is not a mode this device offers\n", xres, yres));
+ return;
+ }
+
+ DEBUG_LOG(("RESDRILL: %dx%d -> %dx%d (mode %d, bit depth %d)\n",
+ wasX, wasY, xres, yres, modeIndex, bitDepth));
+
+ //
+ // From here it is the player's own route and nothing else: open the options menu the way the
+ // in-game quit menu opens it, put the dropdown on the mode we want, and press Accept. Doing the
+ // device change directly instead - which this used to - skips the part that broke, which is the
+ // shell being torn down and rebuilt from inside a shell window's own message handler while the
+ // options layout is still on the stack. QuitMenu.cpp's buttonOptions branch is the three lines
+ // below.
+ //
+ WindowLayout *optLayout = TheShell->getOptionsLayout( TRUE );
+ if( optLayout == NULL )
+ {
+ DEBUG_LOG(("RESDRILL: no options layout to open\n"));
+ return;
+ }
+ optLayout->runInit();
+ optLayout->hide( FALSE );
+ optLayout->bringForward();
+
+ if( comboBoxResolution == NULL )
+ {
+ DEBUG_LOG(("RESDRILL: the options menu came up without its resolution dropdown\n"));
+ return;
+ }
+ GadgetComboBoxSetSelectedPos( comboBoxResolution, modeIndex );
+
+ GameWindow *parent = TheWindowManager->winGetWindowFromId(
+ NULL, TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:OptionsMenuParent" ) ) );
+ NameKeyType acceptID = TheNameKeyGenerator->nameToKey( AsciiString( "OptionsMenu.wnd:ButtonAccept" ) );
+ GameWindow *accept = TheWindowManager->winGetWindowFromId( parent, acceptID );
+ if( parent == NULL || accept == NULL )
+ {
+ DEBUG_LOG(("RESDRILL: no Accept button on the options menu (parent %p, button %p)\n",
+ parent, accept));
+ return;
+ }
+
+ DEBUG_LOG(("RESDRILL: pressing Accept\n"));
+ TheWindowManager->winSendSystemMsg( parent, GBM_SELECTED, (WindowMsgData)accept, acceptID );
+
+ DEBUG_LOG(("RESDRILL: shell and command bar rebuilt at %dx%d\n",
+ TheDisplay->getWidth(), TheDisplay->getHeight()));
+}
+
+//
+// Accept leaves the "keep this resolution?" box on screen, and a player answers it - so the drill
+// has to as well. Cancel is the longer of the two answers: DeclineResolution changes the mode back
+// and rebuilds the shell and the command bar a *second* time, from inside the message box's own
+// GBM_SELECTED handler, over windows the first rebuild already replaced. Answering it on a later
+// frame rather than in the same breath as Accept is the point; the box a player sees has been on
+// screen for a second or two by the time it is clicked.
+//
+void ResolutionDrillDismiss( Bool accept )
+{
+ extern GameWindow *resAcceptMenu; // MainMenu.cpp owns it, DoResolutionDialog fills it in
+
+ if( resAcceptMenu == NULL )
+ {
+ DEBUG_LOG(("RESDRILL: no resolution dialog to answer\n"));
+ return;
+ }
+
+ NameKeyType buttonID = TheNameKeyGenerator->nameToKey(
+ AsciiString( accept ? "MessageBox.wnd:ButtonOk" : "MessageBox.wnd:ButtonCancel" ) );
+ GameWindow *button = TheWindowManager->winGetWindowFromId( resAcceptMenu, buttonID );
+ if( button == NULL )
+ {
+ DEBUG_LOG(("RESDRILL: the resolution dialog has no %s button\n", accept ? "Ok" : "Cancel"));
+ return;
+ }
+
+ DEBUG_LOG(("RESDRILL: answering the resolution dialog with %s\n", accept ? "Ok" : "Cancel"));
+ TheWindowManager->winSendSystemMsg( resAcceptMenu, GBM_SELECTED, (WindowMsgData)button, buttonID );
+
+ DEBUG_LOG(("RESDRILL: after the dialog the display is %dx%d\n",
+ TheDisplay->getWidth(), TheDisplay->getHeight()));
+}
+
static void showAdvancedOptions()
{
WinAdvancedDisplay->winHide(FALSE);
@@ -2308,10 +2476,14 @@ WindowMsgHandledType OptionsMenuSystem( GameWindow *window, UnsignedInt msg,
if(GameSpyIsOverlayOpen(GSOVERLAY_OPTIONS))
+ {
GameSpyCloseOverlay(GSOVERLAY_OPTIONS);
+ applyPendingShellRebuild();
+ }
else
{
DestroyOptionsLayout();
+ applyPendingShellRebuild();
if (dispChanged)
{
DoResolutionDialog();
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp
index 80fd310cf..eff1d3b00 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Shell/Shell.cpp
@@ -510,6 +510,17 @@ void Shell::showShell( Bool runInit )
//else
TheShell->push( AsciiString("Menus/MainMenu.wnd") );
}
+
+ /* -lanlobby: go straight to the LAN screen, on top of the main menu that was just pushed, which
+ is what clicking Multiplayer would have done. The flag is spent here rather than read again,
+ because showShell() also runs on the way back out of a game and the switch is about how this
+ copy of the game starts, not where it lands every time. */
+ if( TheGlobalData->m_lanLobbyOnStart )
+ {
+ TheWritableGlobalData->m_lanLobbyOnStart = FALSE;
+ TheShell->push( AsciiString("Menus/LanLobbyMenu.wnd") );
+ }
+
m_isShellActive = TRUE;
} // end showShell
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
index 0064bfb56..14caf714f 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp
@@ -7833,21 +7833,45 @@ void InGameUI::resetIdleWorker( void )
void InGameUI::recreateControlBar( void )
{
+ //
+ // deleteInstance() hands the block back to the pool without taking the window off the manager's
+ // list and without touching its children, so the freed root stayed in m_windowList and the pool
+ // then handed the same block to the root created two lines later. The list was a ring of
+ // half-freed windows after that, and the first winRepaint that reached one drew a push button
+ // whose overlay image was whatever the block now held. Out of a match nothing showed because
+ // the bar is hidden and winRepaint skips hidden windows; in one it was the crash on changing
+ // resolution. winDestroy unlinks the whole tree and defers the free to the window manager's own
+ // pass, which is also what keeps the pointers below readable until then.
+ //
GameWindow *win = TheWindowManager->winGetWindowFromId(NULL, TheNameKeyGenerator->nameToKey(AsciiString("ControlBar.wnd")));
if(win)
- win->deleteInstance();
-
- m_idleWorkerWin = NULL;
-
+ TheWindowManager->winDestroy(win);
+
+ m_idleWorkerWin = NULL;
+
createControlBar();
-
+
+ //
+ // The bar is rebuilt from its windows rather than replaced. Replacing it re-parsed
+ // CommandButton.ini and CommandSet.ini and handed out new CommandButton addresses, while every
+ // const CommandButton * already held by something in the running game - a production queue, a
+ // hunt update, the partition manager, the academy - went on pointing at the freed ones.
+ //
if(TheControlBar)
{
- delete TheControlBar;
- TheControlBar = NEW ControlBar;
- TheControlBar->init();
- }
+ TheControlBar->initWindows();
+ //
+ // The two things init() cannot do for itself: the shortcut strip belongs to one general, and
+ // the scheme is that general's artwork. Both were applied to windows that no longer exist.
+ //
+ if(TheGameLogic->isInGame() && !TheGameLogic->isInShellGame())
+ {
+ Player *localPlayer = ThePlayerList->getLocalPlayer();
+ TheControlBar->initSpecialPowershortcutBar(localPlayer);
+ TheControlBar->setControlBarSchemeByPlayer(localPlayer);
+ }
+ }
}
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp
index 8392564d4..cdc0a997b 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Input/Mouse.cpp
@@ -981,6 +981,43 @@ void Mouse::resetTooltipDelay( void )
m_displayTooltip = FALSE;
}
+//-------------------------------------------------------------------------------------------------
+/** Where the tooltip box goes for a pointer at (mouseX,mouseY).
+ *
+ * EA's version was the first two tests only, with a @todo on top of them saying the tips still had
+ * to be kept on screen. Each test is a flip, not a clamp: the box jumps by its own width or height
+ * to the other side of the pointer, which is the right answer at the right and bottom edges and no
+ * answer at all at the other two. A tooltip wider than the pointer's distance from the left edge
+ * flips to a negative x; a tall one - the build descriptions run several lines - flips off the top
+ * when the pointer is high up, and the text is then drawn where nobody can read it. So keep the
+ * flip, which is what puts the box on the roomier side, and hold the result inside the screen
+ * afterwards. Letting the pointer sit on the box beats losing the words underneath it. */
+//-------------------------------------------------------------------------------------------------
+void Mouse::placeTooltip( Int mouseX, Int mouseY, Int width, Int height,
+ Int minX, Int minY, Int maxX, Int maxY,
+ Int *xOut, Int *yOut )
+{
+ Int xPos = mouseX + 20;
+ Int yPos = mouseY;
+
+ if( xPos + width + 4 > maxX ) // +4 for spill
+ xPos -= 20 + width;
+ if( yPos + height + 4 > maxY ) // +4 for spill
+ yPos -= height;
+
+ if( xPos + width + 4 > maxX )
+ xPos = maxX - width - 4;
+ if( yPos + height + 4 > maxY )
+ yPos = maxY - height - 4;
+ if( xPos < minX )
+ xPos = minX;
+ if( yPos < minY )
+ yPos = minY;
+
+ *xOut = xPos;
+ *yOut = yPos;
+}
+
//-------------------------------------------------------------------------------------------------
/** Draw the mouse tooltip if one is set */
//-------------------------------------------------------------------------------------------------
@@ -990,25 +1027,13 @@ void Mouse::drawTooltip( void )
return;
}
- /// @todo: Still need to put in display logic so it puts the tool tips in a visable position on the edge of the screen
if( m_displayTooltip && TheDisplay && m_tooltipDisplayString && (m_tooltipDisplayString->getTextLength() > 0) && !m_isTooltipEmpty)
{
Int width, xPos;
Int height, yPos;
m_tooltipDisplayString->getSize(&width,&height);
- xPos = m_currMouse.pos.x + 20;
- yPos = m_currMouse.pos.y;// + 20;
-
- if( xPos + width + 4 > m_maxX ) // +4 for spill
- {
- //xPos = m_maxX - width;
- xPos -= 20 + width;
- }
- if( yPos + height + 4 > m_maxY ) // +4 for spill
- {
- //yPos = m_maxY - height;
- yPos -= /*40 +*/ height;
- }
+ placeTooltip( m_currMouse.pos.x, m_currMouse.pos.y, width, height,
+ m_minX, m_minY, m_maxX, m_maxY, &xPos, &yPos );
Int boxWidth = (m_tooltipAnimateBackground)?(min(width, m_highlightPos)):width;
diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp
index d45d86814..994971830 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/LANAPIhandlers.cpp
@@ -260,9 +260,14 @@ void LANAPI::handleRequestJoin( LANMessage *msg, UnsignedInt senderIP )
}
#endif
- // check for a duplicate serial
+ /* Check for a duplicate serial - unless both ends are on loopback, which is two copies
+ of the game on one machine and therefore one installation, one registry and one
+ serial by construction. EA's check is the retail one-key-one-seat rule and it stays
+ on for every address that could be a second machine; here it would refuse the join
+ every time and there would be no way to play a LAN game against yourself at all. */
AsciiString s;
- for (player = 0; canJoin && player<MAX_SLOTS; ++player)
+ const Bool sameMachine = IsLoopbackIP( m_localIP ) && IsLoopbackIP( senderIP );
+ for (player = 0; canJoin && !sameMachine && player<MAX_SLOTS; ++player)
{
LANGameSlot *slot = m_currentGame->getLANSlot(player);
s.clear();
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 86307101e..f9d208029 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -17,6 +17,7 @@
#include "test_harness.h"
#include "Common/AsciiString.h"
+#include "Common/CommandLine.h"
#include "Common/UnicodeString.h"
#include "Common/GameMemory.h"
#include "Common/NameKeyGenerator.h"
@@ -1228,6 +1229,7 @@ TEST(bitflags_types_keep_their_own_name_tables)
/* GameWindowManager.cpp: destroying a modal window that is not the top of the modal stack
used to leave its entry behind, holding a pointer to freed memory. */
#include "GameClient/GameWindow.h"
+#include "GameClient/Mouse.h"
TEST(destroying_a_modal_window_takes_it_out_of_the_stack_wherever_it_sits)
{
@@ -6639,6 +6641,68 @@ TEST(a_netgame_slot_list_is_the_player_order_on_every_machine)
CHECK_EQ( 2, ResolveHostList( "10.0.0.1,,10.0.0.2", ips, MAX_SLOTS ) );
}
+TEST(two_copies_on_one_machine_each_get_their_own_lobby_address_and_name)
+{
+ /* The LAN lobby binds one UDP port with no SO_REUSEADDR, and both copies read the same
+ Options.ini and the same LAN preferences - so the address and the name have to come from
+ somewhere the two copies can disagree about, which is the command line. */
+ GlobalData *saved = TheWritableGlobalData;
+ TheWritableGlobalData = NEW GlobalData;
+
+ CHECK_EQ( 0u, TheGlobalData->m_defaultIP ); // nothing chosen: the lobby picks an address itself
+ CHECK( TheGlobalData->m_lanPlayerName.isEmpty() );
+
+ char exe[] = "generals.exe";
+ char lanIP[] = "-lanip";
+ char second[] = "127.0.0.2";
+ char *argvIP[] = { exe, lanIP, second };
+ parseCommandLine( 3, argvIP );
+ CHECK_EQ( 0x7f000002, TheGlobalData->m_defaultIP ); // host order, the order SetLocalIP wants
+
+ // a malformed address leaves the last usable one alone rather than binding INADDR_NONE
+ char nonsense[] = "999.1.1.1";
+ char *argvBadIP[] = { exe, lanIP, nonsense };
+ parseCommandLine( 3, argvBadIP );
+ CHECK_EQ( 0x7f000002, TheGlobalData->m_defaultIP );
+
+ char lanName[] = "-lanname";
+ char who[] = "Player 2";
+ char *argvName[] = { exe, lanName, who };
+ parseCommandLine( 3, argvName );
+ CHECK_STR( TheGlobalData->m_lanPlayerName.str(), "Player 2" );
+
+ // -lanlobby opens the LAN screen, and turns the shell map off because the main menu it stacks
+ // on top of is only pushed when there is no shell map
+ CHECK( !TheGlobalData->m_lanLobbyOnStart );
+ CHECK( TheGlobalData->m_shellMapOn );
+ char lanLobby[] = "-lanlobby";
+ char *argvLobby[] = { exe, lanLobby };
+ parseCommandLine( 2, argvLobby );
+ CHECK( TheGlobalData->m_lanLobbyOnStart );
+ CHECK( !TheGlobalData->m_shellMapOn );
+
+ delete TheWritableGlobalData;
+ TheWritableGlobalData = saved;
+}
+
+TEST(the_serial_check_is_waived_only_between_two_addresses_on_this_machine)
+{
+ /* Two copies of the game on one machine are one installation and therefore one CD key, so the
+ host's duplicate-serial check would refuse the join every time. It is waived for a pair of
+ loopback addresses and for nothing else - anything that could be a second machine still
+ answers to the retail rule. */
+ CHECK( IsLoopbackIP( 0x7f000001 ) );
+ CHECK( IsLoopbackIP( 0x7f000002 ) );
+ CHECK( IsLoopbackIP( 0x7f000000 ) ); // the whole of 127.0.0.0/8 routes to loopback
+ CHECK( IsLoopbackIP( 0x7fffffff ) );
+
+ CHECK( !IsLoopbackIP( 0x7e000001 ) ); // 126.x is somebody else
+ CHECK( !IsLoopbackIP( 0x80000001 ) ); // and so is 128.x
+ CHECK( !IsLoopbackIP( 0x0a000001 ) ); // the private ranges a real LAN game runs on
+ CHECK( !IsLoopbackIP( 0xac13287e ) );
+ CHECK( !IsLoopbackIP( 0 ) ); // INADDR_ANY is not an address
+}
+
/* A replay is checked by comparing the CRCs it carries against the ones playback recomputes, one
for one, out of a queue. A game played over a network never gets its frame 0 CRC into the file
- the logic makes it after that frame's commands have already gone out, so it is never sent,
@@ -9575,3 +9639,224 @@ TEST(peace_time_is_off_while_a_computer_player_is_in_the_lobby)
delete TheWritableGlobalData;
TheWritableGlobalData = saved;
}
+
+/* nextToken used to return false on a spent source without touching the caller's token, so the
+ token still held the *previous* one. Every loop written as "walk until the token comes back
+ empty" then never ended. */
+TEST(asciistring_nextToken_empties_the_token_when_the_source_runs_out)
+{
+ AsciiString path( "one\\two" );
+ AsciiString tok;
+
+ CHECK( path.nextToken( &tok, "\\/" ) );
+ CHECK_STR( tok.str(), "one" );
+ CHECK( path.nextToken( &tok, "\\/" ) );
+ CHECK_STR( tok.str(), "two" );
+
+ CHECK( !path.nextToken( &tok, "\\/" ) );
+ CHECK_EQ( tok.getLength(), 0 );
+
+ // and the same answer when the source was empty to begin with
+ AsciiString none;
+ AsciiString held( "stale" );
+ CHECK( !none.nextToken( &held, "\\/" ) );
+ CHECK_EQ( held.getLength(), 0 );
+
+ // a token that is the source itself is still refused, and left as it was
+ AsciiString self( "a\\b" );
+ CHECK( !self.nextToken( &self, "\\/" ) );
+ CHECK_STR( self.str(), "a\\b" );
+}
+
+/* -map "Maps\Twilight Flame\Twilight Flame.map" loses its quotes to WinMain's tokenizer and
+ reaches this function as "Maps\Twilight". With no .map to stop on it grew a string one token
+ at a time until AsciiString's 32767-byte ceiling threw ERROR_OUT_OF_MEMORY out of
+ parseCommandLine, GameEngine::init caught it and ran on to its tail, and the first frame
+ faulted on a NULL TheGameLogic - reported as a crash in update(), with no main menu. */
+TEST(map_path_conversion_terminates_on_a_path_with_no_map_file)
+{
+ AsciiString longForm( "Maps\\Twilight Flame\\Twilight Flame.map" );
+ ConvertShortMapPathToLongMapPath( longForm );
+ CHECK_STR( longForm.str(), "Maps\\Twilight Flame\\Twilight Flame.map" );
+
+ AsciiString shortForm( "Maps\\Alpine Assault.map" );
+ ConvertShortMapPathToLongMapPath( shortForm );
+ CHECK_STR( shortForm.str(), "Maps\\Alpine Assault\\Alpine Assault.map" );
+
+ AsciiString truncated( "Maps\\Twilight" );
+ ConvertShortMapPathToLongMapPath( truncated );
+ CHECK_STR( truncated.str(), "Maps\\Twilight" );
+
+ AsciiString noSeparator( "Twilight Flame.map" );
+ ConvertShortMapPathToLongMapPath( noSeparator );
+ CHECK_STR( noSeparator.str(), "Twilight Flame.map" );
+
+ AsciiString trailing( "Maps\\Twilight\\" );
+ ConvertShortMapPathToLongMapPath( trailing );
+ CHECK_STR( trailing.str(), "Maps\\Twilight\\" );
+}
+
+/* ControlBar.cpp: layoutPanels used to lift every window in a minimised panel by that panel's
+ slide, including the ones applyPanelSlide never moved. Each rebuild of the layout lifted them
+ again, placeInPanel then recorded the lifted position as the authored one, and the bar walked
+ off the top of its own strip - taking the build tooltip, which is placed against
+ BackgroundMarker, off the screen with it. */
+extern Int ControlBar_slideToUndo( Int slideAppliedToWindow, Int panelSlideOffsetNow );
+
+TEST(the_bar_only_lifts_a_window_the_slide_actually_pushed_down)
+{
+ // a window the slide moved comes back by exactly what it was moved by
+ CHECK_EQ( ControlBar_slideToUndo( 48, 48 ), 48 );
+
+ //
+ // and one it skipped is left alone, however far its panel says it went. A plate marker and
+ // anything in a panel that was minimised immediately are both in this case.
+ //
+ CHECK_EQ( ControlBar_slideToUndo( 0, 48 ), 0 );
+ CHECK_EQ( ControlBar_slideToUndo( 0, 121 ), 0 );
+
+ // a window that went down before the panel's slide changed underneath it still comes back whole
+ CHECK_EQ( ControlBar_slideToUndo( 30, 0 ), 30 );
+ CHECK_EQ( ControlBar_slideToUndo( 30, 90 ), 30 );
+
+ // the round trip is a round trip: pushed down by n, lifted by n, net zero
+ static const Int pushes[] = { 0, 1, 17, 48, 121 };
+ for( Int i = 0; i < 5; i++ )
+ {
+ const Int y = 400;
+ const Int down = y + pushes[ i ];
+ CHECK_EQ( down - ControlBar_slideToUndo( pushes[ i ], 121 ), y );
+ }
+}
+
+/* ControlBar.cpp: a resolution change throws every window away and builds it again, but the bar
+ itself has to survive - a production queue, a hunt update and the academy all hold a
+ const CommandButton * that would be left pointing at a freed one. So the window half of init
+ is its own pair of functions, and the teardown half runs twice on the way out: once from the
+ rebuild, once from the destructor. */
+TEST(the_bars_windows_can_be_torn_down_twice_without_taking_the_bar_with_them)
+{
+ ControlBar bar;
+
+ bar.shutdownWindows();
+ CHECK( !bar.getShowBuildTooltipLayout() );
+
+ // again, on a bar that is already holding nothing - which is what the destructor does
+ bar.shutdownWindows();
+ CHECK( !bar.getShowBuildTooltipLayout() );
+
+ // the command buttons are not window state and are not touched by any of it
+ CHECK( bar.getCommandButtons() == NULL );
+ CHECK( bar.findCommandButton( AsciiString( "NoSuchCommandButton" ) ) == NULL );
+}
+
+/* ControlBarScheme.cpp: the scheme places the money readout, the two general's tabs and the toolbar
+ column by reading their parent's screen position and subtracting it, and layoutPanels then runs
+ over the answer. Asking for the panels back is not the same as having them back - the slide is
+ wall-clocked over a fifth of a second - so a scheme rebuilt while the bar was on its way down
+ read a parent that was still travelling, and every child it placed came out that far too high.
+ layoutPanels lifted the parent back afterwards and dragged them up again, placeInPanel recorded
+ the lifted position as the authored one, and it stuck. Measured in a match: 524 with the panels
+ sent home first, 294 without. clearPanelSlide is the "first". */
+TEST(sending_the_panels_home_is_not_the_same_as_them_being_home)
+{
+ ControlBar bar;
+ const Int left = ControlBar::CB_PANEL_LEFT;
+ const Int right = ControlBar::CB_PANEL_RIGHT;
+ const Int count = ControlBar::CB_PANEL_COUNT;
+
+ // away, and all the way away this instant
+ bar.showPanel( left, FALSE, TRUE );
+ CHECK_NEAR( bar.getPanelSlideFraction( left ), 1.0f, 0.0001f );
+ CHECK( bar.isPanelHidden( left ) );
+
+ //
+ // what switchControlBarStage( CONTROL_BAR_STAGE_DEFAULT ) does: it asks. The panel is still down
+ // there, and anything reading a window's position on this frame reads it down there.
+ //
+ bar.showPanel( left, TRUE );
+ CHECK_NEAR( bar.getPanelSlideFraction( left ), 1.0f, 0.0001f );
+
+ // clearPanelSlide does not ask, it declares
+ bar.clearPanelSlide();
+ CHECK_NEAR( bar.getPanelSlideFraction( left ), 0.0f, 0.0001f );
+ CHECK( !bar.isPanelHidden( left ) );
+
+ // and it speaks for all three, not just the one that was asked about
+ Int p;
+ for( p = 0; p < count; p++ )
+ bar.showPanel( p, FALSE, TRUE );
+ bar.clearPanelSlide();
+ for( p = 0; p < count; p++ )
+ {
+ CHECK_NEAR( bar.getPanelSlideFraction( p ), 0.0f, 0.0001f );
+ CHECK( !bar.isPanelHidden( p ) );
+ }
+
+ // a panel that never left is left alone
+ bar.clearPanelSlide();
+ CHECK_NEAR( bar.getPanelSlideFraction( right ), 0.0f, 0.0001f );
+}
+
+/* Mouse.cpp: the tooltip box was placed by two flips and nothing else, under EA's own note that
+ the tips still had to be kept somewhere readable. A flip is the right answer at the right and
+ bottom edges and no answer at the left and top, and both are reachable: setCursorTooltip will
+ wrap a tip to the full width of the display when a caller asks for it, and a caller that asks
+ for less than ten pixels gets a 120-wide column that runs long text hundreds of pixels down. */
+TEST(a_tooltip_is_put_back_on_the_screen_after_it_is_flipped)
+{
+ const Int screenW = 1024, screenH = 768;
+ Int x, y;
+
+ // the ordinary case: to the right of the pointer, level with it, untouched
+ Mouse::placeTooltip( 400, 300, 286, 102, 0, 0, screenW, screenH, &x, &y );
+ CHECK_EQ( x, 420 );
+ CHECK_EQ( y, 300 );
+
+ // right edge: the flip is what puts it on the roomier side, and it stays
+ Mouse::placeTooltip( 1000, 300, 286, 20, 0, 0, screenW, screenH, &x, &y );
+ CHECK_EQ( x, 714 );
+ CHECK( x >= 0 && x + 286 <= screenW );
+
+ // bottom edge, same
+ Mouse::placeTooltip( 400, 760, 286, 40, 0, 0, screenW, screenH, &x, &y );
+ CHECK_EQ( y, 720 );
+ CHECK( y >= 0 && y + 40 <= screenH );
+
+ //
+ // A screen-wide tip with the pointer past the middle: too wide to fit on the right, and the
+ // flip alone lands it at -60. This is the one a player sees with the left half of the text
+ // missing.
+ //
+ Mouse::placeTooltip( 640, 300, 1000, 30, 0, 0, screenW, screenH, &x, &y );
+ CHECK_EQ( x, 0 );
+
+ // a narrow column of long text with the pointer high up: the flip alone puts it above the top
+ Mouse::placeTooltip( 400, 300, 120, 500, 0, 0, screenW, screenH, &x, &y );
+ CHECK_EQ( y, 0 );
+
+ //
+ // Nothing lands outside the screen, whatever is asked for. A box larger than the screen is
+ // pinned to the top left corner, which loses its far edge and keeps its first words.
+ //
+ static const Int sizes[] = { 20, 120, 286, 700, 1000, 1200 };
+ Int i, j, px, py;
+ for( i = 0; i < 6; i++ )
+ for( j = 0; j < 6; j++ )
+ for( px = 0; px <= screenW; px += 128 )
+ for( py = 0; py <= screenH; py += 128 )
+ {
+ Mouse::placeTooltip( px, py, sizes[ i ], sizes[ j ], 0, 0, screenW, screenH, &x, &y );
+ CHECK( x >= 0 );
+ CHECK( y >= 0 );
+ if( sizes[ i ] + 4 <= screenW )
+ CHECK( x + sizes[ i ] + 4 <= screenW );
+ if( sizes[ j ] + 4 <= screenH )
+ CHECK( y + sizes[ j ] + 4 <= screenH );
+ }
+
+ // the limits are read, not assumed: a windowed device with an origin away from zero holds too
+ Mouse::placeTooltip( 200, 200, 400, 300, 100, 150, 500, 450, &x, &y );
+ CHECK( x >= 100 );
+ CHECK( y >= 150 );
+}
diff --git a/lan-play.ps1 b/lan-play.ps1
new file mode 100644
index 000000000..6978db863
--- /dev/null
+++ b/lan-play.ps1
@@ -0,0 +1,135 @@
+<#
+.SYNOPSIS
+ Starts several copies of the game on this machine, each in the LAN lobby, ready to play each
+ other.
+
+.DESCRIPTION
+ The game refuses a second copy of itself unless -multiInstance is on the command line, and even
+ with it two copies could not reach the LAN lobby together: the lobby binds one UDP port with no
+ SO_REUSEADDR, so the second copy came up with a socket error and an empty game list. Three
+ switches fix that, and this script is the four of them tied together.
+
+ Every copy gets its own address out of 127.0.0.0/8 (-lanip). Windows routes that whole range to
+ loopback and delivers a broadcast sent from one of those addresses to the others, which is what
+ carries the lobby's game announcements. Every copy gets its own name (-lanname), because both
+ read the same LAN preferences file and a host denies a join whose name it already holds.
+ -lanlobby opens the LAN screen at startup instead of the main menu, which is the four clicks
+ every copy would otherwise start with.
+
+ What to do once the windows are up: in the first, click Host, pick a map, wait for the others to
+ appear in the slots, then Start. In the others, the hosted game shows up in the game list; click
+ it to join. Faction and colour are per slot, the way they always are.
+
+.EXAMPLE
+ .\lan-play.ps1
+ Two copies, "Player 1" at 127.0.0.1 and "Player 2" at 127.0.0.2.
+
+.EXAMPLE
+ .\lan-play.ps1 -Copies 4 -Windowed:$false
+ Four copies, fullscreen. Alt-tab between them; note that alt-tabbing out of a fullscreen game
+ loses the D3D device, which the engine recovers from but which is a poor way to run four.
+#>
+param(
+ # how many copies to start
+ [int] $Copies = 2,
+ # the exe to run, relative to Run\
+ [string] $Exe = "generals.exe",
+ # names for the copies; the n-th copy takes the n-th name, and anything past the end of the
+ # list gets "Player <n>"
+ [string[]] $Names = @(),
+ # windowed is the only way to see two of them at once
+ [bool] $Windowed = $true,
+ # window size for each copy; two 800x600 windows sit side by side on a 1080p desktop
+ [int] $Width = 800,
+ [int] $Height = 600,
+ # lay the windows out left to right instead of leaving them stacked on top of each other
+ [bool] $Tile = $true,
+ # anything else to hand every copy, e.g. -ExtraArgs '-noaudio'
+ [string[]] $ExtraArgs = @()
+)
+
+$ErrorActionPreference = "Stop"
+
+# in the source tree the exe is in GeneralsMD\Run; in an installed game this script sits next to it
+$runDir = Join-Path $PSScriptRoot "GeneralsMD\Run"
+if (-not (Test-Path (Join-Path $runDir $Exe)))
+{
+ $runDir = $PSScriptRoot
+}
+$exePath = Join-Path $runDir $Exe
+if (-not (Test-Path $exePath))
+{
+ throw "no $Exe in $runDir - build it first (build.bat Release), or run this from the game folder"
+}
+
+if ($Copies -lt 2 -or $Copies -gt 8)
+{
+ throw "-Copies is 2..8; one copy does not need any of this"
+}
+
+$started = @()
+for ($i = 1; $i -le $Copies; $i++)
+{
+ $name = if ($i -le $Names.Count) { $Names[$i - 1] } else { "Player $i" }
+ $ip = "127.0.0.$i"
+
+ # -quickstart drops the logos and the intro movie, which is two minutes of nothing when the point
+ # of starting the game is that another copy of it is waiting in the lobby
+ $argList = @("-multiInstance", "-quickstart", "-lanlobby", "-lanip", $ip, "-lanname", "`"$name`"")
+ if ($Windowed) { $argList += @("-win", "-xres", $Width, "-yres", $Height) }
+ $argList += $ExtraArgs
+
+ # each copy writes its own log, or they overwrite each other's answers
+ $logPrefix = "lan{0}_" -f $i
+ $argList += @("-logPrefix", $logPrefix)
+
+ $p = Start-Process -FilePath $exePath -WorkingDirectory $runDir -ArgumentList $argList -PassThru
+ $started += [pscustomobject]@{ Copy = $i; Name = $name; IP = $ip; PID = $p.Id; Log = $logPrefix + "DebugLogFile.txt" }
+}
+
+if ($Tile -and $Windowed)
+{
+ # The copies are born at the splash's own size and centred, so without this they sit exactly on
+ # top of each other and only the last one started is visible. Move them once each window exists;
+ # the game itself never moves the window after the render device has resized it.
+ Add-Type @"
+using System;
+using System.Runtime.InteropServices;
+public class LanPlayWin {
+ [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int cx, int cy, uint flags);
+}
+"@
+ Add-Type -AssemblyName System.Windows.Forms
+ $desk = [System.Windows.Forms.Screen]::PrimaryScreen.WorkingArea
+
+ $deadline = (Get-Date).AddSeconds(60)
+ $x = 0
+ $y = 0
+ foreach ($s in $started)
+ {
+ $proc = Get-Process -Id $s.PID
+ while ($proc.MainWindowHandle -eq 0 -and (Get-Date) -lt $deadline)
+ {
+ Start-Sleep -Milliseconds 500
+ $proc.Refresh()
+ }
+ if ($proc.MainWindowHandle -ne 0)
+ {
+ # 0x0001 is SWP_NOSIZE: the size is the render device's business, the position is ours
+ [LanPlayWin]::SetWindowPos($proc.MainWindowHandle, [IntPtr]::Zero, $x, $y, 0, 0, 0x0001) | Out-Null
+ }
+ $x += $Width + 8
+ if ($x + $Width -gt $desk.Width)
+ {
+ $x = 0
+ $y += $Height + 40
+ }
+ }
+}
+
+$started | Format-Table -AutoSize
+
+Write-Host ""
+Write-Host "Host in one window, join from the others. Logs are in $runDir."
+Write-Host "If a game list stays empty, grep its log for 'Transport::init' - a bind failure there"
+Write-Host "means two copies took the same -lanip."