Exemplo n.º 1
0
 Route(string path)
 {
     if (Directory.Exists(path))
     {
         var trkFilePath = MSTSPath.GetTRKFileName(path);
         try
         {
             var trkFile = new RouteFile(trkFilePath);
             Name        = trkFile.Tr_RouteFile.Name.Trim();
             RouteID     = trkFile.Tr_RouteFile.RouteID;
             Description = trkFile.Tr_RouteFile.Description.Trim();
         }
         catch
         {
             Name = "<" + catalog.GetString("load error:") + " " + System.IO.Path.GetFileName(path) + ">";
         }
         if (string.IsNullOrEmpty(Name))
         {
             Name = "<" + catalog.GetString("unnamed:") + " " + System.IO.Path.GetFileNameWithoutExtension(path) + ">";
         }
         if (string.IsNullOrEmpty(Description))
         {
             Description = null;
         }
     }
     else
     {
         Name = "<" + catalog.GetString("missing:") + " " + System.IO.Path.GetFileName(path) + ">";
     }
     Path = path;
 }
Exemplo n.º 2
0
        private void LoadFolders()
        {
            Folders = new List <MenuWPF.MainWindow.Folder>();


            if (File.Exists(foldersFile))
            {
                try
                {
                    using (var inf = new BinaryReader(File.Open(foldersFile, FileMode.Open)))
                    {
                        var count = inf.ReadInt32();
                        for (var i = 0; i < count; ++i)
                        {
                            var path = inf.ReadString();
                            var name = inf.ReadString();
                            Folders.Add(new MenuWPF.MainWindow.Folder(name, path));
                            listBoxFolders.Items.Add(name);
                        }
                    }
                }
                catch (Exception error)
                {
                    MessageBox.Show(error.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }

            if (Folders.Count == 0)
            {
                try
                {
                    Folders.Add(new MenuWPF.MainWindow.Folder("- Default -", MSTSPath.Base()));
                    listBoxFolders.Items.Add("- Default -");
                }
                catch (Exception)
                {
                    MessageBox.Show("Microsoft Train Simulator doesn't appear to be installed.\nClick on 'Add...' to point Open Rails at your Microsoft Train Simulator folder.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }

            Folders = Folders.OrderBy(f => f.Name).ToList();
        }
Exemplo n.º 3
0
        public OptionsForm(UserSettings settings, UpdateManager updateManager, bool initialContentSetup)
        {
            InitializeComponent();

            Localizer.Localize(this, catalog);

            Settings      = settings;
            UpdateManager = updateManager;

            // Collect all the available language codes by searching for
            // localisation files, but always include English (base language).
            var languageCodes = new List <string> {
                "en"
            };

            foreach (var path in Directory.GetDirectories(Path.GetDirectoryName(Application.ExecutablePath)))
            {
                if (Directory.GetFiles(path, "*.Messages.resources.dll").Length > 0)
                {
                    languageCodes.Add(Path.GetFileName(path));
                }
            }

            // Turn the list of codes in to a list of code + name pairs for
            // displaying in the dropdown list.
            comboLanguage.DataSource =
                new[] { new ComboBoxMember {
                            Code = "", Name = "System"
                        } }
            .Union(languageCodes
                   .SelectMany(lc =>
            {
                try
                {
                    return(new[] { new ComboBoxMember {
                                       Code = lc, Name = CultureInfo.GetCultureInfo(lc).NativeName
                                   } });
                }
                catch (ArgumentException)
                {
                    return(new ComboBoxMember[0]);
                }
            })
                   .OrderBy(l => l.Name)
                   )
            .ToList();
            comboLanguage.DisplayMember = "Name";
            comboLanguage.ValueMember   = "Code";
            comboLanguage.SelectedValue = Settings.Language;
            if (comboLanguage.SelectedValue == null)
            {
                comboLanguage.SelectedIndex = 0;
            }

            comboBoxOtherUnits.DataSource = new[] {
                new ComboBoxMember {
                    Code = "Route", Name = catalog.GetString("Route")
                },
                new ComboBoxMember {
                    Code = "Automatic", Name = catalog.GetString("Player's location")
                },
                new ComboBoxMember {
                    Code = "Metric", Name = catalog.GetString("Metric")
                },
                new ComboBoxMember {
                    Code = "US", Name = catalog.GetString("Imperial US")
                },
                new ComboBoxMember {
                    Code = "UK", Name = catalog.GetString("Imperial UK")
                },
            }.ToList();
            comboBoxOtherUnits.DisplayMember = "Name";
            comboBoxOtherUnits.ValueMember   = "Code";
            comboBoxOtherUnits.SelectedValue = Settings.Units;

            comboPressureUnit.DataSource = new[] {
                new ComboBoxMember {
                    Code = "Automatic", Name = catalog.GetString("Automatic")
                },
                new ComboBoxMember {
                    Code = "bar", Name = catalog.GetString("bar")
                },
                new ComboBoxMember {
                    Code = "PSI", Name = catalog.GetString("psi")
                },
                new ComboBoxMember {
                    Code = "inHg", Name = catalog.GetString("inHg")
                },
                new ComboBoxMember {
                    Code = "kgf/cm^2", Name = catalog.GetString("kgf/cm²")
                },
            }.ToList();
            comboPressureUnit.DisplayMember = "Name";
            comboPressureUnit.ValueMember   = "Code";
            comboPressureUnit.SelectedValue = Settings.PressureUnit;

            // Windows 2000 and XP should use 8.25pt Tahoma, while Windows
            // Vista and later should use 9pt "Segoe UI". We'll use the
            // Message Box font to allow for user-customizations, though.
            Font = SystemFonts.MessageBoxFont;
            AdhesionLevelValue.Font = new Font(Font, FontStyle.Bold);

            // Fix up the TrackBars on TabPanels to match the current theme.
            if (!Application.RenderWithVisualStyles)
            {
                trackAdhesionFactor.BackColor       = BackColor;
                trackAdhesionFactorChange.BackColor = BackColor;
                trackDayAmbientLight.BackColor      = BackColor;
                trackLODBias.BackColor = BackColor;
            }

            // General tab
            checkAlerter.Checked               = Settings.Alerter;
            checkAlerterExternal.Enabled       = Settings.Alerter;
            checkAlerterExternal.Checked       = Settings.Alerter && !Settings.AlerterDisableExternal;
            checkSpeedControl.Checked          = Settings.SpeedControl;
            checkConfirmations.Checked         = !Settings.SuppressConfirmations;
            checkViewDispatcher.Checked        = Settings.ViewDispatcher;
            checkUseLargeAddressAware.Checked  = Settings.UseLargeAddressAware;
            checkRetainers.Checked             = Settings.RetainersOnAllCars;
            checkGraduatedRelease.Checked      = Settings.GraduatedRelease;
            numericBrakePipeChargingRate.Value = Settings.BrakePipeChargingRate;
            comboLanguage.Text             = Settings.Language;
            comboPressureUnit.Text         = Settings.PressureUnit;
            comboBoxOtherUnits.Text        = settings.Units;
            checkDisableTCSScripts.Checked = Settings.DisableTCSScripts;


            // Audio tab
            checkMSTSBINSound.Checked                 = Settings.MSTSBINSound;
            numericSoundVolumePercent.Value           = Settings.SoundVolumePercent;
            numericSoundDetailLevel.Value             = Settings.SoundDetailLevel;
            numericExternalSoundPassThruPercent.Value = Settings.ExternalSoundPassThruPercent;

            // Video tab
            checkDynamicShadows.Checked       = Settings.DynamicShadows;
            checkShadowAllShapes.Checked      = Settings.ShadowAllShapes;
            checkFastFullScreenAltTab.Checked = Settings.FastFullScreenAltTab;
            checkWindowGlass.Checked          = Settings.WindowGlass;
            checkModelInstancing.Checked      = Settings.ModelInstancing;
            checkWire.Checked             = Settings.Wire;
            checkVerticalSync.Checked     = Settings.VerticalSync;
            numericCab2DStretch.Value     = Settings.Cab2DStretch;
            numericViewingDistance.Value  = Settings.ViewingDistance;
            checkDistantMountains.Checked = Settings.DistantMountains;
            labelDistantMountainsViewingDistance.Enabled   = checkDistantMountains.Checked;
            numericDistantMountainsViewingDistance.Enabled = checkDistantMountains.Checked;
            numericDistantMountainsViewingDistance.Value   = Settings.DistantMountainsViewingDistance / 1000;
            numericViewingFOV.Value         = Settings.ViewingFOV;
            numericWorldObjectDensity.Value = Settings.WorldObjectDensity;
            comboWindowSize.Text            = Settings.WindowSize;
            trackDayAmbientLight.Value      = Settings.DayAmbientLight;
            trackDayAmbientLight_ValueChanged(null, null);
            checkDoubleWire.Checked = Settings.DoubleWire;

            // Simulation tab
            checkUseAdvancedAdhesion.Checked               = Settings.UseAdvancedAdhesion;
            labelAdhesionMovingAverageFilterSize.Enabled   = checkUseAdvancedAdhesion.Checked;
            numericAdhesionMovingAverageFilterSize.Enabled = checkUseAdvancedAdhesion.Checked;
            numericAdhesionMovingAverageFilterSize.Value   = Settings.AdhesionMovingAverageFilterSize;
            checkBreakCouplers.Checked                = Settings.BreakCouplers;
            checkCurveResistanceDependent.Checked     = Settings.CurveResistanceDependent;
            checkCurveSpeedDependent.Checked          = Settings.CurveSpeedDependent;
            checkTunnelResistanceDependent.Checked    = Settings.TunnelResistanceDependent;
            checkWindResistanceDependent.Checked      = Settings.WindResistanceDependent;
            checkOverrideNonElectrifiedRoutes.Checked = Settings.OverrideNonElectrifiedRoutes;
            checkHotStart.Checked  = Settings.HotStart;
            checkAutopilot.Checked = Settings.Autopilot;
            checkForcedRedAtStationStops.Checked = !Settings.NoForcedRedAtStationStops;
            checkExtendedAIShunting.Checked      = Settings.ExtendedAIShunting;
            checkDoorsAITrains.Checked           = Settings.OpenDoorsInAITrains;

            // Keyboard tab
            InitializeKeyboardSettings();

            // DataLogger tab
            var dictionaryDataLoggerSeparator = new Dictionary <string, string>();

            dictionaryDataLoggerSeparator.Add("comma", catalog.GetString("comma"));
            dictionaryDataLoggerSeparator.Add("semicolon", catalog.GetString("semicolon"));
            dictionaryDataLoggerSeparator.Add("tab", catalog.GetString("tab"));
            dictionaryDataLoggerSeparator.Add("space", catalog.GetString("space"));
            comboDataLoggerSeparator.DataSource    = new BindingSource(dictionaryDataLoggerSeparator, null);
            comboDataLoggerSeparator.DisplayMember = "Value";
            comboDataLoggerSeparator.ValueMember   = "Key";
            comboDataLoggerSeparator.Text          = catalog.GetString(Settings.DataLoggerSeparator);
            var dictionaryDataLogSpeedUnits = new Dictionary <string, string>();

            dictionaryDataLogSpeedUnits.Add("route", catalog.GetString("route"));
            dictionaryDataLogSpeedUnits.Add("mps", catalog.GetString("m/s"));
            dictionaryDataLogSpeedUnits.Add("kmph", catalog.GetString("km/h"));
            dictionaryDataLogSpeedUnits.Add("mph", catalog.GetString("mph"));
            comboDataLogSpeedUnits.DataSource    = new BindingSource(dictionaryDataLogSpeedUnits, null);
            comboDataLogSpeedUnits.DisplayMember = "Value";
            comboDataLogSpeedUnits.ValueMember   = "Key";
            comboDataLogSpeedUnits.Text          = catalog.GetString(Settings.DataLogSpeedUnits);
            checkDataLogger.Checked              = Settings.DataLogger;
            checkDataLogPerformance.Checked      = Settings.DataLogPerformance;
            checkDataLogPhysics.Checked          = Settings.DataLogPhysics;
            checkDataLogMisc.Checked             = Settings.DataLogMisc;
            checkDataLogSteamPerformance.Checked = Settings.DataLogSteamPerformance;

            // Evaluation tab
            checkDataLogTrainSpeed.Checked     = Settings.DataLogTrainSpeed;
            labelDataLogTSInterval.Enabled     = checkDataLogTrainSpeed.Checked;
            numericDataLogTSInterval.Enabled   = checkDataLogTrainSpeed.Checked;
            checkListDataLogTSContents.Enabled = checkDataLogTrainSpeed.Checked;
            numericDataLogTSInterval.Value     = Settings.DataLogTSInterval;
            checkListDataLogTSContents.Items.AddRange(new object[] {
                catalog.GetString("Time"),
                catalog.GetString("Train Speed"),
                catalog.GetString("Max. Speed"),
                catalog.GetString("Signal State"),
                catalog.GetString("Track Elevation"),
                catalog.GetString("Direction"),
                catalog.GetString("Control Mode"),
                catalog.GetString("Distance Travelled"),
                catalog.GetString("Throttle %"),
                catalog.GetString("Brake Cyl Press"),
                catalog.GetString("Dyn Brake %"),
                catalog.GetString("Gear Setting")
            });
            for (var i = 0; i < checkListDataLogTSContents.Items.Count; i++)
            {
                checkListDataLogTSContents.SetItemChecked(i, Settings.DataLogTSContents[i] == 1);
            }
            checkDataLogStationStops.Checked = Settings.DataLogStationStops;

            // Content tab
            bindingSourceContent.DataSource = (from folder in Settings.Folders.Folders
                                               orderby folder.Key
                                               select new ContentFolder()
            {
                Name = folder.Key, Path = folder.Value
            }).ToList();
            if (initialContentSetup)
            {
                tabOptions.SelectedTab      = tabPageContent;
                buttonContentBrowse.Enabled = false; // Initial state because browsing a null path leads to an exception
                try
                {
                    bindingSourceContent.Add(new ContentFolder()
                    {
                        Name = "Train Simulator", Path = MSTSPath.Base()
                    });
                }
                catch { }
            }

            // Updater tab
            var updateChannelNames = new Dictionary <string, string> {
                { "stable", catalog.GetString("Stable (recommended)") },
                { "testing", catalog.GetString("Testing") },
                { "unstable", catalog.GetString("Unstable") },
                { "", catalog.GetString("None") },
            };
            var updateChannelDescriptions = new Dictionary <string, string> {
                { "stable", catalog.GetString("Infrequent updates to official, hand-picked versions. Recommended for most users.") },
                { "testing", catalog.GetString("Weekly updates which may contain noticable defects. For project supporters.") },
                { "unstable", catalog.GetString("Daily updates which may contain serious defects. For developers only.") },
                { "", catalog.GetString("No updates.") },
            };
            var spacing = labelUpdateChannel.Margin.Size;
            var indent  = 20;
            var top     = labelUpdateChannel.Bottom + spacing.Height;

            foreach (var channel in UpdateManager.GetChannels())
            {
                var radio = new RadioButton()
                {
                    Text     = updateChannelNames[channel.ToLowerInvariant()],
                    Margin   = labelUpdateChannel.Margin,
                    Left     = spacing.Width,
                    Top      = top,
                    Checked  = updateManager.ChannelName.Equals(channel, StringComparison.InvariantCultureIgnoreCase),
                    AutoSize = true,
                    Tag      = channel,
                };
                tabPageUpdater.Controls.Add(radio);
                top += radio.Height + spacing.Height;
                var label = new Label()
                {
                    Text     = updateChannelDescriptions[channel.ToLowerInvariant()],
                    Margin   = labelUpdateChannel.Margin,
                    Left     = spacing.Width + indent,
                    Top      = top,
                    Width    = tabPageUpdater.ClientSize.Width - indent - spacing.Width * 2,
                    AutoSize = true,
                };
                tabPageUpdater.Controls.Add(label);
                top += label.Height + spacing.Height;
            }

            // Experimental tab
            numericUseSuperElevation.Value        = Settings.UseSuperElevation;
            numericSuperElevationMinLen.Value     = Settings.SuperElevationMinLen;
            numericSuperElevationGauge.Value      = Settings.SuperElevationGauge;
            checkPerformanceTuner.Checked         = Settings.PerformanceTuner;
            labelPerformanceTunerTarget.Enabled   = checkPerformanceTuner.Checked;
            numericPerformanceTunerTarget.Enabled = checkPerformanceTuner.Checked;
            numericPerformanceTunerTarget.Value   = Settings.PerformanceTunerTarget;
            trackLODBias.Value = Settings.LODBias;
            trackLODBias_ValueChanged(null, null);
            checkConditionalLoadOfNightTextures.Checked = Settings.ConditionalLoadOfDayOrNightTextures;
            checkSignalLightGlow.Checked         = Settings.SignalLightGlow;
            checkCircularSpeedGauge.Checked      = Settings.CircularSpeedGauge;
            checkLODViewingExtention.Checked     = Settings.LODViewingExtention;
            checkPreferDDSTexture.Checked        = Settings.PreferDDSTexture;
            checkUseLocationPassingPaths.Checked = Settings.UseLocationPassingPaths;
            checkUseMSTSEnv.Checked            = Settings.UseMSTSEnv;
            trackAdhesionFactor.Value          = Settings.AdhesionFactor;
            checkAdhesionPropToWeather.Checked = Settings.AdhesionProportionalToWeather;
            trackAdhesionFactorChange.Value    = Settings.AdhesionFactorChange;
            trackAdhesionFactor_ValueChanged(null, null);
            checkShapeWarnings.Checked   = !Settings.SuppressShapeWarnings;
            precipitationBoxHeight.Value = Settings.PrecipitationBoxHeight;
            precipitationBoxWidth.Value  = Settings.PrecipitationBoxWidth;
            precipitationBoxLength.Value = Settings.PrecipitationBoxLength;
            checkCorrectQuestionableBrakingParams.Checked = Settings.CorrectQuestionableBrakingParams;
            numericActRandomizationLevel.Value            = Settings.ActRandomizationLevel;
            numericActWeatherRandomizationLevel.Value     = Settings.ActWeatherRandomizationLevel;
        }
Exemplo n.º 4
0
        /// <summary>
        /// Saves may come from other, foreign installations (i.e. not this PC).
        /// They can be replayed or resumed on this PC but they will contain activity / path / consist filenames
        /// and these may be inappropriate for this PC, typically having a different path.
        /// This method tries to use the paths in the Save if they exist on the current PC.
        /// If not, it prompts the user to locate a matching file from those on the current PC.
        ///
        /// The save file is then modified to contain filename(s) from the current PC instead.
        /// </summary>
        public bool Found(Save save)
        {
            if (SelectedAction == MainForm.UserAction.SinglePlayerTimetableGame)
            {
                return(true); // no additional actions required for timetable resume
            }
            else
            {
                try
                {
                    BinaryReader inf          = new BinaryReader(new FileStream(save.File, FileMode.Open, FileAccess.Read));
                    var          version      = inf.ReadString();
                    var          build        = inf.ReadString();
                    var          routeName    = inf.ReadString();
                    var          pathName     = inf.ReadString();
                    var          gameTime     = inf.ReadInt32();
                    var          realTime     = inf.ReadInt64();
                    var          currentTileX = inf.ReadSingle();
                    var          currentTileZ = inf.ReadSingle();
                    var          initialTileX = inf.ReadSingle();
                    var          initialTileZ = inf.ReadSingle();
                    var          tempInt      = inf.ReadInt32();
                    var          savedArgs    = new string[tempInt];
                    for (var i = 0; i < savedArgs.Length; i++)
                    {
                        savedArgs[i] = inf.ReadString();
                    }

                    // Re-locate files if saved on another PC
                    var rewriteNeeded = false;
                    // savedArgs[0] contains Activity or Path filepath
                    var filePath = savedArgs[0];
                    if (!System.IO.File.Exists(filePath))
                    {
                        // Show the dialog and get result.
                        openFileDialog1.InitialDirectory = MSTSPath.Base();
                        openFileDialog1.FileName         = Path.GetFileName(filePath);
                        openFileDialog1.Title            = @"Find location for file " + filePath;
                        if (openFileDialog1.ShowDialog() != DialogResult.OK)
                        {
                            return(false);
                        }
                        rewriteNeeded = true;
                        savedArgs[0]  = openFileDialog1.FileName;
                    }
                    if (savedArgs.Length > 1)   // Explore, not Activity
                    {
                        // savedArgs[1] contains Consist filepath
                        filePath = savedArgs[1];
                        if (!System.IO.File.Exists(filePath))
                        {
                            // Show the dialog and get result.
                            openFileDialog1.InitialDirectory = MSTSPath.Base();
                            openFileDialog1.FileName         = Path.GetFileName(filePath);
                            openFileDialog1.Title            = @"Find location for file " + filePath;
                            if (openFileDialog1.ShowDialog() != DialogResult.OK)
                            {
                                return(false);
                            }
                            rewriteNeeded = true;
                            savedArgs[1]  = openFileDialog1.FileName;
                        }
                    }
                    if (rewriteNeeded)
                    {
                        using (BinaryWriter outf = new BinaryWriter(new FileStream(save.File + ".tmp", FileMode.Create, FileAccess.Write)))
                        {
                            // copy the start of the file
                            outf.Write(version);
                            outf.Write(build);
                            outf.Write(routeName);
                            outf.Write(pathName);
                            outf.Write(gameTime);
                            outf.Write(realTime);
                            outf.Write(currentTileX);
                            outf.Write(currentTileZ);
                            outf.Write(initialTileX);
                            outf.Write(initialTileZ);
                            outf.Write(savedArgs.Length);
                            // copy the pars which may have changed
                            for (var i = 0; i < savedArgs.Length; i++)
                            {
                                outf.Write(savedArgs[i]);
                            }
                            // copy the rest of the file
                            while (inf.BaseStream.Position < inf.BaseStream.Length)
                            {
                                outf.Write(inf.ReadByte());
                            }
                        }
                        inf.Close();
                        File.Replace(save.File + ".tmp", save.File, null);
                    }
                    else
                    {
                        inf.Close();
                    }
                }
                catch
                {
                }
            }
            return(true);
        }