Example #1
0
        public void LoadGeneralsMaps()
        {
            var rootFolder   = InstalledFilesTestData.GetInstallationDirectory(SageGame.CncGenerals);
            var installation = new GameInstallation(new GeneralsDefinition(), rootFolder);
            var fileSystem   = installation.CreateFileSystem();

            var maps = fileSystem.GetFiles("maps").Where(x => x.FilePath.EndsWith(".map")).ToList();

            Platform.Start();

            using (var window = new GameWindow("OpenSAGE test runner", 100, 100, 800, 600, GraphicsBackend.Direct3D11))
            {
                using (var game = GameFactory.CreateGame(installation, fileSystem, GamePanel.FromGameWindow(window)))
                {
                    foreach (var map in maps)
                    {
                        _testOutputHelper.WriteLine($"Loading {map.FilePath}...");

                        var scene = game.ContentManager.Load <Scene3D>(map.FilePath);
                        Assert.NotNull(scene);

                        game.ContentManager.Unload();
                    }
                }
            }

            Platform.Stop();
        }
Example #2
0
        private void ChangeInstallation(GameInstallation installation)
        {
            _installation = installation;

            if (_fileSystem != null)
            {
                _fileSystem.Dispose();
                _fileSystem = null;
            }

            if (_game != null)
            {
                _game.Dispose();
                _game = null;
            }

            _fileSystem = installation.CreateFileSystem();

            _game = new Game(
                HostPlatform.GraphicsDevice,
                HostPlatform.GraphicsDevice2D,
                _fileSystem,
                installation.Game);

            InstallationChanged?.Invoke(this, new InstallationChangedEventArgs(installation, _fileSystem));
        }
Example #3
0
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            DirectoryInfo gameDirectory = new DirectoryInfo(value.ToString());

            if (gameDirectory.Exists)
            {
                FileInfo[] subFiles = gameDirectory.GetFiles();
                foreach (FileInfo info in subFiles)
                {
                    if (info.Extension.ToLower() == ".exe" && info.Name.Contains("RCT3"))
                    {
                        GameInstallation installation = GlobalStateHelper.RunningGameInfo;
                        if (installation == null || installation.GameFileFullName != info.FullName)
                        {
                            using FileStream peFileStream = new FileStream(info.FullName, FileMode.Open);
                            PeFile peFile = new PeFile(peFileStream);
                            if (!GameVersionHelper.ValidTimeDateStamps.Keys.Contains(peFile.ImageNtHeaders.FileHeader.TimeDateStamp))
                            {
                                continue;
                            }
                        }
                        return(ValidationResult.ValidResult);
                    }
                }
            }
            return(new ValidationResult(false, App.Current.Resources["ValidationRule_GameFileError"]));
        }
Example #4
0
        public void LoadGeneralsMaps()
        {
            var rootFolder   = InstalledFilesTestData.GetInstallationDirectory(SageGame.CncGenerals);
            var installation = new GameInstallation(new GeneralsDefinition(), rootFolder);

            Platform.Start();

            using (var game = new Game(installation, GraphicsBackend.Direct3D11))
            {
                var maps = game.ContentManager.FileSystem.GetFiles("maps").Where(x => x.FilePath.EndsWith(".map")).ToList();

                foreach (var map in maps)
                {
                    _testOutputHelper.WriteLine($"Loading {map.FilePath}...");

                    game.AssetStore.PushScope();

                    throw new System.NotImplementedException();

                    // TODO: Need to update to use new way of starting game.
                    //using (var scene = game.LoadMap(map.FilePath))
                    //{
                    //    Assert.NotNull(scene);
                    //}

                    game.AssetStore.PopScope();
                }
            }

            Platform.Stop();
        }
Example #5
0
        private void ChangeInstallation(GameInstallation installation)
        {
            _installation = installation;

            if (_fileSystem != null)
            {
                _fileSystem.Dispose();
                _fileSystem = null;
            }

            var launcherImagePath = installation.Game.LauncherImagePath;

            if (launcherImagePath != null)
            {
                var fullImagePath = Path.Combine(installation.Path, launcherImagePath);
                _installationImageView.Image = new Bitmap(fullImagePath);
            }
            else
            {
                _installationImageView.Image = null;
            }

            _fileSystem = installation.CreateFileSystem();

            InstallationChanged?.Invoke(this, new InstallationChangedEventArgs(installation, _fileSystem));
        }
Example #6
0
        public MainForm(GameWindow gameWindow, ImGuiRenderer imGuiRenderer)
        {
            _gameWindow    = gameWindow;
            _imGuiRenderer = imGuiRenderer;

            _installations = GameInstallation.FindAll(GameDefinition.All).ToList();
            ChangeInstallation(_installations.FirstOrDefault());
        }
Example #7
0
        public MainForm(GameWindow gameWindow, ImGuiRenderer imGuiRenderer)
        {
            _gameWindow     = gameWindow;
            _isVSyncEnabled = _gameWindow.GraphicsDevice.SyncToVerticalBlank;
            _imGuiRenderer  = imGuiRenderer;

            _installations = GameInstallation.FindAll(GameDefinition.All).ToList();
            ChangeInstallation(_installations.FirstOrDefault());
        }
Example #8
0
        public GameFixture()
        {
            var rootFolder   = InstalledFilesTestData.GetInstallationDirectory(SageGame.CncGenerals);
            var installation = new GameInstallation(new GeneralsDefinition(), rootFolder);

            Platform.Start();

            Game = new Game(installation);
        }
Example #9
0
        public static Game CreateGame(
            GameInstallation installation,
            FileSystem fileSystem,
            Func <GameWindow> createWindow)
        {
            var definition = installation.Game;

            return(new Game(definition, fileSystem, createWindow));
        }
Example #10
0
        public SaveFileTests()
        {
            var rootFolder   = InstalledFilesTestData.GetInstallationDirectory(SageGame.CncGenerals);
            var installation = new GameInstallation(new GeneralsDefinition(), rootFolder);

            Platform.Start();

            _game = new Game(installation, GraphicsBackend.Direct3D11);
        }
Example #11
0
        private void ChangeInstallation(GameInstallation installation)
        {
            _selectedInstallation = installation;

            _imGuiRenderer.ClearCachedImageResources();

            RemoveAndDispose(ref _contentView);
            _files = null;
            RemoveAndDispose(ref _game);
            RemoveAndDispose(ref _gamePanel);
            RemoveAndDispose(ref _fileSystem);
            RemoveAndDispose(ref _launcherImage);

            if (installation == null)
            {
                _files = new List <FileSystemEntry>();
                return;
            }

            _fileSystem = AddDisposable(installation.CreateFileSystem());

            var launcherImagePath = installation.Game.LauncherImagePath;

            if (launcherImagePath != null)
            {
                var prefixLang = installation.Game.LauncherImagePrefixLang;
                if (prefixLang)
                {
                    var lang = LanguageUtility.ReadCurrentLanguage(installation.Game, _fileSystem.RootDirectory);
                    launcherImagePath = lang + launcherImagePath;
                }

                var launcherImageEntry = _fileSystem.GetFile(launcherImagePath);

                if (launcherImageEntry != null)
                {
                    _launcherImage = AddDisposable(new ImageSharpTexture(launcherImageEntry.Open()).CreateDeviceTexture(
                                                       _gameWindow.GraphicsDevice, _gameWindow.GraphicsDevice.ResourceFactory));
                }
            }

            _files = _fileSystem.Files.OrderBy(x => x.FilePath).ToList();

            _currentFile = -1;

            _gamePanel = AddDisposable(new ImGuiGamePanel(_gameWindow));
            _gamePanel.EnsureFrame(new Mathematics.Rectangle(0, 0, 100, 100));

            _game = AddDisposable(GameFactory.CreateGame(
                                      installation,
                                      _fileSystem,
                                      _gamePanel));

            //InstallationChanged?.Invoke(this, new InstallationChangedEventArgs(installation, _fileSystem));
        }
        private void Reset_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult rsltMessageBox = MessageBox.Show(ResetMessage, "Reset", MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (rsltMessageBox == MessageBoxResult.Yes)
            {
                String configFolder = System.IO.Path.Combine(GameInstallation.GetRootPath(), "UDKGame\\Config");
                System.IO.Directory.Delete(configFolder, true);
                this.ApplyResetOrVerify(ApplyUpdateWindow.UpdateWindowType.Reset);
            }
        }
Example #13
0
        public static Game CreateGame(
            GameInstallation installation,
            FileSystem fileSystem,
            GamePanel panel)
        {
            var definition = installation.Game;

            return(new Game(
                       definition,
                       fileSystem,
                       panel));
        }
Example #14
0
        private void ChangeInstallation(GameInstallation installation)
        {
            _selectedInstallation = installation;

            _imGuiRenderer.ClearCachedImageResources();

            RemoveAndDispose(ref _contentView);
            _files = null;
            RemoveAndDispose(ref _game);
            RemoveAndDispose(ref _gamePanel);
            RemoveAndDispose(ref _fileSystem);
            RemoveAndDispose(ref _launcherImage);

            if (installation == null)
            {
                _files = new List <FileSystemEntry>();
                return;
            }

            var launcherImagePath = installation.Game.LauncherImagePath;

            if (launcherImagePath != null)
            {
                var fullImagePath = Path.Combine(installation.Path, launcherImagePath);
                if (File.Exists(fullImagePath))
                {
                    _launcherImage = AddDisposable(new ImageSharpTexture(fullImagePath).CreateDeviceTexture(
                                                       _gameWindow.GraphicsDevice, _gameWindow.GraphicsDevice.ResourceFactory));
                }
            }

            _fileSystem = AddDisposable(installation.CreateFileSystem());

            _files = _fileSystem.Files.OrderBy(x => x.FilePath).ToList();

            _currentFile = -1;

            _gamePanel = AddDisposable(new ImGuiGamePanel(_gameWindow));
            _gamePanel.EnsureFrame(new Mathematics.Rectangle(0, 0, 100, 100));

            _game = AddDisposable(GameFactory.CreateGame(
                                      installation,
                                      _fileSystem,
                                      _gamePanel));

            //InstallationChanged?.Invoke(this, new InstallationChangedEventArgs(installation, _fileSystem));
        }
        private void ApplyResetOrVerify(ApplyUpdateWindow.UpdateWindowType type)
        {
            var targetDir      = GameInstallation.GetRootPath();
            var applicationDir = System.IO.Path.Combine(GameInstallation.GetRootPath(), "patch");
            var patchUrls      = VersionCheck.GamePatchUrls;
            var patchVersion   = VersionCheck.GetLatestGameVersionName();

            var  progress = new Progress <DirectoryPatcherProgressReport>();
            var  cancellationTokenSource = new System.Threading.CancellationTokenSource();
            Task task = new RXPatcher().ApplyPatchFromWeb(patchUrls, targetDir, applicationDir, progress, cancellationTokenSource.Token);

            var window = new ApplyUpdateWindow(task, progress, patchVersion, cancellationTokenSource, type);

            window.Owner = this;
            window.ShowDialog();

            VersionCheck.UpdateGameVersion();
        }
Example #16
0
        public static Game CreateGame(
            IGameDefinition definition,
            GameWindow window)
        {
            var installation = GameInstallation
                               .FindAll(new[] { definition })
                               .FirstOrDefault();

            if (installation == null)
            {
                throw new Exception($"No installations for {definition.Game} could be found.");
            }

            return(CreateGame(
                       installation,
                       installation.CreateFileSystem(),
                       window));
        }
Example #17
0
        public void LoadGeneralsMaps()
        {
            var rootFolder   = InstalledFilesTestData.GetInstallationDirectory(SageGame.CncGenerals);
            var installation = new GameInstallation(new GeneralsDefinition(), rootFolder);

            Platform.Start();

            using (var game = new Game(installation, GraphicsBackend.Direct3D11))
            {
                var maps = game.ContentManager.FileSystem.GetFiles("maps").Where(x => x.FilePath.EndsWith(".map")).ToList();

                foreach (var map in maps)
                {
                    _testOutputHelper.WriteLine($"Loading {map.FilePath}...");

                    var scene = game.ContentManager.Load <Scene3D>(map.FilePath);
                    Assert.NotNull(scene);

                    game.ContentManager.Unload();
                }
            }

            Platform.Stop();
        }
Example #18
0
        public static void Run(Options opts)
        {
            var             definition       = GameDefinition.FromGame(opts.Game);
            GraphicsBackend?preferredBackend = null;

            var installation = GameInstallation
                               .FindAll(new[] { definition })
                               .FirstOrDefault();

            if (installation == null)
            {
                Console.WriteLine($"OpenSAGE was unable to find any installations of {definition.DisplayName}.\n");

                Console.WriteLine("You can manually specify the installation path by setting the following environment variable:");
                Console.WriteLine($"\t{definition.Identifier.ToUpper()}_PATH=<installation path>\n");

                Console.WriteLine("OpenSAGE doesn't yet detect every released version of every game. Please report undetected versions to our GitHub page:");
                Console.WriteLine("\thttps://github.com/OpenSAGE/OpenSAGE/issues");

                Console.WriteLine("\n\n Press any key to exit.");

                Console.ReadLine();

                Environment.Exit(1);
            }

            if (opts.Renderer != Renderer.Default)
            {
                preferredBackend = (GraphicsBackend)opts.Renderer;
            }

            Platform.Start();

            // TODO: Read game version from assembly metadata or .git folder
            // TODO: Set window icon.
            using (var window = new GameWindow("OpenSAGE (master)", 100, 100, 1024, 768, preferredBackend))
                using (var gamePanel = GamePanel.FromGameWindow(window))
                    using (var game = GameFactory.CreateGame(installation, installation.CreateFileSystem(), gamePanel))
                    {
                        window.GraphicsDevice.SyncToVerticalBlank = !opts.DisableVsync;

                        game.Configuration.LoadShellMap = !opts.NoShellmap;

                        if (opts.Map == null)
                        {
                            game.ShowMainMenu();
                        }
                        else
                        {
                            game.StartGame(opts.Map, new EchoConnection(), new[] { "America", "GLA" }, 0);
                        }

                        while (game.IsRunning)
                        {
                            if (!window.PumpEvents())
                            {
                                break;
                            }

                            game.Tick();
                        }
                    }

            Platform.Stop();
        }
Example #19
0
        public static void Run(Options opts)
        {
            logger.Info("Starting...");

            var DetectedGame = opts.Game;
            var GameFolder   = opts.GamePath;
            var UseLocators  = true;

            if (GameFolder == null)
            {
                GameFolder = Environment.CurrentDirectory;
            }

            foreach (var gameDef in GameDefinition.All)
            {
                if (gameDef.Probe(GameFolder))
                {
                    DetectedGame = gameDef.Game;
                    UseLocators  = false;
                }
            }

            var definition = GameDefinition.FromGame(DetectedGame);
            GameInstallation installation;

            if (UseLocators)
            {
                installation = GameInstallation
                               .FindAll(new[] { definition })
                               .FirstOrDefault();
            }
            else
            {
                installation = new GameInstallation(definition, GameFolder);
            }

            if (installation == null)
            {
                Console.WriteLine($"OpenSAGE was unable to find any installations of {definition.DisplayName}.\n");

                Console.WriteLine("You can manually specify the installation path by setting the following environment variable:");
                Console.WriteLine($"\t{definition.Identifier.ToUpper()}_PATH=<installation path>\n");

                Console.WriteLine("OpenSAGE doesn't yet detect every released version of every game. Please report undetected versions to our GitHub page:");
                Console.WriteLine("\thttps://github.com/OpenSAGE/OpenSAGE/issues");

                Console.WriteLine("\n\n Press any key to exit.");

                Console.ReadLine();

                Environment.Exit(1);
            }

            logger.Debug($"Have installation of {definition.DisplayName}");

            Platform.Start();

            var traceEnabled = !string.IsNullOrEmpty(opts.TraceFile);

            if (traceEnabled)
            {
                GameTrace.Start(opts.TraceFile);
            }

            // TODO: Read game version from assembly metadata or .git folder
            // TODO: Set window icon.
            var config = new Configuration()
            {
                UseFullscreen = opts.Fullscreen,
                UseRenderDoc  = opts.RenderDoc,
                LoadShellMap  = !opts.NoShellmap,
            };

            if (opts.LanIPAddress != "")
            {
                try {
                    config.LanIpAddress = IPAddress.Parse(opts.LanIPAddress);
                }catch (FormatException) {
                    logger.Error($"Could not parse specified LAN IP address: {opts.LanIPAddress}");
                }
            }

            logger.Debug($"Have configuration");

            using (var game = new Game(installation, opts.Renderer, config))
            {
                game.GraphicsDevice.SyncToVerticalBlank = !opts.DisableVsync;

                game.DeveloperModeEnabled = opts.DeveloperMode;

                if (opts.DeveloperMode)
                {
                    game.Window.Maximized = true;
                }

                if (opts.ReplayFile != null)
                {
                    var replayFile = game.ContentManager.UserDataFileSystem?.GetFile(Path.Combine("Replays", opts.ReplayFile));
                    if (replayFile == null)
                    {
                        logger.Debug("Could not find entry for Replay " + opts.ReplayFile);
                        game.ShowMainMenu();
                    }

                    game.LoadReplayFile(replayFile);
                }
                else if (opts.Map != null)
                {
                    game.Restart = StartMap;
                    StartMap();

                    void StartMap()
                    {
                        var mapCache = game.AssetStore.MapCaches.GetByName(opts.Map);

                        if (mapCache == null)
                        {
                            logger.Debug("Could not find MapCache entry for map " + opts.Map);
                            game.ShowMainMenu();
                        }
                        else if (mapCache.IsMultiplayer)
                        {
                            var pSettings = new PlayerSetting?[]
                            {
                                new PlayerSetting(null, game.AssetStore.PlayerTemplates.GetByName("FactionAmerica"), new ColorRgb(255, 0, 0), PlayerOwner.Player),
                                new PlayerSetting(null, game.AssetStore.PlayerTemplates.GetByName("FactionGLA"), new ColorRgb(0, 255, 0), PlayerOwner.EasyAi),
                            };

                            logger.Debug("Starting multiplayer game");

                            game.StartMultiPlayerGame(opts.Map,
                                                      new EchoConnection(),
                                                      pSettings,
                                                      0);
                        }
                        else
                        {
                            logger.Debug("Starting singleplayer game");

                            game.StartSinglePlayerGame(opts.Map);
                        }
                    }
                }
                else
                {
                    logger.Debug("Showing main menu");
                    game.ShowMainMenu();
                }

                logger.Debug("Starting game");

                game.Run();
            }

            if (traceEnabled)
            {
                GameTrace.Stop();
            }

            Platform.Stop();
        }
Example #20
0
        public static void Run(Options opts)
        {
            logger.Info("Starting...");

            var definition = GameDefinition.FromGame(opts.Game);

            var installation = GameInstallation
                               .FindAll(new[] { definition })
                               .FirstOrDefault();

            if (installation == null)
            {
                Console.WriteLine($"OpenSAGE was unable to find any installations of {definition.DisplayName}.\n");

                Console.WriteLine("You can manually specify the installation path by setting the following environment variable:");
                Console.WriteLine($"\t{definition.Identifier.ToUpper()}_PATH=<installation path>\n");

                Console.WriteLine("OpenSAGE doesn't yet detect every released version of every game. Please report undetected versions to our GitHub page:");
                Console.WriteLine("\thttps://github.com/OpenSAGE/OpenSAGE/issues");

                Console.WriteLine("\n\n Press any key to exit.");

                Console.ReadLine();

                Environment.Exit(1);
            }

            logger.Debug($"Have installation of {definition.DisplayName}");

            Platform.Start();

            var traceEnabled = !string.IsNullOrEmpty(opts.TraceFile);

            if (traceEnabled)
            {
                GameTrace.Start(opts.TraceFile);
            }

            // TODO: Read game version from assembly metadata or .git folder
            // TODO: Set window icon.
            var config = new Configuration()
            {
                UseFullscreen = opts.Fullscreen,
                UseRenderDoc  = opts.RenderDoc,
                LoadShellMap  = !opts.NoShellmap,
            };

            logger.Debug($"Have configuration");

            using (var game = new Game(installation, opts.Renderer, config))
            {
                game.GraphicsDevice.SyncToVerticalBlank = !opts.DisableVsync;

                game.DeveloperModeEnabled = opts.DeveloperMode;

                if (opts.ReplayFile != null)
                {
                    using (var fileSystem = new FileSystem(Path.Combine(game.UserDataFolder, "Replays")))
                    {
                        game.LoadReplayFile(fileSystem.GetFile(opts.ReplayFile));
                    }
                }
                else if (opts.Map != null)
                {
                    var pSettings = new PlayerSetting?[]
                    {
                        new PlayerSetting(null, "America", new ColorRgb(255, 0, 0)),
                        new PlayerSetting(null, "GLA", new ColorRgb(255, 255, 255)),
                    };

                    logger.Debug("Starting multiplayer game");
                    game.StartMultiPlayerGame(opts.Map,
                                              new EchoConnection(),
                                              pSettings,
                                              0);
                }
                else
                {
                    logger.Debug("Showing main menu");
                    game.ShowMainMenu();
                }

                logger.Debug("Starting game");

                game.Run();
            }

            if (traceEnabled)
            {
                GameTrace.Stop();
            }

            Platform.Stop();
        }
Example #21
0
        public static void Main(string[] args)
        {
            var             noShellMap       = false;
            var             definition       = GameDefinition.FromGame(SageGame.CncGenerals);
            string          mapName          = null;
            GraphicsBackend?preferredBackend = null;

            ArgumentSyntax.Parse(args, syntax =>
            {
                string preferredBackendString = null;
                syntax.DefineOption("renderer", ref preferredBackendString, false, $"Choose which renderer backend should be used. Valid options: {string.Join(",", Enum.GetNames(typeof(GraphicsBackend)))}");
                if (preferredBackendString != null)
                {
                    if (Enum.TryParse <GraphicsBackend>(preferredBackendString, out var preferredBackendTemp))
                    {
                        preferredBackend = preferredBackendTemp;
                    }
                    else
                    {
                        syntax.ReportError($"Unknown renderer backend: {preferredBackendString}");
                    }
                }

                syntax.DefineOption("noshellmap", ref noShellMap, false, "Disables loading the shell map, speeding up startup time.");

                string gameName    = null;
                var availableGames = string.Join(", ", GameDefinition.All.Select(def => def.Game.ToString()));

                syntax.DefineOption("game", ref gameName, false, $"Chooses which game to start. Valid options: {availableGames}");

                // If a game has been specified, make sure it's valid.
                if (gameName != null && !GameDefinition.TryGetByName(gameName, out definition))
                {
                    syntax.ReportError($"Unknown game: {gameName}");
                }

                syntax.DefineOption("map", ref mapName, false,
                                    "Immediately starts a new skirmish with default settings in the specified map. The map file must be specified with the full path.");
            });

            var installation = GameInstallation
                               .FindAll(new[] { definition })
                               .FirstOrDefault();

            if (installation == null)
            {
                Console.WriteLine($"OpenSAGE was unable to find any installations of {definition.DisplayName}.\n");

                Console.WriteLine("You can manually specify the installation path by setting the following environment variable:");
                Console.WriteLine($"\t{definition.Identifier.ToUpper()}_PATH=<installation path>\n");

                Console.WriteLine("OpenSAGE doesn't yet detect every released version of every game. Please report undetected versions to our GitHub page:");
                Console.WriteLine("\thttps://github.com/OpenSAGE/OpenSAGE/issues");

                Environment.Exit(1);
            }

            Platform.Start();

            // TODO: Read game version from assembly metadata or .git folder
            // TODO: Set window icon.
            using (var window = new GameWindow("OpenSAGE (master)", 100, 100, 1024, 768, preferredBackend))
                using (var gamePanel = GamePanel.FromGameWindow(window))
                    using (var game = GameFactory.CreateGame(installation, installation.CreateFileSystem(), gamePanel))
                    {
                        game.Configuration.LoadShellMap = !noShellMap;

                        if (mapName == null)
                        {
                            game.ShowMainMenu();
                        }
                        else
                        {
                            game.StartGame(mapName, new EchoConnection(), new[] { "America", "GLA" }, 0);
                        }

                        while (game.IsRunning)
                        {
                            if (!window.PumpEvents())
                            {
                                break;
                            }

                            game.Tick();
                        }
                    }

            Platform.Stop();
        }
 public InstallationChangedEventArgs(GameInstallation installation, FileSystem fileSystem)
 {
     Installation = installation;
     FileSystem   = fileSystem;
 }
Example #23
0
        static void GameWindowAdapter(string rootPath)
        {
            var installation = new GameInstallation(new AptEditorDefinition(), rootPath);

            using var game = new Game(installation, null, new Configuration { LoadShellMap = false });
            // should be the ImGui context created by DeveloperModeView
            var initialContext = ImGui.GetCurrentContext();
            var device         = game.GraphicsDevice;
            var window         = game.Window;

            using var imGuiRenderer = new ImGuiRenderer(device,
                                                        game.Panel.OutputDescription,
                                                        window.ClientBounds.Width,
                                                        window.ClientBounds.Height);
            var font = imGuiRenderer.LoadSystemFont("consola.ttf");

            using var commandList = device.ResourceFactory.CreateCommandList();
            var ourContext = ImGui.GetCurrentContext();

            // reset ImGui Context to initial one
            ImGui.SetCurrentContext(initialContext);

            var mainForm = new MainForm(game);

            void OnClientSizeChanged(object?sender, EventArgs args)
            {
                imGuiRenderer.WindowResized(window.ClientBounds.Width, window.ClientBounds.Height);
            }

            void OnRendering2D(object?sender, EventArgs e)
            {
                var previousContext = ImGui.GetCurrentContext();

                ImGui.SetCurrentContext(ourContext);
                try
                {
                    commandList.Begin();
                    commandList.SetFramebuffer(game.Panel.Framebuffer);
                    imGuiRenderer.Update((float)game.RenderTime.DeltaTime.TotalSeconds, window.CurrentInputSnapshot);
                    using (var fontSetter = new ImGuiFontSetter(font))
                    {
                        mainForm.Draw();
                    }
                    imGuiRenderer.Render(game.GraphicsDevice, commandList);
                    commandList.End();
                    device.SubmitCommands(commandList);
                }
                finally
                {
                    ImGui.SetCurrentContext(previousContext);
                }
            }

            window.ClientSizeChanged += OnClientSizeChanged;
            game.RenderCompleted     += OnRendering2D;
            try
            {
                game.ShowMainMenu();
                game.Run();
            }
            finally
            {
                game.RenderCompleted     -= OnRendering2D;
                window.ClientSizeChanged -= OnClientSizeChanged;
            }
        }
Example #24
0
        public static void Run(Options opts)
        {
            logger.Info("Starting...");

            var DetectedGame = opts.Game;
            var GameFolder   = opts.GamePath;
            var UseLocators  = true;

            if (GameFolder == null)
            {
                GameFolder = Environment.CurrentDirectory;
            }

            foreach (var gameDef in GameDefinition.All)
            {
                if (gameDef.Probe(GameFolder))
                {
                    DetectedGame = gameDef.Game;
                    UseLocators  = false;
                }
            }

            var definition = GameDefinition.FromGame(DetectedGame);
            GameInstallation installation;

            if (UseLocators)
            {
                installation = GameInstallation
                               .FindAll(new[] { definition })
                               .FirstOrDefault();
            }
            else
            {
                installation = new GameInstallation(definition, GameFolder);
            }

            if (installation == null)
            {
                Console.WriteLine($"OpenSAGE was unable to find any installations of {definition.DisplayName}.\n");

                Console.WriteLine("You can manually specify the installation path by setting the following environment variable:");
                Console.WriteLine($"\t{definition.Identifier.ToUpper()}_PATH=<installation path>\n");

                Console.WriteLine("OpenSAGE doesn't yet detect every released version of every game. Please report undetected versions to our GitHub page:");
                Console.WriteLine("\thttps://github.com/OpenSAGE/OpenSAGE/issues");

                Console.WriteLine("\n\n Press any key to exit.");

                Console.ReadLine();

                Environment.Exit(1);
            }

            logger.Debug($"Have installation of {definition.DisplayName}");

            Platform.Start();

            var traceEnabled = !string.IsNullOrEmpty(opts.TraceFile);

            if (traceEnabled)
            {
                GameTrace.Start(opts.TraceFile);
            }

            // TODO: Read game version from assembly metadata or .git folder
            // TODO: Set window icon.
            var config = new Configuration()
            {
                UseRenderDoc   = opts.RenderDoc,
                LoadShellMap   = !opts.NoShellmap,
                UseUniquePorts = opts.UseUniquePorts
            };

            UPnP.InitializeAsync(TimeSpan.FromSeconds(10)).ContinueWith(_ => logger.Info($"UPnP status: {UPnP.Status}"));

            logger.Debug($"Have configuration");

            using (var window = new GameWindow($"OpenSAGE - {installation.Game.DisplayName} - master", 100, 100, 1024, 768, opts.Fullscreen))
                using (var game = new Game(installation, opts.Renderer, config, window))
                    using (var textureCopier = new TextureCopier(game, window.Swapchain.Framebuffer.OutputDescription))
                        using (var developerModeView = new DeveloperModeView(game, window))
                        {
                            game.GraphicsDevice.SyncToVerticalBlank = !opts.DisableVsync;

                            var developerModeEnabled = opts.DeveloperMode;

                            if (opts.DeveloperMode)
                            {
                                window.Maximized = true;
                            }

                            if (opts.ReplayFile != null)
                            {
                                var replayFile = game.ContentManager.UserDataFileSystem?.GetFile(Path.Combine("Replays", opts.ReplayFile));
                                if (replayFile == null)
                                {
                                    logger.Debug("Could not find entry for Replay " + opts.ReplayFile);
                                    game.ShowMainMenu();
                                }

                                game.LoadReplayFile(replayFile);
                            }
                            else if (opts.Map != null)
                            {
                                game.Restart = StartMap;
                                StartMap();

                                void StartMap()
                                {
                                    var mapCache = game.AssetStore.MapCaches.GetByName(opts.Map);

                                    if (mapCache == null)
                                    {
                                        logger.Debug("Could not find MapCache entry for map " + opts.Map);
                                        game.ShowMainMenu();
                                    }
                                    else if (mapCache.IsMultiplayer)
                                    {
                                        var pSettings = new PlayerSetting[]
                                        {
                                            new PlayerSetting(null, "FactionAmerica", new ColorRgb(255, 0, 0), 0, PlayerOwner.Player),
                                            new PlayerSetting(null, "FactionGLA", new ColorRgb(0, 255, 0), 0, PlayerOwner.EasyAi),
                                        };

                                        logger.Debug("Starting multiplayer game");

                                        game.StartSkirmishOrMultiPlayerGame(opts.Map,
                                                                            new EchoConnection(),
                                                                            pSettings,
                                                                            Environment.TickCount,
                                                                            false);
                                    }
                                    else
                                    {
                                        logger.Debug("Starting singleplayer game");

                                        game.StartSinglePlayerGame(opts.Map);
                                    }
                                }
                            }
                            else
                            {
                                logger.Debug("Showing main menu");
                                game.ShowMainMenu();
                            }

                            game.InputMessageBuffer.Handlers.Add(
                                new CallbackMessageHandler(
                                    HandlingPriority.Window,
                                    message =>
                            {
                                if (message.MessageType == InputMessageType.KeyDown && message.Value.Key == Key.Enter && (message.Value.Modifiers & ModifierKeys.Alt) != 0)
                                {
                                    window.Fullscreen = !window.Fullscreen;
                                    return(InputMessageResult.Handled);
                                }

                                if (message.MessageType == InputMessageType.KeyDown && message.Value.Key == Key.F11)
                                {
                                    developerModeEnabled = !developerModeEnabled;
                                    return(InputMessageResult.Handled);
                                }

                                return(InputMessageResult.NotHandled);
                            }));

                            logger.Debug("Starting game");

                            game.StartRun();

                            while (game.IsRunning)
                            {
                                if (!window.PumpEvents())
                                {
                                    break;
                                }

                                if (developerModeEnabled)
                                {
                                    developerModeView.Tick();
                                }
                                else
                                {
                                    game.Update(window.MessageQueue);

                                    game.Panel.EnsureFrame(window.ClientBounds);

                                    game.Render();

                                    textureCopier.Execute(
                                        game.Panel.Framebuffer.ColorTargets[0].Target,
                                        window.Swapchain.Framebuffer);
                                }

                                window.MessageQueue.Clear();

                                game.GraphicsDevice.SwapBuffers(window.Swapchain);
                            }
                        }

            if (traceEnabled)
            {
                GameTrace.Stop();
            }

            Platform.Stop();
        }
Example #25
0
        public MainForm()
        {
            ClientSize = new Size(1024, 768);
            Maximize();

            Title = "OpenSAGE Data Viewer";

            Icon = Icon.FromResource("OpenSage.DataViewer.Resources.AppIcon.ico");

            var quitCommand = new Command((sender, e) => Application.Instance.Quit())
            {
                MenuText = "Quit",
                Shortcut = Application.Instance.CommonModifier | Keys.Q
            };

            _installationsMenuItem = new ButtonMenuItem {
                Text = "&Installation"
            };
            RadioCommand firstInstallationCommand = null;

            var installations = GameInstallation.FindAll(GameDefinition.All);

            foreach (var installation in installations)
            {
                var installationCommand = new RadioCommand((sender, e) => ChangeInstallation(installation))
                {
                    MenuText = installation.Game.DisplayName.Replace("&", "&&")
                };

                if (firstInstallationCommand == null)
                {
                    firstInstallationCommand = installationCommand;
                }
                else
                {
                    installationCommand.Controller = firstInstallationCommand;
                }

                _installationsMenuItem.Items.Add(installationCommand);
            }

            Menu = new MenuBar
            {
                Items =
                {
                    _installationsMenuItem,
                },
                QuitItem = quitCommand
            };

            _installationImageView        = new ImageView();
            _installationImageView.Width  = 250;
            _installationImageView.Height = 187;

            var contentView = new ContentView(() => _installation, () => _fileSystem);

            var filesList = new FilesList(this)
            {
                Width = 250
            };

            filesList.SelectedFileChanged += (sender, e) =>
            {
                contentView.SetContent(e.Entry);
            };

            var sidebar = new TableLayout(
                _installationImageView,
                filesList);

            Content = new Splitter
            {
                Panel1 = sidebar,
                Panel2 = contentView
            };
        }