/// <summary>Loads a custom plugin for the specified train.</summary> /// <param name="train">The train to attach the plugin to.</param> /// <param name="trainFolder">The absolute path to the train folder.</param> /// <param name="encoding">The encoding to be used.</param> /// <returns>Whether the plugin was loaded successfully.</returns> internal static bool LoadCustomPlugin(TrainManager.Train train, string trainFolder, System.Text.Encoding encoding) { string config = OpenBveApi.Path.CombineFile(trainFolder, "ats.cfg"); if (!System.IO.File.Exists(config)) { return(false); } string[] lines = System.IO.File.ReadAllLines(config, encoding); if (lines.Length == 0) { return(false); } string file = OpenBveApi.Path.CombineFile(trainFolder, lines[0]); string title = System.IO.Path.GetFileName(file); if (!System.IO.File.Exists(file)) { Interface.AddMessage(Interface.MessageType.Error, true, "The train plugin " + title + " could not be found in " + config); return(false); } Program.AppendToLogFile("Loading train plugin: " + file); bool success = LoadPlugin(train, file, trainFolder); if (success == false) { Loading.PluginError = Interface.GetInterfaceString("errors_plugin_failure1").Replace("[plugin]", file); } else { Program.AppendToLogFile("Train plugin loaded successfully."); } return(success); }
/* -------------------------------------------------------------- * This file contains the drawing routines for the loading screen * -------------------------------------------------------------- */ internal static void DrawLoadingScreen() { // begin HACK // Gl.glEnable(Gl.GL_BLEND); BlendEnabled = true; Gl.glDisable(Gl.GL_LIGHTING); LightingEnabled = false; int size = Math.Min(Screen.Width, Screen.Height); DrawRectangle(null, new Point(0, 0), new Size(Screen.Width, Screen.Height), Color128.Black); if (Textures.LoadTexture(TextureLogo, Textures.OpenGlTextureWrapMode.ClampClamp)) { DrawRectangle(TextureLogo, new Point((Screen.Width - size) / 2, (Screen.Height - size) / 2), new Size(size, size), Color128.White); } DrawRectangle(null, new Point((Screen.Width - size) / 2, Screen.Height - (int)Fonts.NormalFont.FontSize - 10), new Size(Screen.Width, (int)Fonts.NormalFont.FontSize + 10), new Color128(0.0f, 0.0f, 0.0f, 0.5f)); // double routeProgress = Math.Max(0.0, Math.Min(1.0, Loading.RouteProgress)); // double trainProgress = Math.Max(0.0, Math.Min(1.0, Loading.TrainProgress)); string text; // if (routeProgress < 1.0) { // text = "Loading route... " + (100.0 * routeProgress).ToString("0") + "%"; // } else if (trainProgress < 1.0) { // text = "Loading train... " + (100.0 * trainProgress).ToString("0") + "%"; // } else { // text = "Loading textures and sounds..."; // } text = Interface.GetInterfaceString("message_loading"); DrawString(Fonts.SmallFont, text, new Point((Screen.Width - size) / 2 + 5, Screen.Height - (int)(Fonts.NormalFont.FontSize / 2) - 5), TextAlignment.CenterLeft, Color128.White); // end HACK // }
// joystick grab private void textboxJoystickGrab_Enter(object sender, EventArgs e) { if (!radiobuttonJoystick.Checked) { textboxJoystickGrab.Text = Interface.GetInterfaceString("controls_selection_keyboard_assignment_grabbing"); textboxJoystickGrab.BackColor = Color.Crimson; textboxJoystickGrab.ForeColor = Color.White; KeyGrab = true; return; } bool FullAxis = false; if (this.Tag == null & listviewControls.SelectedIndices.Count == 1) { int j = listviewControls.SelectedIndices[0]; if (Interface.CurrentControls[j].InheritedType == Interface.CommandType.AnalogFull) { FullAxis = true; } } if (FullAxis) { textboxJoystickGrab.Text = Interface.GetInterfaceString("controls_selection_joystick_assignment_grab_fullaxis"); } else { textboxJoystickGrab.Text = Interface.GetInterfaceString("controls_selection_joystick_assignment_grab_normal"); } textboxJoystickGrab.BackColor = Color.Crimson; textboxJoystickGrab.ForeColor = Color.White; }
private void textboxJoystickGrab_KeyDown(object sender, KeyEventArgs e) { //Required to avoid race condition with openTK recieving the same event internally System.Threading.Thread.Sleep(1); var kbState = OpenTK.Input.Keyboard.GetState(); if (KeyGrab == false) { return; } for (int j = 0; j < Interface.TranslatedKeys.Length; j++) { if (kbState.IsKeyDown(Interface.TranslatedKeys[j].Key)) { int i = listviewControls.SelectedIndices[0]; Interface.CurrentControls[i].Key = Interface.TranslatedKeys[j].Key; UpdateControlListElement(listviewControls.Items[i], i, true); comboboxKeyboardKey.SelectedIndex = j; } } textboxJoystickGrab.Text = Interface.GetInterfaceString("controls_selection_keyboard_assignment_grab"); textboxJoystickGrab.BackColor = panelControls.BackColor; textboxJoystickGrab.ForeColor = Color.Black; comboboxKeyboardKey.Focus(); }
private void textboxJoystickGrab_Leave(object sender, EventArgs e) { textboxJoystickGrab.Text = Interface.GetInterfaceString("controls_selection_joystick_assignment_grab"); textboxJoystickGrab.BackColor = panelControls.BackColor; textboxJoystickGrab.ForeColor = Color.Black; KeyGrab = false; }
// ======== // joystick // ======== // joystick private void radiobuttonJoystick_CheckedChanged(object sender, EventArgs e) { if (this.Tag == null & listviewControls.SelectedIndices.Count == 1) { int i = listviewControls.SelectedIndices[0]; Interface.CurrentControls[i].Method = Interface.ControlMethod.Joystick; UpdateControlListElement(listviewControls.Items[i], i, true); } panelJoystick.Enabled = radiobuttonJoystick.Checked; if (radiobuttonJoystick.Checked || radiobuttonKeyboard.Checked) { textboxJoystickGrab.Enabled = true; } else { textboxJoystickGrab.Enabled = false; } if (radiobuttonJoystick.Checked) { textboxJoystickGrab.Text = Interface.GetInterfaceString("controls_selection_joystick_assignment_grab"); } else { textboxJoystickGrab.Text = Interface.GetInterfaceString("controls_selection_keyboard_assignment_grab"); } }
// import private void buttonControlsImport_Click(object sender, EventArgs e) { OpenFileDialog Dialog = new OpenFileDialog(); Dialog.CheckFileExists = true; //Dialog.InitialDirectory = Interface.GetControlsFolder(); Dialog.Filter = Interface.GetInterfaceString("dialog_controlsfiles") + "|*.controls|" + Interface.GetInterfaceString("dialog_allfiles") + "|*"; if (Dialog.ShowDialog() == DialogResult.OK) { try { Interface.LoadControls(Dialog.FileName, out Interface.CurrentControls); for (int i = 0; i < listviewControls.SelectedItems.Count; i++) { listviewControls.SelectedItems[i].Selected = false; } listviewControls.Items.Clear(); ListViewItem[] Items = new ListViewItem[Interface.CurrentControls.Length]; for (int i = 0; i < Interface.CurrentControls.Length; i++) { Items[i] = new ListViewItem(new string[] { "", "", "", "" }); UpdateControlListElement(Items[i], i, false); } listviewControls.Items.AddRange(Items); listviewControls.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); } catch (Exception ex) { MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand); } } }
// load private void formLoading_Load(object sender, EventArgs e) { this.MinimumSize = this.Size; try { string f = Interface.GetCombinedFileName(Program.FileSystem.GetDataFolder("Menu"), "banner.png"); pictureboxBanner.Image = Image.FromFile(f); } catch { } labelRoute.Text = Interface.GetInterfaceString("loading_loading_route"); labelTrain.Text = Interface.GetInterfaceString("loading_loading_train"); labelAlmostTitle.Text = Interface.GetInterfaceString("loading_almost"); labelFilesNotFoundCaption.Text = Interface.GetInterfaceString("loading_almost_filesnotfound"); buttonIssues.Text = Interface.GetInterfaceString("loading_almost_show"); labelProblemsTitle.Text = Interface.GetInterfaceString("loading_problems"); listviewProblems.Columns[0].Text = Interface.GetInterfaceString("loading_problems_type"); listviewProblems.Columns[1].Text = Interface.GetInterfaceString("loading_problems_description"); buttonSave.Text = Interface.GetInterfaceString("loading_save"); buttonIgnore.Text = Interface.GetInterfaceString("loading_ignore"); buttonCancel.Text = Interface.GetInterfaceString("loading_cancel"); /* * For some reasons, the Ignore and Save Report buttons do not show * up later on Mac OS X if initially set to invisible. * */ if (Program.CurrentPlatform != Program.Platform.Mac) { buttonIgnore.Visible = false; buttonSave.Visible = false; } }
// save private void buttonSave_Click(object sender, EventArgs e) { if (Loading.Complete) { // prepare System.Text.StringBuilder Builder = new System.Text.StringBuilder(); for (int i = 0; i < Interface.MessageCount; i++) { Builder.AppendLine(Interface.Messages[i].Text); } // save SaveFileDialog Dialog = new SaveFileDialog(); Dialog.Filter = Interface.GetInterfaceString("dialog_textfiles") + "|*.txt|" + Interface.GetInterfaceString("dialog_allfiles") + "|*"; if (Dialog.ShowDialog() == DialogResult.OK) { try { System.IO.File.WriteAllText(Dialog.FileName, Builder.ToString(), System.Text.Encoding.UTF8); } catch (Exception ex) { MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand); } } } }
internal override void Trigger(int Direction, EventTriggerType TriggerType, TrainManager.Train Train, int CarIndex) { if (TriggerType == EventTriggerType.FrontCarFrontAxle) { if (Direction < 0) { Train.StationFrontCar = true; } else if (Direction > 0) { Train.StationFrontCar = false; if (Train == TrainManager.PlayerTrain) { Timetable.UpdateCustomTimetable(Game.Stations[this.StationIndex].TimetableDaytimeTexture, Game.Stations[this.StationIndex].TimetableNighttimeTexture); } } } else if (TriggerType == EventTriggerType.RearCarRearAxle) { if (Direction < 0) { Train.Station = this.StationIndex; Train.StationRearCar = true; if (Train.NextStopSkipped != TrainManager.StopSkipMode.None) { Train.LastStation = this.StationIndex; } Train.NextStopSkipped = TrainManager.StopSkipMode.None; } else if (Direction > 0) { if (Train.Station == StationIndex) { if (Train == TrainManager.PlayerTrain) { if (Game.PlayerStopsAtStation(StationIndex) & TrainManager.PlayerTrain.StationState == TrainManager.TrainStopState.Pending) { string s = Interface.GetInterfaceString("message_station_passed"); s = s.Replace("[name]", Game.Stations[StationIndex].Name); Game.AddMessage(s, MessageManager.MessageDependency.None, Interface.GameMode.Normal, MessageColor.Orange, Game.SecondsSinceMidnight + 10.0, null); } else if (Game.PlayerStopsAtStation(StationIndex) & TrainManager.PlayerTrain.StationState == TrainManager.TrainStopState.Boarding) { string s = Interface.GetInterfaceString("message_station_passed_boarding"); s = s.Replace("[name]", Game.Stations[StationIndex].Name); Game.AddMessage(s, MessageManager.MessageDependency.None, Interface.GameMode.Normal, MessageColor.Red, Game.SecondsSinceMidnight + 10.0, null); } } Train.Station = -1; Train.StationRearCar = false; Train.StationState = TrainManager.TrainStopState.Pending; int d = Train.DriverCar; Sounds.StopSound(Train.Cars[d].Sounds.Halt.Source); } } } }
// --- initialization and deinitialization --- /// <summary>Initializes audio. A call to Deinitialize must be made when terminating the program.</summary> /// <returns>Whether initializing audio was successful.</returns> internal static void Initialize() { Deinitialize(); switch (Interface.CurrentOptions.SoundRange) { case Interface.SoundRange.Low: OuterRadiusFactorMinimum = 2.0; OuterRadiusFactorMaximum = 8.0; OuterRadiusFactorMaximumSpeed = 1.0; break; case Interface.SoundRange.Medium: OuterRadiusFactorMinimum = 4.0; OuterRadiusFactorMaximum = 16.0; OuterRadiusFactorMaximumSpeed = 2.0; break; case Interface.SoundRange.High: OuterRadiusFactorMinimum = 6.0; OuterRadiusFactorMaximum = 24.0; OuterRadiusFactorMaximumSpeed = 3.0; break; } OuterRadiusFactor = Math.Sqrt(OuterRadiusFactorMinimum * OuterRadiusFactorMaximum); OuterRadiusFactorSpeed = 0.0; OpenAlDevice = Alc.OpenDevice(null); if (OpenAlDevice != IntPtr.Zero) { OpenAlContext = Alc.CreateContext(OpenAlDevice, (int[])null); if (OpenAlContext != ContextHandle.Zero) { Alc.MakeContextCurrent(OpenAlContext); try { AL.SpeedOfSound(343.0f); } catch { MessageBox.Show(Interface.GetInterfaceString("errors_sound_openal_version"), Interface.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand); } AL.DistanceModel(ALDistanceModel.None); return; } Alc.CloseDevice(OpenAlDevice); OpenAlDevice = IntPtr.Zero; MessageBox.Show(Interface.GetInterfaceString("errors_sound_openal_context"), Interface.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand); return; } OpenAlContext = ContextHandle.Zero; MessageBox.Show(Interface.GetInterfaceString("errors_sound_openal_device"), Interface.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand); }
private void textboxJoystickGrab_Leave(object sender, EventArgs e) { if (radiobuttonJoystick.Checked) { textboxJoystickGrab.Text = Interface.GetInterfaceString("controls_selection_joystick_assignment_grab"); } else { textboxJoystickGrab.Text = Interface.GetInterfaceString("controls_selection_keyboard_assignment_grab"); } textboxJoystickGrab.BackColor = panelControls.BackColor; textboxJoystickGrab.ForeColor = Color.Black; KeyGrab = false; }
// ================ // review last game // ================ // score save private void buttonScoreExport_Click(object sender, EventArgs e) { SaveFileDialog Dialog = new SaveFileDialog(); Dialog.OverwritePrompt = true; Dialog.Filter = Interface.GetInterfaceString("dialog_textfiles") + "|*.txt|" + Interface.GetInterfaceString("dialog_allfiles") + "|*"; if (Dialog.ShowDialog() == DialogResult.OK) { try { Interface.ExportScore(Dialog.FileName); } catch (Exception ex) { MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand); } } }
private void UpdateFrontForward(TrainManager.Train Train, bool UpdateTrain, bool UpdateSection) { if (UpdateTrain) { // update train if (this.NextSectionIndex >= 0) { if (!Game.Sections[this.NextSectionIndex].Invisible) { if (Game.Sections[this.NextSectionIndex].CurrentAspect >= 0) { Train.CurrentSectionLimit = Game.Sections[this.NextSectionIndex].Aspects[Game.Sections[this.NextSectionIndex].CurrentAspect].Speed; } else { Train.CurrentSectionLimit = double.PositiveInfinity; } Train.CurrentSectionIndex = this.NextSectionIndex; } } else { Train.CurrentSectionLimit = double.PositiveInfinity; Train.CurrentSectionIndex = -1; } // messages if (this.NextSectionIndex < 0 || !Game.Sections[this.NextSectionIndex].Invisible) { if (Train.CurrentSectionLimit == 0.0 && Game.MinimalisticSimulation == false) { Game.AddMessage(Interface.GetInterfaceString("message_signal_stop"), MessageManager.MessageDependency.PassedRedSignal, Interface.GameMode.Normal, MessageColor.Red, double.PositiveInfinity, null); } else if (Train.Specs.CurrentAverageSpeed > Train.CurrentSectionLimit) { Game.AddMessage(Interface.GetInterfaceString("message_signal_overspeed"), MessageManager.MessageDependency.SectionLimit, Interface.GameMode.Normal, MessageColor.Orange, double.PositiveInfinity, null); } } } if (UpdateSection) { // update sections if (this.NextSectionIndex >= 0) { Game.Sections[this.NextSectionIndex].Enter(Train); Game.UpdateSection(this.NextSectionIndex); } } }
/// <summary>Loads a custom plugin for the specified train.</summary> /// <param name="train">The train to attach the plugin to.</param> /// <param name="trainFolder">The absolute path to the train folder.</param> /// <param name="encoding">The encoding to be used.</param> /// <returns>Whether the plugin was loaded successfully.</returns> internal static bool LoadCustomPlugin(TrainManager.Train train, string trainFolder, System.Text.Encoding encoding) { string config = OpenBveApi.Path.CombineFile(trainFolder, "ats.cfg"); if (!System.IO.File.Exists(config)) { return(false); } string[] lines = System.IO.File.ReadAllLines(config, encoding); if (lines.Length == 0) { return(false); } string file = OpenBveApi.Path.CombineFile(trainFolder, lines[0]); string title = System.IO.Path.GetFileName(file); if (!System.IO.File.Exists(file)) { if (lines[0].EndsWith(".dll") && encoding.Equals(System.Text.Encoding.Unicode)) { // Our filename ends with .dll so probably is not mangled Unicode Interface.AddMessage(Interface.MessageType.Error, true, "The train plugin " + title + " could not be found in " + config); return(false); } // Try again with ASCII encoding lines = System.IO.File.ReadAllLines(config, System.Text.Encoding.GetEncoding(1252)); file = OpenBveApi.Path.CombineFile(trainFolder, lines[0]); title = System.IO.Path.GetFileName(file); if (!System.IO.File.Exists(file)) { // Nope, still not found Interface.AddMessage(Interface.MessageType.Error, true, "The train plugin " + title + " could not be found in " + config); return(false); } } Program.AppendToLogFile("Loading train plugin: " + file); bool success = LoadPlugin(train, file, trainFolder); if (success == false) { Loading.PluginError = Interface.GetInterfaceString("errors_plugin_failure1").Replace("[plugin]", file); } else { Program.AppendToLogFile("Train plugin loaded successfully."); } return(success); }
// ======= // options // ======= // language private void comboboxLanguages_SelectedIndexChanged(object sender, EventArgs e) { if (this.Tag != null) { return; } int i = comboboxLanguages.SelectedIndex; if (i >= 0 & i < LanguageFiles.Length) { string Code = System.IO.Path.GetFileNameWithoutExtension(LanguageFiles[i]); string Folder = Program.FileSystem.GetDataFolder("Flags"); #if !DEBUG try { #endif Interface.LoadLanguage(LanguageFiles[i]); #if !DEBUG } catch (Exception ex) { MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand); } #endif #if !DEBUG try { #endif string Flag = Interface.GetInterfaceString("language_flag"); string File = OpenBveApi.Path.CombineFile(Folder, Flag); if (!System.IO.File.Exists(File)) { File = OpenBveApi.Path.CombineFile(Folder, "unknown.png"); } if (System.IO.File.Exists(File)) { pictureboxLanguage.Image = Image.FromFile(File); } else { pictureboxLanguage.Image = null; } CurrentLanguageCode = Code; #if !DEBUG } catch { } #endif ApplyLanguage(); TextboxRouteFilterTextChanged(null, null); TextboxTrainFilterTextChanged(null, null); } }
// export private void buttonControlsExport_Click(object sender, EventArgs e) { SaveFileDialog Dialog = new SaveFileDialog(); Dialog.OverwritePrompt = true; //Dialog.InitialDirectory = Interface.GetControlsFolder(); Dialog.Filter = Interface.GetInterfaceString("dialog_controlsfiles") + "|*.controls|" + Interface.GetInterfaceString("dialog_allfiles") + "|*"; if (Dialog.ShowDialog() == DialogResult.OK) { try { Interface.SaveControls(Dialog.FileName); } catch (Exception ex) { MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand); } } }
private void UpdateControlListElement(ListViewItem Item, int Index, bool ResizeColumns) { Interface.CommandInfo Info; Interface.TryGetCommandInfo(Interface.CurrentControls[Index].Command, out Info); Item.SubItems[0].Text = Info.Name; switch (Info.Type) { case Interface.CommandType.Digital: Item.SubItems[1].Text = Interface.GetInterfaceString("controls_list_type_digital"); break; case Interface.CommandType.AnalogHalf: Item.SubItems[1].Text = Interface.GetInterfaceString("controls_list_type_analoghalf"); break; case Interface.CommandType.AnalogFull: Item.SubItems[1].Text = Interface.GetInterfaceString("controls_list_type_analogfull"); break; default: Item.SubItems[1].Text = Info.Type.ToString(); break; } Item.SubItems[2].Text = Info.Description; if (Interface.CurrentControls[Index].Method == Interface.ControlMethod.Keyboard) { Item.ImageKey = "keyboard"; } else if (Interface.CurrentControls[Index].Method == Interface.ControlMethod.Joystick) { if (Info.Type == Interface.CommandType.AnalogHalf | Info.Type == Interface.CommandType.AnalogFull) { Item.ImageKey = "joystick"; } else { Item.ImageKey = "gamepad"; } } else { Item.ImageKey = null; } Item.SubItems[3].Text = GetControlDetails(Index); if (ResizeColumns) { listviewControls.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); } }
// black box export private void buttonBlackBoxExport_Click(object sender, EventArgs e) { SaveFileDialog Dialog = new SaveFileDialog(); Dialog.OverwritePrompt = true; if (comboboxBlackBoxFormat.SelectedIndex == 0) { Dialog.Filter = Interface.GetInterfaceString("dialog_csvfiles") + "|*.txt|" + Interface.GetInterfaceString("dialog_allfiles") + "|*"; } else { Dialog.Filter = Interface.GetInterfaceString("dialog_textfiles") + "|*.txt|" + Interface.GetInterfaceString("dialog_allfiles") + "|*"; } if (Dialog.ShowDialog() == DialogResult.OK) { try { Interface.ExportBlackBox(Dialog.FileName, (Interface.BlackBoxFormat)comboboxBlackBoxFormat.SelectedIndex); } catch (Exception ex) { MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand); } } }
private void textboxJoystickGrab_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { if (KeyGrab == false) { return; } KeyboardState state = OpenTK.Input.Keyboard.GetState(); for (int j = 0; j < Interface.TranslatedKeys.Length; j++) { if (state.IsKeyDown(Interface.TranslatedKeys[j].Key)) { int i = listviewControls.SelectedIndices[0]; Interface.CurrentControls[i].Key = Interface.TranslatedKeys[j].Key; UpdateControlListElement(listviewControls.Items[i], i, true); comboboxKeyboardKey.SelectedIndex = j; } } textboxJoystickGrab.Text = Interface.GetInterfaceString("controls_selection_keyboard_assignment_grab"); textboxJoystickGrab.BackColor = panelControls.BackColor; textboxJoystickGrab.ForeColor = Color.Black; comboboxKeyboardKey.Focus(); }
private void routeWorkerThread_completed(object sender, RunWorkerCompletedEventArgs e) { if (e.Error != null) { TryLoadImage(pictureboxRouteImage, "route_error.png"); textboxRouteDescription.Text = e.Error.Message; textboxRouteEncodingPreview.Text = ""; pictureboxRouteMap.Image = null; pictureboxRouteGradient.Image = null; Result.RouteFile = null; checkboxTrainDefault.Text = Interface.GetInterfaceString("start_train_usedefault"); return; } try { pictureboxRouteMap.Image = Illustrations.CreateRouteMap(pictureboxRouteMap.Width, pictureboxRouteMap.Height, false); pictureboxRouteGradient.Image = Illustrations.CreateRouteGradientProfile(pictureboxRouteGradient.Width, pictureboxRouteGradient.Height, false); // image if (Game.RouteImage.Length != 0) { try { pictureboxRouteImage.Image = Image.FromFile(Game.RouteImage); } catch { TryLoadImage(pictureboxRouteImage, "route_error.png"); } } else { string[] f = new string[] { ".png", ".bmp", ".gif", ".tiff", ".tif", ".jpeg", ".jpg" }; int i; for (i = 0; i < f.Length; i++) { string g = OpenBveApi.Path.CombineFile(System.IO.Path.GetDirectoryName(Result.RouteFile), System.IO.Path.GetFileNameWithoutExtension(Result.RouteFile) + f[i]); if (System.IO.File.Exists(g)) { try { pictureboxRouteImage.Image = Image.FromFile(g); } catch { pictureboxRouteImage.Image = null; } break; } } if (i == f.Length) { TryLoadImage(pictureboxRouteImage, "route_unknown.png"); } } // description string Description = Interface.ConvertNewlinesToCrLf(Game.RouteComment); if (Description.Length != 0) { textboxRouteDescription.Text = Description; } else { textboxRouteDescription.Text = System.IO.Path.GetFileNameWithoutExtension(Result.RouteFile); } textboxRouteEncodingPreview.Text = Interface.ConvertNewlinesToCrLf(Description); if (Game.TrainName != null) { checkboxTrainDefault.Text = Interface.GetInterfaceString("start_train_usedefault") + @" (" + Game.TrainName + @")"; } else { checkboxTrainDefault.Text = Interface.GetInterfaceString("start_train_usedefault"); } } catch (Exception ex) { TryLoadImage(pictureboxRouteImage, "route_error.png"); textboxRouteDescription.Text = ex.Message; textboxRouteEncodingPreview.Text = ""; pictureboxRouteMap.Image = null; pictureboxRouteGradient.Image = null; Result.RouteFile = null; checkboxTrainDefault.Text = Interface.GetInterfaceString("start_train_usedefault"); } if (checkboxTrainDefault.Checked) { ShowDefaultTrain(); } this.Cursor = Cursors.Default; //Deliberately select the tab when the process is complete //This hopefully fixes another instance of the 'grey tabs' bug tabcontrolRouteDetails.SelectedTab = tabpageRouteDescription; buttonStart.Enabled = Result.RouteFile != null & Result.TrainFolder != null; }
// get control details private string GetControlDetails(int Index) { Interface.CommandInfo Info; Interface.TryGetCommandInfo(Interface.CurrentControls[Index].Command, out Info); System.Globalization.CultureInfo Culture = System.Globalization.CultureInfo.InvariantCulture; string Separator = Interface.GetInterfaceString("controls_assignment_separator"); if (Interface.CurrentControls[Index].Method == Interface.ControlMethod.Keyboard) { string t = Interface.GetInterfaceString("controls_assignment_keyboard") + Separator; if ((Interface.CurrentControls[Index].Modifier & Interface.KeyboardModifier.Shift) != 0) { t += Interface.GetInterfaceString("controls_assignment_keyboard_shift"); } if ((Interface.CurrentControls[Index].Modifier & Interface.KeyboardModifier.Ctrl) != 0) { t += Interface.GetInterfaceString("controls_assignment_keyboard_ctrl"); } if ((Interface.CurrentControls[Index].Modifier & Interface.KeyboardModifier.Alt) != 0) { t += Interface.GetInterfaceString("controls_assignment_keyboard_alt"); } int j; for (j = 0; j < Interface.Keys.Length; j++) { if (Interface.Keys[j].Value == Interface.CurrentControls[Index].Element) { t += Interface.Keys[j].Description; break; } } if (j == Interface.Keys.Length) { t += "{" + Interface.CurrentControls[Index].Element.ToString(Culture) + "}"; } return(t); } else if (Interface.CurrentControls[Index].Method == Interface.ControlMethod.Joystick) { string t = Interface.GetInterfaceString("controls_assignment_joystick").Replace("[index]", (Interface.CurrentControls[Index].Device + 1).ToString(Culture)); switch (Interface.CurrentControls[Index].Component) { case Interface.JoystickComponent.Axis: t += Separator + Interface.GetInterfaceString("controls_assignment_joystick_axis").Replace("[index]", (Interface.CurrentControls[Index].Element + 1).ToString(Culture)); if (Interface.CurrentControls[Index].Direction == -1) { t += Separator + Interface.GetInterfaceString("controls_assignment_joystick_axis_negative"); } else if (Interface.CurrentControls[Index].Direction == 1) { t += Separator + Interface.GetInterfaceString("controls_assignment_joystick_axis_positive"); } else { t += Separator + Interface.GetInterfaceString("controls_assignment_joystick_axis_invalid"); } break; case Interface.JoystickComponent.Button: t += Separator + Interface.GetInterfaceString("controls_assignment_joystick_button").Replace("[index]", (Interface.CurrentControls[Index].Element + 1).ToString(Culture)); break; case Interface.JoystickComponent.Hat: t += Separator + Interface.GetInterfaceString("controls_assignment_joystick_hat").Replace("[index]", (Interface.CurrentControls[Index].Element + 1).ToString(Culture)); if (Interface.CurrentControls[Index].Direction == (int)Sdl.SDL_HAT_LEFT) { t += Separator + Interface.GetInterfaceString("controls_assignment_joystick_hat_left"); } else if (Interface.CurrentControls[Index].Direction == (int)Sdl.SDL_HAT_LEFTUP) { t += Separator + Interface.GetInterfaceString("controls_assignment_joystick_hat_upleft"); } else if (Interface.CurrentControls[Index].Direction == (int)Sdl.SDL_HAT_UP) { t += Separator + Interface.GetInterfaceString("controls_assignment_joystick_hat_up"); } else if (Interface.CurrentControls[Index].Direction == (int)Sdl.SDL_HAT_RIGHTUP) { t += Separator + Interface.GetInterfaceString("controls_assignment_joystick_hat_upright"); } else if (Interface.CurrentControls[Index].Direction == (int)Sdl.SDL_HAT_RIGHT) { t += Separator + Interface.GetInterfaceString("controls_assignment_joystick_hat_right"); } else if (Interface.CurrentControls[Index].Direction == (int)Sdl.SDL_HAT_RIGHTDOWN) { t += Separator + Interface.GetInterfaceString("controls_assignment_joystick_hat_downright"); } else if (Interface.CurrentControls[Index].Direction == (int)Sdl.SDL_HAT_DOWN) { t += Separator + Interface.GetInterfaceString("controls_assignment_joystick_hat_down"); } else if (Interface.CurrentControls[Index].Direction == (int)Sdl.SDL_HAT_LEFTDOWN) { t += Separator + Interface.GetInterfaceString("controls_assignment_joystick_hat_downleft"); } else { t += Separator + Interface.GetInterfaceString("controls_assignment_joystick_hat_invalid"); } break; default: break; } return(t); } else { return(Interface.GetInterfaceString("controls_assignment_invalid")); } }
internal void LoadCalibration(string calibrationFile) { if (!File.Exists(calibrationFile)) { return; } try { for (int i = 0; i < Calibration.Length; i++) { Calibration[i] = new AxisCalibration(); } XmlDocument currentXML = new XmlDocument(); currentXML.Load(calibrationFile); XmlNodeList documentNodes = currentXML.SelectNodes("openBVE/RailDriverCalibration"); if (documentNodes != null && documentNodes.Count != 0) { for (int i = 0; i < documentNodes.Count; i++) { int idx = -1; int lMin = 0; int lMax = 255; foreach (XmlNode node in documentNodes[i].ChildNodes) { switch (node.Name.ToLowerInvariant()) { case "axis": foreach (XmlNode n in node.ChildNodes) { switch (n.Name.ToLowerInvariant()) { case "index": if (!NumberFormats.TryParseIntVb6(n.InnerText, out idx)) { Program.AppendToLogFile(@"Invalid index in RailDriver calibration file"); } break; case "minimum": if (!NumberFormats.TryParseIntVb6(n.InnerText, out lMin)) { Program.AppendToLogFile(@"Invalid minimum in RailDriver calibration file"); } break; case "maximum": if (!NumberFormats.TryParseIntVb6(n.InnerText, out lMax)) { Program.AppendToLogFile(@"Invalid minimum in RailDriver calibration file"); } break; } } lMin = Math.Abs(lMin); lMax = Math.Abs(lMax); if (lMin > 255) { lMin = 255; } else if (lMin < 0) { lMin = 0; } if (lMax >= 255) { lMax = 255; } else if (lMax < 0) { lMax = 0; } if (lMin >= lMax) { throw new InvalidDataException(@"Maximum must be non-zero and greater than minimum."); } if (idx == -1) { throw new InvalidDataException(@"Invalid axis specified."); } Calibration[idx].Minimum = lMin; Calibration[idx].Maximum = lMax; break; } } } } } catch { for (int i = 0; i < Calibration.Length; i++) { Calibration[i] = new AxisCalibration(); } MessageBox.Show(Interface.GetInterfaceString("raildriver_config_error"), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand); //Clear the calibration file File.Delete(calibrationFile); } }
/// <summary>Attempts to load and parse the current train's panel configuration file.</summary> /// <param name="TrainPath">The absolute on-disk path to the train folder.</param> /// <param name="Encoding">The automatically detected or manually set encoding of the panel configuration file.</param> /// <param name="Train">The base train on which to apply the panel configuration.</param> internal static void ParsePanelConfig(string TrainPath, System.Text.Encoding Encoding, TrainManager.Train Train) { string File = OpenBveApi.Path.CombineFile(TrainPath, "panel.animated"); if (System.IO.File.Exists(File)) { Program.AppendToLogFile("Loading train panel: " + File); ObjectManager.AnimatedObjectCollection a = AnimatedObjectParser.ReadObject(File, Encoding, ObjectManager.ObjectLoadMode.DontAllowUnloadOfTextures); try { for (int i = 0; i < a.Objects.Length; i++) { a.Objects[i].ObjectIndex = ObjectManager.CreateDynamicObject(); } Train.Cars[Train.DriverCar].CarSections[0].Elements = a.Objects; Train.Cars[Train.DriverCar].CameraRestrictionMode = World.CameraRestrictionMode.NotAvailable; World.CameraRestriction = World.CameraRestrictionMode.NotAvailable; World.UpdateViewingDistances(); } catch { var currentError = Interface.GetInterfaceString("error_critical_file"); currentError = currentError.Replace("[file]", "panel.animated"); MessageBox.Show(currentError, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand); Program.RestartArguments = " "; Loading.Cancel = true; } } else { var Panel2 = false; try { File = OpenBveApi.Path.CombineFile(TrainPath, "panel2.cfg"); if (System.IO.File.Exists(File)) { Program.AppendToLogFile("Loading train panel: " + File); Panel2 = true; Panel2CfgParser.ParsePanel2Config("panel2.cfg", TrainPath, Encoding, Train, Train.DriverCar); Train.Cars[Train.DriverCar].CameraRestrictionMode = World.CameraRestrictionMode.On; World.CameraRestriction = World.CameraRestrictionMode.On; } else { File = OpenBveApi.Path.CombineFile(TrainPath, "panel.cfg"); if (System.IO.File.Exists(File)) { Program.AppendToLogFile("Loading train panel: " + File); PanelCfgParser.ParsePanelConfig(TrainPath, Encoding, Train); Train.Cars[Train.DriverCar].CameraRestrictionMode = World.CameraRestrictionMode.On; World.CameraRestriction = World.CameraRestrictionMode.On; } else { World.CameraRestriction = World.CameraRestrictionMode.NotAvailable; } } } catch { var currentError = Interface.GetInterfaceString("errors_critical_file"); currentError = currentError.Replace("[file]", Panel2 == true ? "panel2.cfg" : "panel.cfg"); MessageBox.Show(currentError, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand); Program.RestartArguments = " "; Loading.Cancel = true; } } }
/// <summary>This method is called once the route and train data have been preprocessed, in order to physically setup the simulation</summary> private void SetupSimulation() { if (Loading.Cancel) { Close(); } Timetable.CreateTimetable(); //Check if any critical errors have occured during the route or train loading for (int i = 0; i < Interface.MessageCount; i++) { if (Interface.Messages[i].Type == Interface.MessageType.Critical) { MessageBox.Show("A critical error has occured:\n\n" + Interface.Messages[i].Text + "\n\nPlease inspect the error log file for further information.", "Load", MessageBoxButtons.OK, MessageBoxIcon.Hand); Close(); } } Renderer.InitializeLighting(); Game.LogRouteName = System.IO.Path.GetFileName(MainLoop.currentResult.RouteFile); Game.LogTrainName = System.IO.Path.GetFileName(MainLoop.currentResult.TrainFolder); Game.LogDateTime = DateTime.Now; if (Interface.CurrentOptions.LoadInAdvance) { Textures.LoadAllTextures(); } else { Textures.UnloadAllTextures(); } // camera ObjectManager.InitializeVisibility(); World.CameraTrackFollower.Update(0.0, true, false); World.CameraTrackFollower.Update(-0.1, true, false); World.CameraTrackFollower.Update(0.1, true, false); World.CameraTrackFollower.TriggerType = TrackManager.EventTriggerType.Camera; // starting time and track position Game.SecondsSinceMidnight = 0.0; Game.StartupTime = 0.0; int PlayerFirstStationIndex = -1; double PlayerFirstStationPosition; int os = -1; bool f = false; for (int i = 0; i < Game.Stations.Length; i++) { if (!String.IsNullOrEmpty(Game.InitialStationName)) { if (Game.InitialStationName.ToLowerInvariant() == Game.Stations[i].Name.ToLowerInvariant()) { PlayerFirstStationIndex = i; } } if (Game.Stations[i].StopMode == StationStopMode.AllStop | Game.Stations[i].StopMode == StationStopMode.PlayerStop & Game.Stations[i].Stops.Length != 0) { if (f == false) { os = i; f = true; } } } if (PlayerFirstStationIndex == -1) { PlayerFirstStationIndex = os; } { int s = Game.GetStopIndex(PlayerFirstStationIndex, TrainManager.PlayerTrain.Cars.Length); if (s >= 0) { PlayerFirstStationPosition = Game.Stations[PlayerFirstStationIndex].Stops[s].TrackPosition; double TrainLength = 0.0; for (int c = 0; c < TrainManager.Trains[TrainManager.PlayerTrain.TrainIndex].Cars.Length; c++) { TrainLength += TrainManager.Trains[TrainManager.PlayerTrain.TrainIndex].Cars[c].Length; } for (int j = 0; j < Game.BufferTrackPositions.Length; j++) { if (PlayerFirstStationPosition > Game.BufferTrackPositions[j] && PlayerFirstStationPosition - TrainLength < Game.BufferTrackPositions[j]) { /* * HACK: The initial start position for the player train is stuck on a set of buffers * This means we have to make some one the fly adjustments to the first station stop position */ //Set the start position to be the buffer position plus the train length plus 1m PlayerFirstStationPosition = Game.BufferTrackPositions[j] + TrainLength + 1; //Update the station stop location if (s >= 0) { Game.Stations[PlayerFirstStationIndex].Stops[s].TrackPosition = PlayerFirstStationPosition; } else { Game.Stations[PlayerFirstStationIndex].DefaultTrackPosition = PlayerFirstStationPosition; } break; } } } else { PlayerFirstStationPosition = Game.Stations[PlayerFirstStationIndex].DefaultTrackPosition; } if (Game.InitialStationTime != -1) { Game.SecondsSinceMidnight = Game.InitialStationTime; Game.StartupTime = Game.InitialStationTime; } else { if (Game.Stations[PlayerFirstStationIndex].ArrivalTime < 0.0) { if (Game.Stations[PlayerFirstStationIndex].DepartureTime < 0.0) { Game.SecondsSinceMidnight = 0.0; Game.StartupTime = 0.0; } else { Game.SecondsSinceMidnight = Game.Stations[PlayerFirstStationIndex].DepartureTime - Game.Stations[PlayerFirstStationIndex].StopTime; Game.StartupTime = Game.Stations[PlayerFirstStationIndex].DepartureTime - Game.Stations[PlayerFirstStationIndex].StopTime; } } else { Game.SecondsSinceMidnight = Game.Stations[PlayerFirstStationIndex].ArrivalTime; Game.StartupTime = Game.Stations[PlayerFirstStationIndex].ArrivalTime; } } } int OtherFirstStationIndex = -1; double OtherFirstStationPosition = 0.0; double OtherFirstStationTime = 0.0; for (int i = 0; i < Game.Stations.Length; i++) { if (Game.Stations[i].StopMode == StationStopMode.AllStop | Game.Stations[i].StopMode == StationStopMode.PlayerPass & Game.Stations[i].Stops.Length != 0) { OtherFirstStationIndex = i; int s = Game.GetStopIndex(i, TrainManager.PlayerTrain.Cars.Length); if (s >= 0) { OtherFirstStationPosition = Game.Stations[i].Stops[s].TrackPosition; } else { OtherFirstStationPosition = Game.Stations[i].DefaultTrackPosition; } if (Game.Stations[i].ArrivalTime < 0.0) { if (Game.Stations[i].DepartureTime < 0.0) { OtherFirstStationTime = 0.0; } else { OtherFirstStationTime = Game.Stations[i].DepartureTime - Game.Stations[i].StopTime; } } else { OtherFirstStationTime = Game.Stations[i].ArrivalTime; } break; } } if (Game.PrecedingTrainTimeDeltas.Length != 0) { OtherFirstStationTime -= Game.PrecedingTrainTimeDeltas[Game.PrecedingTrainTimeDeltas.Length - 1]; if (OtherFirstStationTime < Game.SecondsSinceMidnight) { Game.SecondsSinceMidnight = OtherFirstStationTime; } } // initialize trains for (int i = 0; i < TrainManager.Trains.Length; i++) { TrainManager.Trains[i].Initialize(); int s = i == TrainManager.PlayerTrain.TrainIndex ? PlayerFirstStationIndex : OtherFirstStationIndex; if (s >= 0) { if (Game.Stations[s].OpenLeftDoors) { for (int j = 0; j < TrainManager.Trains[i].Cars.Length; j++) { TrainManager.Trains[i].Cars[j].Doors[0].AnticipatedOpen = true; } } if (Game.Stations[s].OpenRightDoors) { for (int j = 0; j < TrainManager.Trains[i].Cars.Length; j++) { TrainManager.Trains[i].Cars[j].Doors[1].AnticipatedOpen = true; } } } if (Game.Sections.Length != 0) { Game.Sections[0].Enter(TrainManager.Trains[i]); } for (int j = 0; j < TrainManager.Trains[i].Cars.Length; j++) { double length = TrainManager.Trains[i].Cars[0].Length; TrainManager.Trains[i].Cars[j].Move(-length, 0.01); TrainManager.Trains[i].Cars[j].Move(length, 0.01); } } // score Game.CurrentScore.ArrivalStation = PlayerFirstStationIndex + 1; Game.CurrentScore.DepartureStation = PlayerFirstStationIndex; Game.CurrentScore.Maximum = 0; for (int i = 0; i < Game.Stations.Length; i++) { if (i != PlayerFirstStationIndex & Game.PlayerStopsAtStation(i)) { if (i == 0 || Game.Stations[i - 1].Type != StationType.ChangeEnds) { Game.CurrentScore.Maximum += Game.ScoreValueStationArrival; } } } if (Game.CurrentScore.Maximum <= 0) { Game.CurrentScore.Maximum = Game.ScoreValueStationArrival; } // signals if (Game.Sections.Length > 0) { Game.UpdateSection(Game.Sections.Length - 1); } // move train in position for (int i = 0; i < TrainManager.Trains.Length; i++) { double p; if (i == TrainManager.PlayerTrain.TrainIndex) { p = PlayerFirstStationPosition; } else if (TrainManager.Trains[i].State == TrainManager.TrainState.Bogus) { p = Game.BogusPretrainInstructions[0].TrackPosition; TrainManager.Trains[i].AI = new Game.BogusPretrainAI(TrainManager.Trains[i]); } else { p = OtherFirstStationPosition; } for (int j = 0; j < TrainManager.Trains[i].Cars.Length; j++) { TrainManager.Trains[i].Cars[j].Move(p, 0.01); } } // timetable if (Timetable.DefaultTimetableDescription.Length == 0) { Timetable.DefaultTimetableDescription = Game.LogTrainName; } // initialize camera if (World.CameraRestriction == World.CameraRestrictionMode.NotAvailable) { World.CameraMode = World.CameraViewMode.InteriorLookAhead; } //Place the initial camera in the driver car TrainManager.PlayerTrain.Cars[TrainManager.PlayerTrain.DriverCar].UpdateCamera(); World.CameraTrackFollower.Update(-1.0, true, false); ObjectManager.UpdateVisibility(World.CameraTrackFollower.TrackPosition + World.CameraCurrentAlignment.Position.Z); World.CameraSavedExterior = new World.CameraAlignment(new OpenBveApi.Math.Vector3(-2.5, 1.5, -15.0), 0.3, -0.2, 0.0, PlayerFirstStationPosition, 1.0); World.CameraSavedTrack = new World.CameraAlignment(new OpenBveApi.Math.Vector3(-3.0, 2.5, 0.0), 0.3, 0.0, 0.0, TrainManager.PlayerTrain.Cars[0].FrontAxle.Follower.TrackPosition - 10.0, 1.0); // signalling sections for (int i = 0; i < TrainManager.Trains.Length; i++) { int s = TrainManager.Trains[i].CurrentSectionIndex; Game.Sections[s].Enter(TrainManager.Trains[i]); } if (Game.Sections.Length > 0) { Game.UpdateSection(Game.Sections.Length - 1); } // fast-forward until start time { Game.MinimalisticSimulation = true; const double w = 0.25; double u = Game.StartupTime - Game.SecondsSinceMidnight; if (u > 0) { while (true) { double v = u < w ? u : w; u -= v; Game.SecondsSinceMidnight += v; TrainManager.UpdateTrains(v); if (u <= 0.0) { break; } TotalTimeElapsedForSectionUpdate += v; if (TotalTimeElapsedForSectionUpdate >= 1.0) { if (Game.Sections.Length > 0) { Game.UpdateSection(Game.Sections.Length - 1); } TotalTimeElapsedForSectionUpdate = 0.0; } } } Game.MinimalisticSimulation = false; } // animated objects ObjectManager.UpdateAnimatedWorldObjects(0.0, true); TrainManager.UpdateTrainObjects(0.0, true); //HACK: This function calls a single update on all objects attached to the player's train // but ignores any specified damping so that all needles etc. are in the correct place // for the first frame, rather than spinning wildly to get to the starting point. TrainManager.PlayerTrain.UpdateCabObjects(); // timetable if (TrainManager.PlayerTrain.Station >= 0) { Timetable.UpdateCustomTimetable(Game.Stations[TrainManager.PlayerTrain.Station].TimetableDaytimeTexture, Game.Stations[TrainManager.PlayerTrain.Station].TimetableNighttimeTexture); if (Timetable.CustomObjectsUsed != 0 & Timetable.CustomTimetableAvailable && Interface.CurrentOptions.TimeTableStyle != Interface.TimeTableMode.AutoGenerated && Interface.CurrentOptions.TimeTableStyle != Interface.TimeTableMode.None) { Timetable.CurrentTimetable = Timetable.TimetableState.Custom; } } //Create AI driver for the player train if specified via the commmand line if (Game.InitialAIDriver == true) { TrainManager.PlayerTrain.AI = new Game.SimpleHumanDriverAI(TrainManager.PlayerTrain); if (TrainManager.PlayerTrain.Plugin != null && !TrainManager.PlayerTrain.Plugin.SupportsAI) { Game.AddMessage(Interface.GetInterfaceString("notification_aiunable"), MessageManager.MessageDependency.None, Interface.GameMode.Expert, OpenBveApi.Colors.MessageColor.White, Game.SecondsSinceMidnight + 10.0, null); } } // warnings / errors if (Interface.MessageCount != 0) { int filesNotFound = 0; int errors = 0; int warnings = 0; for (int i = 0; i < Interface.MessageCount; i++) { if (Interface.Messages[i].FileNotFound) { filesNotFound++; } else if (Interface.Messages[i].Type == Interface.MessageType.Error) { errors++; } else if (Interface.Messages[i].Type == Interface.MessageType.Warning) { warnings++; } } string NotFound = null; string Messages = null; if (filesNotFound != 0) { NotFound = filesNotFound.ToString() + " file(s) not found"; Game.AddMessage(NotFound, MessageManager.MessageDependency.None, Interface.GameMode.Expert, MessageColor.Magenta, Game.SecondsSinceMidnight + 10.0, null); } if (errors != 0 & warnings != 0) { Messages = errors.ToString() + " error(s), " + warnings.ToString() + " warning(s)"; Game.AddMessage(Messages, MessageManager.MessageDependency.None, Interface.GameMode.Expert, MessageColor.Magenta, Game.SecondsSinceMidnight + 10.0, null); } else if (errors != 0) { Messages = errors.ToString() + " error(s)"; Game.AddMessage(Messages, MessageManager.MessageDependency.None, Interface.GameMode.Expert, MessageColor.Magenta, Game.SecondsSinceMidnight + 10.0, null); } else { Messages = warnings.ToString() + " warning(s)"; Game.AddMessage(Messages, MessageManager.MessageDependency.None, Interface.GameMode.Expert, MessageColor.Magenta, Game.SecondsSinceMidnight + 10.0, null); } Game.RouteInformation.FilesNotFound = NotFound; Game.RouteInformation.ErrorsAndWarnings = Messages; //Print the plugin error encountered (If any) for 10s //This must be done after the simulation has init, as otherwise the timeout doesn't work if (Loading.PluginError != null) { Game.AddMessage(Loading.PluginError, MessageManager.MessageDependency.None, Interface.GameMode.Expert, OpenBveApi.Colors.MessageColor.Red, Game.SecondsSinceMidnight + 5.0, null); Game.AddMessage(Interface.GetInterfaceString("errors_plugin_failure2"), MessageManager.MessageDependency.None, Interface.GameMode.Expert, OpenBveApi.Colors.MessageColor.Red, Game.SecondsSinceMidnight + 5.0, null); } } loadComplete = true; RenderRealTimeElapsed = 0.0; RenderTimeElapsed = 0.0; World.InitializeCameraRestriction(); Loading.SimulationSetup = true; switch (Game.InitialViewpoint) { case 1: //Switch camera to exterior MainLoop.SaveCameraSettings(); World.CameraMode = World.CameraViewMode.Exterior; MainLoop.RestoreCameraSettings(); for (int j = 0; j < TrainManager.PlayerTrain.Cars.Length; j++) { TrainManager.PlayerTrain.Cars[j].ChangeCarSection(TrainManager.CarSectionType.Exterior); } //Make bogies visible for (int j = 0; j < TrainManager.PlayerTrain.Cars.Length; j++) { TrainManager.PlayerTrain.Cars[j].FrontBogie.ChangeSection(0); TrainManager.PlayerTrain.Cars[j].RearBogie.ChangeSection(0); } World.CameraAlignmentDirection = new World.CameraAlignment(); World.CameraAlignmentSpeed = new World.CameraAlignment(); MainLoop.UpdateViewport(MainLoop.ViewPortChangeMode.NoChange); World.UpdateAbsoluteCamera(0.0); World.UpdateViewingDistances(); break; case 2: //Switch camera to track MainLoop.SaveCameraSettings(); World.CameraMode = World.CameraViewMode.Track; MainLoop.RestoreCameraSettings(); for (int j = 0; j < TrainManager.PlayerTrain.Cars.Length; j++) { TrainManager.PlayerTrain.Cars[j].ChangeCarSection(TrainManager.CarSectionType.Exterior); } for (int j = 0; j < TrainManager.PlayerTrain.Cars.Length; j++) { TrainManager.PlayerTrain.Cars[j].FrontBogie.ChangeSection(0); TrainManager.PlayerTrain.Cars[j].RearBogie.ChangeSection(0); } World.CameraAlignmentDirection = new World.CameraAlignment(); World.CameraAlignmentSpeed = new World.CameraAlignment(); MainLoop.UpdateViewport(MainLoop.ViewPortChangeMode.NoChange); World.UpdateAbsoluteCamera(0.0); World.UpdateViewingDistances(); break; case 3: //Switch camera to flyby MainLoop.SaveCameraSettings(); World.CameraMode = World.CameraViewMode.FlyBy; MainLoop.RestoreCameraSettings(); for (int j = 0; j < TrainManager.PlayerTrain.Cars.Length; j++) { TrainManager.PlayerTrain.Cars[j].ChangeCarSection(TrainManager.CarSectionType.Exterior); } for (int j = 0; j < TrainManager.PlayerTrain.Cars.Length; j++) { TrainManager.PlayerTrain.Cars[j].FrontBogie.ChangeSection(0); TrainManager.PlayerTrain.Cars[j].RearBogie.ChangeSection(0); } World.CameraAlignmentDirection = new World.CameraAlignment(); World.CameraAlignmentSpeed = new World.CameraAlignment(); MainLoop.UpdateViewport(MainLoop.ViewPortChangeMode.NoChange); World.UpdateAbsoluteCamera(0.0); World.UpdateViewingDistances(); break; case 4: //Switch camera to flyby MainLoop.SaveCameraSettings(); World.CameraMode = World.CameraViewMode.FlyByZooming; MainLoop.RestoreCameraSettings(); for (int j = 0; j < TrainManager.PlayerTrain.Cars.Length; j++) { TrainManager.PlayerTrain.Cars[j].ChangeCarSection(TrainManager.CarSectionType.Exterior); } for (int j = 0; j < TrainManager.PlayerTrain.Cars.Length; j++) { TrainManager.PlayerTrain.Cars[j].FrontBogie.ChangeSection(0); TrainManager.PlayerTrain.Cars[j].RearBogie.ChangeSection(0); } World.CameraAlignmentDirection = new World.CameraAlignment(); World.CameraAlignmentSpeed = new World.CameraAlignment(); MainLoop.UpdateViewport(MainLoop.ViewPortChangeMode.NoChange); World.UpdateAbsoluteCamera(0.0); World.UpdateViewingDistances(); break; } }
//We need to explicitly specify the default constructor public OpenBVEGame(int width, int height, GraphicsMode currentGraphicsMode, GameWindowFlags @default) : base(width, height, currentGraphicsMode, Interface.GetInterfaceString("program_title"), @default) { try { var assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); System.Drawing.Icon ico = new System.Drawing.Icon(OpenBveApi.Path.CombineFile(OpenBveApi.Path.CombineDirectory(assemblyFolder, "Data"), "icon.ico")); this.Icon = ico; } catch { } }
internal override void Trigger(int Direction, EventTriggerType TriggerType, TrainManager.Train Train, int CarIndex) { if (Direction < 0) { if (TriggerType == EventTriggerType.FrontCarFrontAxle) { int n = Train.RouteLimits.Length; if (n > 0) { Array.Resize <double>(ref Train.RouteLimits, n - 1); Train.CurrentRouteLimit = double.PositiveInfinity; for (int i = 0; i < n - 1; i++) { if (Train.RouteLimits[i] < Train.CurrentRouteLimit) { Train.CurrentRouteLimit = Train.RouteLimits[i]; } } } } else if (TriggerType == EventTriggerType.RearCarRearAxle) { int n = Train.RouteLimits.Length; Array.Resize <double>(ref Train.RouteLimits, n + 1); for (int i = n; i > 0; i--) { Train.RouteLimits[i] = Train.RouteLimits[i - 1]; } Train.RouteLimits[0] = this.PreviousSpeedLimit; } } else if (Direction > 0) { if (TriggerType == EventTriggerType.FrontCarFrontAxle) { int n = Train.RouteLimits.Length; Array.Resize <double>(ref Train.RouteLimits, n + 1); Train.RouteLimits[n] = this.NextSpeedLimit; if (this.NextSpeedLimit < Train.CurrentRouteLimit) { Train.CurrentRouteLimit = this.NextSpeedLimit; } if (Train.Specs.CurrentAverageSpeed > this.NextSpeedLimit) { Game.AddMessage(Interface.GetInterfaceString("message_route_overspeed"), MessageManager.MessageDependency.RouteLimit, Interface.GameMode.Normal, MessageColor.Orange, double.PositiveInfinity, null); } } else if (TriggerType == EventTriggerType.RearCarRearAxle) { int n = Train.RouteLimits.Length; if (n > 0) { Train.CurrentRouteLimit = double.PositiveInfinity; for (int i = 0; i < n - 1; i++) { Train.RouteLimits[i] = Train.RouteLimits[i + 1]; if (Train.RouteLimits[i] < Train.CurrentRouteLimit) { Train.CurrentRouteLimit = Train.RouteLimits[i]; } } Array.Resize <double>(ref Train.RouteLimits, n - 1); } } } }
// show default train private void ShowDefaultTrain() { if (string.IsNullOrEmpty(Result.RouteFile)) { return; } if (string.IsNullOrEmpty(Game.TrainName)) { return; } string Folder; try { Folder = System.IO.Path.GetDirectoryName(Result.RouteFile); if (Game.TrainName[0] == '$') { Folder = OpenBveApi.Path.CombineDirectory(Folder, Game.TrainName); if (System.IO.Directory.Exists(Folder)) { string File = OpenBveApi.Path.CombineFile(Folder, "train.dat"); if (System.IO.File.Exists(File)) { Result.TrainFolder = Folder; ShowTrain(false); return; } } } } catch { Folder = null; } try { while (true) { string TrainFolder = OpenBveApi.Path.CombineDirectory(Folder, "Train"); if (System.IO.Directory.Exists(TrainFolder)) { try { Folder = OpenBveApi.Path.CombineDirectory(TrainFolder, Game.TrainName); } catch { Folder = null; } if (Folder != null && System.IO.Directory.Exists(Folder)) { string File = OpenBveApi.Path.CombineFile(Folder, "train.dat"); if (System.IO.File.Exists(File)) { // train found Result.TrainFolder = Folder; ShowTrain(false); return; } } break; } if (Folder == null) { continue; } System.IO.DirectoryInfo Info = System.IO.Directory.GetParent(Folder); if (Info != null) { Folder = Info.FullName; } else { break; } } } catch { } // train not found Result.TrainFolder = null; TryLoadImage(pictureboxTrainImage, "train_error.png"); textboxTrainDescription.Text = Interface.ConvertNewlinesToCrLf(Interface.GetInterfaceString("start_train_notfound") + Game.TrainName); comboboxTrainEncoding.Tag = new object(); comboboxTrainEncoding.SelectedIndex = 0; comboboxTrainEncoding.Tag = null; labelTrainEncoding.Enabled = false; panelTrainEncoding.Enabled = false; labelTrainEncodingPreview.Enabled = false; textboxTrainEncodingPreview.Enabled = false; textboxTrainEncodingPreview.Text = ""; groupboxTrainDetails.Visible = true; }
// update private void timerUpdate_Tick(object sender, EventArgs e) { { int a = (int)Math.Floor(100.0 * Loading.RouteProgress); if (a < 0) { a = 0; } else if (a > 100) { a = 100; } labelRoutePercentage.Text = a.ToString(System.Globalization.CultureInfo.InvariantCulture) + "%"; progressbarRoute.Value = a; } { int a = (int)Math.Floor(100.0 * Loading.TrainProgress); if (a < 0) { a = 0; } else if (a > 100) { a = 100; } labelTrainPercentage.Text = a.ToString(System.Globalization.CultureInfo.InvariantCulture) + "%"; progressbarTrain.Value = a; } if (Loading.Complete) { timerUpdate.Enabled = false; AllowClosing = true; bool critical = false; if (QueryCancel) { this.DialogResult = DialogResult.Cancel; } else if (Interface.MessageCount == 0) { this.DialogResult = DialogResult.OK; } else { int errors = 0; for (int i = 0; i < Interface.MessageCount; i++) { if (Interface.Messages[i].FileNotFound) { errors++; } if (Interface.Messages[i].Type == Interface.MessageType.Critical) { critical = true; } } if (errors == 0) { labelFilesNotFoundCaption.Visible = false; labelFilesNotFoundValue.Visible = false; labelHelp.Text = Interface.GetInterfaceString("loading_almost_help_general"); } else { labelFilesNotFoundValue.Text = errors.ToString(System.Globalization.CultureInfo.InvariantCulture); labelHelp.Text = Interface.GetInterfaceString("loading_almost_help_filesnotfound"); } panelAlmost.Visible = true; panelLoading.Visible = false; if (critical) { ShowMessages(); buttonSave.Visible = true; panelProblems.Visible = true; buttonIgnore.Visible = false; panelAlmost.Visible = false; } else { buttonIgnore.Visible = true; buttonIgnore.BringToFront(); buttonIgnore.Focus(); } } } }
// show route private void ShowRoute(bool UserSelectedEncoding) { if (Result.RouteFile != null && !routeWorkerThread.IsBusy) { this.Cursor = Cursors.WaitCursor; TryLoadImage(pictureboxRouteImage, "loading.png"); groupboxRouteDetails.Visible = true; textboxRouteDescription.Text = Interface.GetInterfaceString("start_route_processing"); // determine encoding if (!UserSelectedEncoding) { comboboxRouteEncoding.Tag = new object(); comboboxRouteEncoding.SelectedIndex = 0; comboboxRouteEncoding.Items[0] = "(UTF-8)"; comboboxRouteEncoding.Tag = null; Result.RouteEncoding = System.Text.Encoding.UTF8; switch (Interface.GetEncodingFromFile(Result.RouteFile)) { case Interface.Encoding.Utf7: panelRouteEncoding.Enabled = false; comboboxRouteEncoding.SelectedIndex = 0; comboboxRouteEncoding.Items[0] = "(UTF-7)"; Result.RouteEncoding = System.Text.Encoding.UTF7; break; case Interface.Encoding.Utf8: panelRouteEncoding.Enabled = false; comboboxRouteEncoding.SelectedIndex = 0; comboboxRouteEncoding.Items[0] = "(UTF-8)"; Result.RouteEncoding = System.Text.Encoding.UTF8; break; case Interface.Encoding.Utf16Le: panelRouteEncoding.Enabled = false; comboboxRouteEncoding.SelectedIndex = 0; comboboxRouteEncoding.Items[0] = "(UTF-16 little endian)"; Result.RouteEncoding = System.Text.Encoding.Unicode; break; case Interface.Encoding.Utf16Be: panelRouteEncoding.Enabled = false; comboboxRouteEncoding.SelectedIndex = 0; comboboxRouteEncoding.Items[0] = "(UTF-16 big endian)"; Result.RouteEncoding = System.Text.Encoding.BigEndianUnicode; break; case Interface.Encoding.Utf32Le: panelRouteEncoding.Enabled = false; comboboxRouteEncoding.SelectedIndex = 0; comboboxRouteEncoding.Items[0] = "(UTF-32 little endian)"; Result.RouteEncoding = System.Text.Encoding.UTF32; break; case Interface.Encoding.Utf32Be: panelRouteEncoding.Enabled = false; comboboxRouteEncoding.SelectedIndex = 0; comboboxRouteEncoding.Items[0] = "(UTF-32 big endian)"; Result.RouteEncoding = System.Text.Encoding.GetEncoding(12001); break; } panelRouteEncoding.Enabled = true; comboboxRouteEncoding.Tag = new object(); int i; for (i = 0; i < Interface.CurrentOptions.RouteEncodings.Length; i++) { if (Interface.CurrentOptions.RouteEncodings[i].Value == Result.RouteFile) { int j; for (j = 1; j < EncodingCodepages.Length; j++) { if (EncodingCodepages[j] == Interface.CurrentOptions.RouteEncodings[i].Codepage) { comboboxRouteEncoding.SelectedIndex = j; Result.RouteEncoding = System.Text.Encoding.GetEncoding(EncodingCodepages[j]); break; } } if (j == EncodingCodepages.Length) { comboboxRouteEncoding.SelectedIndex = 0; Result.RouteEncoding = System.Text.Encoding.UTF8; } break; } } comboboxRouteEncoding.Tag = null; } routeWorkerThread.RunWorkerAsync(); } }