Exemple #1
0
        /// <summary>Loads the specified route.</summary>
        /// <param name="path">The path to the file or folder that contains the route.</param>
        /// <param name="Encoding">The user-selected encoding (if appropriate)</param>
        /// <param name="trainPath">The path to the selected train</param>
        /// <param name="objectPath">The base object folder path</param>
        /// <param name="soundPath">The base sound folder path</param>
        /// <param name="PreviewOnly">Whether this is a preview</param>
        /// <param name="route">Receives the route.</param>
        /// <returns>Whether loading the sound was successful.</returns>
        public override bool LoadRoute(string path, Encoding Encoding, string trainPath, string objectPath, string soundPath, bool PreviewOnly, ref object route)
        {
            if (Encoding == null)
            {
                Encoding = Encoding.UTF8;
            }
            LastException   = null;
            Cancel          = false;
            CurrentProgress = 0.0;
            IsLoading       = true;
            FileSystem.AppendToLogFile("Loading route file: " + path);
            FileSystem.AppendToLogFile("INFO: Route file hash " + Path.GetChecksum(path));
            CurrentRoute = (CurrentRoute)route;
            //First, check the format of the route file
            //RW routes were written for BVE1 / 2, and have a different command syntax
            bool isRw = path.ToLowerInvariant().EndsWith(".rw");

            FileSystem.AppendToLogFile("Route file format is: " + (isRw ? "RW" : "CSV"));
            try
            {
                Parser parser = new Parser();
                parser.ParseRoute(path, isRw, Encoding, trainPath, objectPath, soundPath, PreviewOnly, this);
                IsLoading = false;
                return(true);
            }
            catch (Exception ex)
            {
                route = null;
                CurrentHost.AddMessage(MessageType.Error, false, "An unexpected error occured whilst attempting to load the following routefile: " + path);
                IsLoading     = false;
                LastException = ex;
                return(false);
            }
        }
Exemple #2
0
 public BackgroundChangeEvent(CurrentRoute CurrentRoute, double TrackPositionDelta, BackgroundHandle PreviousBackground, BackgroundHandle NextBackground) : base(TrackPositionDelta)
 {
     currentRoute       = CurrentRoute;
     DontTriggerAnymore = false;
     previousBackground = PreviousBackground;
     nextBackground     = NextBackground;
 }
Exemple #3
0
 public StationEndEvent(HostInterface Host, CurrentRoute CurrentRoute, double TrackPositionDelta, int StationIndex) : base(TrackPositionDelta)
 {
     currentHost        = Host;
     currentRoute       = CurrentRoute;
     DontTriggerAnymore = false;
     this.StationIndex  = StationIndex;
 }
Exemple #4
0
 /// <summary>Loads the specified route.</summary>
 /// <param name="path">The path to the file or folder that contains the route.</param>
 /// <param name="Encoding">The user-selected encoding (if appropriate)</param>
 /// <param name="trainPath">The path to the selected train</param>
 /// <param name="objectPath">The base object folder path</param>
 /// <param name="soundPath">The base sound folder path</param>
 /// <param name="PreviewOnly">Whether this is a preview</param>
 /// <param name="route">Receives the route.</param>
 /// <returns>Whether loading the sound was successful.</returns>
 public override bool LoadRoute(string path, System.Text.Encoding Encoding, string trainPath, string objectPath, string soundPath, bool PreviewOnly, ref object route)
 {
     LastException   = null;
     Cancel          = false;
     CurrentProgress = 0.0;
     IsLoading       = true;
     FileSystem.AppendToLogFile("Loading route file: " + path);
     CurrentRoute          = (CurrentRoute)route;
     CurrentRoute.Stations = new RouteStation[] { };
     FileSystem.AppendToLogFile("Route file format is: Mechanik");
     try
     {
         Parser parser = new Parser();
         parser.ParseRoute(path, PreviewOnly);
         if (PreviewOnly && CurrentRoute.Stations.Length == 0)
         {
             route = null;
             CurrentHost.AddMessage(MessageType.Error, false, "No stations were found in the following Mechanik routefile: " + path + Environment.NewLine + Environment.NewLine + "This is most likely a module file.");
             IsLoading = false;
             return(false);
         }
         IsLoading = false;
         return(true);
     }
     catch (Exception ex)
     {
         route = null;
         CurrentHost.AddMessage(MessageType.Error, false, "An unexpected error occured whilst attempting to load the following Mechanik routefile: " + path);
         IsLoading     = false;
         LastException = ex;
         return(false);
     }
 }
Exemple #5
0
        public SectionChangeEvent(CurrentRoute CurrentRoute, double TrackPositionDelta, int PreviousSectionIndex, int NextSectionIndex) : base(TrackPositionDelta)
        {
            currentRoute = CurrentRoute;

            DontTriggerAnymore        = false;
            this.PreviousSectionIndex = PreviousSectionIndex;
            this.NextSectionIndex     = NextSectionIndex;
        }
Exemple #6
0
 public StationEndEvent(double TrackPositionDelta, int StationIndex, CurrentRoute Route, HostInterface Host)
 {
     this.TrackPositionDelta = TrackPositionDelta;
     this.DontTriggerAnymore = false;
     this.StationIndex       = StationIndex;
     this.Route       = Route;
     this.currentHost = Host;
 }
Exemple #7
0
        public FogChangeEvent(CurrentRoute CurrentRoute, double TrackPositionDelta, Fog PreviousFog, Fog CurrentFog, Fog NextFog) : base(TrackPositionDelta)
        {
            currentRoute = CurrentRoute;

            DontTriggerAnymore = false;
            this.PreviousFog   = PreviousFog;
            this.CurrentFog    = CurrentFog;
            this.NextFog       = NextFog;
        }
Exemple #8
0
        public TransponderEvent(CurrentRoute CurrentRoute, double TrackPositionDelta, int Type, int Data, int SectionIndex, bool ClipToFirstRedSection) : base(TrackPositionDelta)
        {
            currentRoute = CurrentRoute;

            DontTriggerAnymore         = false;
            this.Type                  = Type;
            this.Data                  = Data;
            this.SectionIndex          = SectionIndex;
            this.ClipToFirstRedSection = ClipToFirstRedSection;
        }
Exemple #9
0
        internal void Create(CurrentRoute CurrentRoute, Block[] Blocks, int CurrentBlock, int CurrentTrackElement, double[] SignalSpeeds, double StartingDistance, double BlockInterval)
        {
            int m = CurrentRoute.Sections.Length;

            Array.Resize(ref CurrentRoute.Sections, m + 1);
            // create associated transponders
            for (int g = 0; g <= CurrentBlock; g++)
            {
                for (int l = 0; l < Blocks[g].Transponders.Length; l++)
                {
                    if (Blocks[g].Transponders[l].Type != -1 & Blocks[g].Transponders[l].SectionIndex == m)
                    {
                        int o = CurrentRoute.Tracks[0].Elements[CurrentTrackElement - CurrentBlock + g].Events.Length;
                        Array.Resize(ref CurrentRoute.Tracks[0].Elements[CurrentTrackElement - CurrentBlock + g].Events, o + 1);
                        double dt = Blocks[g].Transponders[l].TrackPosition - StartingDistance + (CurrentBlock - g) * BlockInterval;
                        CurrentRoute.Tracks[0].Elements[CurrentTrackElement - CurrentBlock + g].Events[o] = new TransponderEvent(CurrentRoute, dt, Blocks[g].Transponders[l].Type, Blocks[g].Transponders[l].Data, m, Blocks[g].Transponders[l].ClipToFirstRedSection);
                        Blocks[g].Transponders[l].Type = -1;
                    }
                }
            }

            // create section
            SectionAspect[] newAspects = new SectionAspect[Aspects.Length];
            for (int l = 0; l < Aspects.Length; l++)
            {
                newAspects[l].Number = Aspects[l];
                if (Aspects[l] >= 0 & Aspects[l] < SignalSpeeds.Length)
                {
                    newAspects[l].Speed = SignalSpeeds[Aspects[l]];
                }
                else
                {
                    newAspects[l].Speed = double.PositiveInfinity;
                }
            }

            if (m > 0)
            {
                CurrentRoute.Sections[m] = new RouteManager2.SignalManager.Section(TrackPosition, newAspects, Type, CurrentRoute.Sections[m - 1]);
                CurrentRoute.Sections[m - 1].NextSection = CurrentRoute.Sections[m];
            }
            else
            {
                CurrentRoute.Sections[m] = new RouteManager2.SignalManager.Section(TrackPosition, newAspects, Type);
            }

            CurrentRoute.Sections[m].StationIndex = DepartureStationIndex;
            CurrentRoute.Sections[m].Invisible    = Invisible;
            // create section change event
            double d = TrackPosition - StartingDistance;
            int    p = CurrentRoute.Tracks[0].Elements[CurrentTrackElement].Events.Length;

            Array.Resize(ref CurrentRoute.Tracks[0].Elements[CurrentTrackElement].Events, p + 1);
            CurrentRoute.Tracks[0].Elements[CurrentTrackElement].Events[p] = new SectionChangeEvent(CurrentRoute, d, m - 1, m);
        }
Exemple #10
0
        public RequestStopEvent(CurrentRoute CurrentRoute, int StationIndex, int MaxCars, bool FullSpeed, RequestStop OnTime, RequestStop Early, RequestStop Late)
        {
            currentRoute = CurrentRoute;

            fullSpeed    = FullSpeed;
            onTime       = OnTime;
            stationIndex = StationIndex;
            early        = Early;
            late         = Late;
            maxCars      = MaxCars;
        }
Exemple #11
0
        internal void Create(CurrentRoute CurrentRoute, double StartingDistance, int CurrentElement, ref int CurrentBrightnessElement, ref int CurrentBrightnessEvent, ref double CurrentBrightnessTrackPosition, ref float CurrentBrightnessValue)
        {
            for (int tt = 0; tt < CurrentRoute.Tracks.Count; tt++)
            {
                int t = CurrentRoute.Tracks.ElementAt(tt).Key;
                int m = CurrentRoute.Tracks[t].Elements[CurrentElement].Events.Length;
                Array.Resize(ref CurrentRoute.Tracks[t].Elements[CurrentElement].Events, m + 1);
                double d = TrackPosition - StartingDistance;
                CurrentRoute.Tracks[t].Elements[CurrentElement].Events[m] = new BrightnessChangeEvent(d, Value, CurrentBrightnessValue, TrackPosition - CurrentBrightnessTrackPosition);

                if (t == 0)
                {
                    if (CurrentBrightnessElement >= 0 & CurrentBrightnessEvent >= 0)
                    {
                        BrightnessChangeEvent bce = (BrightnessChangeEvent)CurrentRoute.Tracks[t].Elements[CurrentBrightnessElement].Events[CurrentBrightnessEvent];
                        bce.NextBrightness = Value;
                        bce.NextDistance   = TrackPosition - CurrentBrightnessTrackPosition;
                    }

                    CurrentBrightnessEvent = m;
                }
                else
                {
                    if (CurrentBrightnessElement >= 0 & CurrentBrightnessEvent >= 0)
                    {
                        for (int e = 0; e < CurrentRoute.Tracks[t].Elements[CurrentBrightnessElement].Events.Length; e++)
                        {
                            if (!(CurrentRoute.Tracks[t].Elements[CurrentBrightnessElement].Events[e] is BrightnessChangeEvent))
                            {
                                continue;
                            }
                            BrightnessChangeEvent bce = (BrightnessChangeEvent)CurrentRoute.Tracks[t].Elements[CurrentBrightnessElement].Events[e];
                            bce.NextBrightness = Value;
                            bce.NextDistance   = TrackPosition - CurrentBrightnessTrackPosition;
                        }
                    }
                }
            }
            CurrentBrightnessElement       = CurrentElement;
            CurrentBrightnessTrackPosition = TrackPosition;
            CurrentBrightnessValue         = Value;
        }
Exemple #12
0
 public LightingChangeEvent(CurrentRoute CurrentRoute, object PreviousLightDefinition, object NextLightDefinition)
 {
     currentRoute = CurrentRoute;
     if (PreviousLightDefinition is LightDefinition)
     {
         previousLightDefinition = (LightDefinition)PreviousLightDefinition;
     }
     else
     {
         previousLightDefinitions = (LightDefinition[])PreviousLightDefinition;
     }
     if (NextLightDefinition is LightDefinition)
     {
         nextLightDefinition = (LightDefinition)NextLightDefinition;
     }
     else
     {
         nextLightDefinitions = (LightDefinition[])NextLightDefinition;
     }
 }
Exemple #13
0
 private void OkCommandMethod()
 {
     if (CurrentRoute.Id == 0 || !CurrentRoute.Equals(CurrentDataBase.Routes.Find(CurrentRoute.Id)))
     {
         if (!String.IsNullOrEmpty(CurrentRoute.Name))
         {
             Int32 unixTimestamp = (Int32)(DateTime.Now.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
             CurrentRoute.AddingDate          = CurrentRoute.AddingDate == 0 ? unixTimestamp : CurrentRoute.AddingDate;
             CurrentAddRouteView.DialogResult = true;
         }
         else
         {
             MessageBox.Show("Введите имя маршрута!");
         }
     }
     else
     {
         CurrentAddRouteView.DialogResult = false;
     }
 }
Exemple #14
0
        // load route
        internal static bool LoadRoute()
        {
            CurrentStation = -1;
            Game.Reset();
            Renderer.UpdateViewport();
            bool result;

            try {
                Loading.Load(CurrentRouteFile, System.Text.Encoding.UTF8);
                result = true;
            } catch (Exception ex) {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                Game.Reset();
                CurrentRoute = null;
                result       = false;
            }
            Renderer.Lighting.Initialize();
            Renderer.InitializeVisibility();
            Renderer.TextureManager.UnloadAllTextures();
            return(result);
        }
Exemple #15
0
        private static void Main(string[] args)
        {
            // Add handler for UI thread exceptions
            Application.ThreadException += (CrashHandler.UIThreadException);

            // Force all WinForms errors to go through handler
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            // This handler is for catching non-UI thread exceptions
            AppDomain.CurrentDomain.UnhandledException += (CrashHandler.CurrentDomain_UnhandledException);


            //Determine the current CPU architecture-
            //ARM will generally only support OpenGL-ES
            PortableExecutableKinds peKind;

            typeof(object).Module.GetPEKind(out peKind, out CurrentCPUArchitecture);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            //--- determine the running environment ---
            //I wonder if disabling this hack will stop the craashing on Linux....
            CurrentlyRunningOnMono = Type.GetType("Mono.Runtime") != null;
            //Doesn't appear to, but Mono have fixed the button appearance bug
            CurrentlyRunningOnWindows = Environment.OSVersion.Platform == PlatformID.Win32S | Environment.OSVersion.Platform == PlatformID.Win32Windows | Environment.OSVersion.Platform == PlatformID.Win32NT;
            Joysticks   = new JoystickManager();
            CurrentHost = new Host();
            try {
                FileSystem = FileSystem.FromCommandLineArgs(args);
                FileSystem.CreateFileSystem();
            } catch (Exception ex) {
                MessageBox.Show(Translations.GetInterfaceString("errors_filesystem_invalid") + Environment.NewLine + Environment.NewLine + ex.Message, Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }

            Renderer     = new NewRenderer();
            Sounds       = new Sounds();
            CurrentRoute = new CurrentRoute(Renderer);

            //Platform specific startup checks
            if (CurrentlyRunningOnMono && !CurrentlyRunningOnWindows)
            {
                // --- Check if we're running as root, and prompt not to ---
                if (getuid() == 0)
                {
                    MessageBox.Show(
                        "You are currently running as the root user." + System.Environment.NewLine +
                        "This is a bad idea, please dont!", Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }

                if (File.Exists(@"/System/Library/CoreServices/SystemVersion.plist"))
                {
                    //Mono's platform detection doesn't reliably differentiate between OS-X and Unix
                    CurrentlyRunningOnMacOS = true;
                }
            }
            else
            {
                if (!System.IO.File.Exists(System.IO.Path.Combine(Environment.SystemDirectory, "OpenAL32.dll")))
                {
                    MessageBox.Show(
                        "OpenAL was not found on your system, and will now be installed." + System.Environment.NewLine + System.Environment.NewLine +
                        "Please follow the install prompts.", Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);

                    ProcessStartInfo info = new ProcessStartInfo(Path.Combine(FileSystem.DataFolder, "Dependencies\\Win32\\oalinst.exe"));
                    info.UseShellExecute = true;
                    if (Environment.OSVersion.Version.Major >= 6)
                    {
                        info.Verb = "runas";
                    }
                    try
                    {
                        Process p = Process.Start(info);
                        if (p != null)
                        {
                            p.WaitForExit();
                        }
                        else
                        {
                            //For unknown reasons, the process failed to trigger, but did not raise an exception itself
                            //Throw one
                            throw new Win32Exception();
                        }
                    }
                    catch (Win32Exception)
                    {
                        MessageBox.Show(
                            "An error occured during OpenAL installation....", Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
                }
            }


            // --- load options and controls ---
            Interface.LoadOptions();
            //Switch between SDL2 and native backends; use native backend by default
            var options = new ToolkitOptions();

            if (Interface.CurrentOptions.PreferNativeBackend)
            {
                options.Backend = PlatformBackend.PreferNative;
            }
            Toolkit.Init(options);
            // --- load language ---
            string folder = Program.FileSystem.GetDataFolder("Languages");

            Translations.LoadLanguageFiles(folder);

            folder = Program.FileSystem.GetDataFolder("Cursors");
            Cursors.LoadCursorImages(folder);

            Interface.LoadControls(null, out Interface.CurrentControls);
            folder = Program.FileSystem.GetDataFolder("Controls");
            string file = OpenBveApi.Path.CombineFile(folder, "Default keyboard assignment.controls");

            Interface.Control[] controls;
            Interface.LoadControls(file, out controls);
            Interface.AddControls(ref Interface.CurrentControls, controls);

            InputDevicePlugin.LoadPlugins(Program.FileSystem);

            // --- check the command-line arguments for route and train ---
            formMain.MainDialogResult result = new formMain.MainDialogResult();
            CommandLine.ParseArguments(args, ref result);
            // --- check whether route and train exist ---
            if (result.RouteFile != null)
            {
                if (!System.IO.File.Exists(result.RouteFile))
                {
                    result.RouteFile = null;
                }
            }
            if (result.TrainFolder != null)
            {
                if (!System.IO.Directory.Exists(result.TrainFolder))
                {
                    result.TrainFolder = null;
                }
            }
            // --- if a route was provided but no train, try to use the route default ---
            if (result.RouteFile != null & result.TrainFolder == null)
            {
                if (!Plugins.LoadPlugins())
                {
                    throw new Exception("Unable to load the required plugins- Please reinstall OpenBVE");
                }
                Game.Reset(false);
                bool loaded = false;
                for (int i = 0; i < Program.CurrentHost.Plugins.Length; i++)
                {
                    if (Program.CurrentHost.Plugins[i].Route != null && Program.CurrentHost.Plugins[i].Route.CanLoadRoute(result.RouteFile))
                    {
                        object Route = (object)Program.CurrentRoute;                         //must cast to allow us to use the ref keyword.
                        Program.CurrentHost.Plugins[i].Route.LoadRoute(result.RouteFile, result.RouteEncoding, null, null, null, true, ref Route);
                        Program.CurrentRoute = (CurrentRoute)Route;
                        Program.Renderer.Lighting.OptionAmbientColor  = CurrentRoute.Atmosphere.AmbientLightColor;
                        Program.Renderer.Lighting.OptionDiffuseColor  = CurrentRoute.Atmosphere.DiffuseLightColor;
                        Program.Renderer.Lighting.OptionLightPosition = CurrentRoute.Atmosphere.LightPosition;
                        loaded = true;
                        break;
                    }
                }
                Plugins.UnloadPlugins();
                if (!loaded)
                {
                    throw new Exception("No plugins capable of loading routefile " + result.RouteFile + " were found.");
                }
                if (!string.IsNullOrEmpty(Interface.CurrentOptions.TrainName))
                {
                    folder = System.IO.Path.GetDirectoryName(result.RouteFile);
                    while (true)
                    {
                        string trainFolder = OpenBveApi.Path.CombineDirectory(folder, "Train");
                        if (System.IO.Directory.Exists(trainFolder))
                        {
                            try
                            {
                                folder = OpenBveApi.Path.CombineDirectory(trainFolder, Interface.CurrentOptions.TrainName);
                            }
                            catch (Exception ex)
                            {
                                if (ex is ArgumentException)
                                {
                                    break;
                                }
                            }
                            if (System.IO.Directory.Exists(folder))
                            {
                                file = OpenBveApi.Path.CombineFile(folder, "train.dat");
                                if (System.IO.File.Exists(file))
                                {
                                    result.TrainFolder   = folder;
                                    result.TrainEncoding = System.Text.Encoding.UTF8;
                                    for (int j = 0; j < Interface.CurrentOptions.TrainEncodings.Length; j++)
                                    {
                                        if (string.Compare(Interface.CurrentOptions.TrainEncodings[j].Value, result.TrainFolder, StringComparison.InvariantCultureIgnoreCase) == 0)
                                        {
                                            result.TrainEncoding = System.Text.Encoding.GetEncoding(Interface.CurrentOptions.TrainEncodings[j].Codepage);
                                            break;
                                        }
                                    }
                                }
                            }
                            break;
                        }
                        if (folder == null)
                        {
                            continue;
                        }
                        System.IO.DirectoryInfo info = System.IO.Directory.GetParent(folder);
                        if (info != null)
                        {
                            folder = info.FullName;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                Game.Reset(false);
            }
            // --- show the main menu if necessary ---
            if (result.RouteFile == null | result.TrainFolder == null)
            {
                Joysticks.RefreshJoysticks();

                // end HACK //
                result = formMain.ShowMainDialog(result);
            }
            else
            {
                result.Start = true;
                //Apply translations
                Translations.SetInGameLanguage(Translations.CurrentLanguageCode);
            }
            // --- start the actual program ---
            if (result.Start)
            {
                if (Initialize())
                {
                                        #if !DEBUG
                    try {
                                                #endif
                    MainLoop.StartLoopEx(result);
                                                #if !DEBUG
                }
                catch (Exception ex) {
                    bool found = false;
                    for (int i = 0; i < TrainManager.Trains.Length; i++)
                    {
                        if (TrainManager.Trains[i] != null && TrainManager.Trains[i].Plugin != null)
                        {
                            if (TrainManager.Trains[i].Plugin.LastException != null)
                            {
                                CrashHandler.LoadingCrash(ex.Message, true);
                                MessageBox.Show("The train plugin " + TrainManager.Trains[i].Plugin.PluginTitle + " caused a runtime exception: " + TrainManager.Trains[i].Plugin.LastException.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                                found            = true;
                                RestartArguments = "";
                                break;
                            }
                        }
                    }
                    if (!found)
                    {
                        if (ex is System.DllNotFoundException)
                        {
                            Interface.AddMessage(MessageType.Critical, false, "The required system library " + ex.Message + " was not found on the system.");
                            switch (ex.Message)
                            {
                            case "libopenal.so.1":
                                MessageBox.Show("openAL was not found on this system. \n Please install libopenal1 via your distribtion's package management system.", Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                                break;

                            default:
                                MessageBox.Show("The required system library " + ex.Message + " was not found on this system.", Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                                break;
                            }
                        }
                        else
                        {
                            Interface.AddMessage(MessageType.Critical, false, "The route and train loader encountered the following critical error: " + ex.Message);
                            CrashHandler.LoadingCrash(ex + Environment.StackTrace, false);
                        }
                        RestartArguments = "";
                    }
                }
#endif
                }
                Deinitialize();
            }
            // --- restart the program if necessary ---
            if (RestartArguments != null)
            {
                string arguments;
                if (FileSystem.RestartArguments.Length != 0 & RestartArguments.Length != 0)
                {
                    arguments = FileSystem.RestartArguments + " " + RestartArguments;
                }
                else
                {
                    arguments = FileSystem.RestartArguments + RestartArguments;
                }
                try {
                    System.Diagnostics.Process.Start(System.IO.File.Exists(FileSystem.RestartProcess) ? FileSystem.RestartProcess : Application.ExecutablePath, arguments);
                } catch (Exception ex) {
                    MessageBox.Show(ex.Message + "\n\nProcess = " + FileSystem.RestartProcess + "\nArguments = " + arguments, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Exemple #16
0
        internal static void Main(string[] args)
        {
            CurrentlyRunOnMono = Type.GetType("Mono.Runtime") != null;
            CurrentHost        = new Host();
            // file system
            FileSystem = FileSystem.FromCommandLineArgs(args);
            FileSystem.CreateFileSystem();
            Renderer     = new NewRenderer();
            CurrentRoute = new CurrentRoute(Renderer);
            Options.LoadOptions();
            if (Renderer.Screen.Width == 0 || Renderer.Screen.Height == 0)
            {
                Renderer.Screen.Width  = 960;
                Renderer.Screen.Height = 600;
            }
            Plugins.LoadPlugins();
            // command line arguments
            SkipArgs = new bool[args.Length];
            if (args.Length != 0)
            {
                string File = System.IO.Path.Combine(Application.StartupPath, "RouteViewer.exe");
                if (System.IO.File.Exists(File))
                {
                    int Skips = 0;
                    System.Text.StringBuilder NewArgs = new System.Text.StringBuilder();
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (args[i] != null && System.IO.File.Exists(args[i]))
                        {
                            if (System.IO.Path.GetExtension(args[i]).Equals(".csv", StringComparison.OrdinalIgnoreCase))
                            {
                                string Text = System.IO.File.ReadAllText(args[i], System.Text.Encoding.UTF8);
                                if (Text.Length != -1 &&
                                    Text.IndexOf("CreateMeshBuilder", StringComparison.OrdinalIgnoreCase) == -1)
                                {
                                    if (NewArgs.Length != 0)
                                    {
                                        NewArgs.Append(" ");
                                    }
                                    NewArgs.Append("\"" + args[i] + "\"");
                                    SkipArgs[i] = true;
                                    Skips++;
                                }
                            }
                        }
                        else
                        {
                            SkipArgs[i] = true;
                            Skips++;
                        }
                    }
                    if (NewArgs.Length != 0)
                    {
                        System.Diagnostics.Process.Start(File, NewArgs.ToString());
                    }
                    if (Skips == args.Length)
                    {
                        return;
                    }
                }
            }

            var options = new ToolkitOptions();

            options.Backend = PlatformBackend.PreferX11;
            Toolkit.Init(options);
            Interface.CurrentOptions.ObjectOptimizationBasicThreshold = 1000;
            Interface.CurrentOptions.ObjectOptimizationFullThreshold  = 250;
            Interface.CurrentOptions.AntiAliasingLevel         = 16;
            Interface.CurrentOptions.AnisotropicFilteringLevel = 16;
            // initialize camera

            currentGraphicsMode       = new GraphicsMode(new ColorFormat(8, 8, 8, 8), 24, 8, Interface.CurrentOptions.AntiAliasingLevel);
            currentGameWindow         = new ObjectViewer(Renderer.Screen.Width, Renderer.Screen.Height, currentGraphicsMode, "Object Viewer", GameWindowFlags.Default);
            currentGameWindow.Visible = true;
            currentGameWindow.TargetUpdateFrequency = 0;
            currentGameWindow.TargetRenderFrequency = 0;
            currentGameWindow.Title = "Object Viewer";
            currentGameWindow.Run();
            // quit
            Renderer.TextureManager.UnloadAllTextures();
        }
Exemple #17
0
 public TransponderEvent(CurrentRoute CurrentRoute, double TrackPositionDelta, TransponderTypes Type, int Data, int SectionIndex, bool ClipToFirstRedSection)
     : this(CurrentRoute, TrackPositionDelta, (int)Type, Data, SectionIndex, ClipToFirstRedSection)
 {
 }
Exemple #18
0
        internal static void Main(string[] args)
        {
            CurrentHost = new Host();
            // file system
            FileSystem = FileSystem.FromCommandLineArgs(args, CurrentHost);
            FileSystem.CreateFileSystem();
            Renderer     = new NewRenderer();
            CurrentRoute = new CurrentRoute(Renderer);
            Renderer.CameraTrackFollower = new TrackFollower(CurrentHost);
            Options.LoadOptions();
            if (Renderer.Screen.Width == 0 || Renderer.Screen.Height == 0)
            {
                Renderer.Screen.Width  = 960;
                Renderer.Screen.Height = 600;
            }
            Plugins.LoadPlugins();
            // command line arguments
            List <string> filesToLoad = new List <string>();

            if (args.Length != 0)
            {
                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i] != null)
                    {
                        if (System.IO.File.Exists(args[i]))
                        {
                            for (int j = 0; j < CurrentHost.Plugins.Length; j++)
                            {
                                if (CurrentHost.Plugins[j].Route != null && CurrentHost.Plugins[j].Route.CanLoadRoute(args[i]))
                                {
                                    string File = System.IO.Path.Combine(Application.StartupPath, "RouteViewer.exe");
                                    if (System.IO.File.Exists(File))
                                    {
                                        System.Diagnostics.Process.Start(File, args[i]);
                                    }
                                    continue;
                                }

                                if (CurrentHost.Plugins[j].Object != null && CurrentHost.Plugins[j].Object.CanLoadObject(args[i]))
                                {
                                    filesToLoad.Add(args[i]);
                                }
                            }
                        }
                        else if (args[i].ToLowerInvariant() == "/enablehacks")
                        {
                            //Deliberately undocumented option for debugging use
                            Interface.CurrentOptions.EnableBveTsHacks = true;
                            for (int j = 0; j < CurrentHost.Plugins.Length; j++)
                            {
                                if (CurrentHost.Plugins[j].Object != null)
                                {
                                    CompatabilityHacks enabledHacks = new CompatabilityHacks
                                    {
                                        BveTsHacks        = true,
                                        CylinderHack      = false,
                                        BlackTransparency = true
                                    };
                                    CurrentHost.Plugins[j].Object.SetCompatibilityHacks(enabledHacks);
                                }
                            }
                        }
                    }
                }

                if (filesToLoad.Count != 0)
                {
                    Files = filesToLoad.ToArray();
                }
            }

            var options = new ToolkitOptions
            {
                Backend = PlatformBackend.PreferX11
            };

            Toolkit.Init(options);
            Interface.CurrentOptions.ObjectOptimizationBasicThreshold = 1000;
            Interface.CurrentOptions.ObjectOptimizationFullThreshold  = 250;
            Interface.CurrentOptions.AntiAliasingLevel         = 16;
            Interface.CurrentOptions.AnisotropicFilteringLevel = 16;
            // initialize camera

            currentGraphicsMode = new GraphicsMode(new ColorFormat(8, 8, 8, 8), 24, 8, Interface.CurrentOptions.AntiAliasingLevel);
            currentGameWindow   = new ObjectViewer(Renderer.Screen.Width, Renderer.Screen.Height, currentGraphicsMode, "Object Viewer", GameWindowFlags.Default)
            {
                Visible = true,
                TargetUpdateFrequency = 0,
                TargetRenderFrequency = 0,
                Title = "Object Viewer"
            };
            currentGameWindow.Run();
            // quit
            Renderer.TextureManager.UnloadAllTextures();
        }
Exemple #19
0
        public void Recalculate()
        {
            Application.Current.Dispatcher.Invoke((Action)(() =>
            {
                CurrentRoute.Clear();
            }), DispatcherPriority.Normal, null);


            if (WayPoints.Count < 2)
            {
                return;
            }

            double actualMaxLY = MaxLY;

            if (JDC != 5)
            {
                actualMaxLY *= .9;
            }

            // new routing
            string start = string.Empty;
            string end   = WayPoints[0];

            List <string> avoidSystems = AvoidSystems.ToList();


            AlternateMids.Clear();


            // loop through all the waypoints
            for (int i = 1; i < WayPoints.Count; i++)
            {
                start = end;
                end   = WayPoints[i];



                List <Navigation.RoutePoint> sysList = Navigation.NavigateCapitals(start, end, actualMaxLY, null, avoidSystems);

                if (sysList != null)
                {
                    Application.Current.Dispatcher.Invoke((Action)(() =>
                    {
                        foreach (Navigation.RoutePoint s in sysList)
                        {
                            // for multiple waypoint routes, the first in the new and last item in the list will be the same system, so remove
                            if (CurrentRoute.Count > 0 && CurrentRoute.Last().SystemName == s.SystemName)
                            {
                                CurrentRoute.Last().LY = s.LY;
                            }
                            else
                            {
                                CurrentRoute.Add(s);
                            }
                        }

                        if (sysList.Count > 2)
                        {
                            for (int j = 2; j < sysList.Count; j++)
                            {
                                List <string> a = Navigation.GetSystemsWithinXLYFrom(CurrentRoute[j - 2].SystemName, MaxLY, false, false);
                                List <string> b = Navigation.GetSystemsWithinXLYFrom(CurrentRoute[j].SystemName, MaxLY, false, false);

                                IEnumerable <string> alternatives = a.AsQueryable().Intersect(b);

                                AlternateMids[CurrentRoute[j - 1].SystemName] = new ObservableCollection <string>();
                                foreach (string mid in alternatives)
                                {
                                    if (mid != CurrentRoute[j - 1].SystemName)
                                    {
                                        AlternateMids[CurrentRoute[j - 1].SystemName].Add(mid);
                                    }
                                }
                            }
                        }
                    }), DispatcherPriority.Normal, null);
                }
            }
        }
Exemple #20
0
 public BibaAuthorizationHandler(CurrentRoute route)
 {
     _route = route;
 }
Exemple #21
0
        internal static void Main(string[] args)
        {
            CurrentHost          = new Host();
            commandLineArguments = args;
            // platform and mono
            CurrentlyRunOnMono = Type.GetType("Mono.Runtime") != null;
            // file system
            FileSystem = FileSystem.FromCommandLineArgs(args);
            FileSystem.CreateFileSystem();
            Renderer     = new NewRenderer();
            CurrentRoute = new CurrentRoute(Renderer);
            Sounds       = new Sounds();

            // command line arguments
            SkipArgs = new bool[args.Length];
            if (args.Length != 0)
            {
                string File = System.IO.Path.Combine(Application.StartupPath, "ObjectViewer.exe");
                if (System.IO.File.Exists(File))
                {
                    int Skips = 0;
                    System.Text.StringBuilder NewArgs = new System.Text.StringBuilder();
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (args[i] != null && System.IO.File.Exists(args[i]))
                        {
                            if (System.IO.Path.GetExtension(args[i]).Equals(".csv", StringComparison.OrdinalIgnoreCase))
                            {
                                string Text = System.IO.File.ReadAllText(args[i], System.Text.Encoding.UTF8);
                                if (Text.Length == 0 || Text.IndexOf("CreateMeshBuilder", StringComparison.OrdinalIgnoreCase) >= 0)
                                {
                                    if (NewArgs.Length != 0)
                                    {
                                        NewArgs.Append(" ");
                                    }
                                    NewArgs.Append("\"" + args[i] + "\"");
                                    SkipArgs[i] = true;
                                    Skips++;
                                }
                            }
                        }
                        else
                        {
                            SkipArgs[i] = true;
                            Skips++;
                        }
                    }
                    if (NewArgs.Length != 0)
                    {
                        System.Diagnostics.Process.Start(File, NewArgs.ToString());
                    }
                    if (Skips == args.Length)
                    {
                        return;
                    }
                }
            }
            Options.LoadOptions();
            var options = new ToolkitOptions();

            Plugins.LoadPlugins();
            options.Backend = PlatformBackend.PreferX11;
            Toolkit.Init(options);
            string folder = Program.FileSystem.GetDataFolder("Languages");

            Translations.LoadLanguageFiles(folder);
            Interface.CurrentOptions.ObjectOptimizationBasicThreshold = 1000;
            Interface.CurrentOptions.ObjectOptimizationFullThreshold  = 250;
            // application
            currentGraphicsMode = new GraphicsMode(new ColorFormat(8, 8, 8, 8), 24, 8, Interface.CurrentOptions.AntiAliasingLevel);
            if (Renderer.Screen.Width == 0 || Renderer.Screen.Height == 0)
            {
                //Duff values saved, so reset to something sensible else we crash
                Renderer.Screen.Width  = 1024;
                Renderer.Screen.Height = 768;
            }
            Renderer.CameraTrackFollower            = new TrackFollower(Program.CurrentHost);
            currentGameWindow                       = new RouteViewer(Renderer.Screen.Width, Renderer.Screen.Height, currentGraphicsMode, "Route Viewer", GameWindowFlags.Default);
            currentGameWindow.Visible               = true;
            currentGameWindow.TargetUpdateFrequency = 0;
            currentGameWindow.TargetRenderFrequency = 0;
            currentGameWindow.Title                 = "Route Viewer";
            processCommandLineArgs                  = true;
            currentGameWindow.Run();
            //Unload
            Sounds.Deinitialize();
        }
Exemple #22
0
        // parse route
        internal void ParseRoute(string FileName, bool isRW, System.Text.Encoding Encoding, string trainPath, string objectPath, string soundPath, bool PreviewOnly, Plugin hostPlugin)
        {
            Plugin       = hostPlugin;
            CurrentRoute = Plugin.CurrentRoute;

            /*
             * Store paths for later use
             */
            ObjectPath = objectPath;
            SoundPath  = soundPath;
            TrainPath  = trainPath;
            IsRW       = isRW;
            if (!PreviewOnly)
            {
                for (int i = 0; i < Plugin.CurrentHost.Plugins.Length; i++)
                {
                    if (Plugin.CurrentHost.Plugins[i].Object != null)
                    {
                        Plugin.CurrentHost.Plugins[i].Object.SetObjectParser(SoundPath);                         //HACK: Pass out the sound folder path to those plugins which consume it
                    }
                }
            }
            freeObjCount  = 0;
            railtypeCount = 0;
            Plugin.CurrentOptions.UnitOfSpeed           = "km/h";
            Plugin.CurrentOptions.SpeedConversionFactor = 0.0;
            CompatibilityFolder = Plugin.FileSystem.GetDataFolder("Compatibility");
            if (!PreviewOnly)
            {
                CompatibilityObjects.LoadCompatibilityObjects(Path.CombineFile(CompatibilityFolder, "CompatibilityObjects.xml"));
            }

            RoutePatchDatabaseParser.LoadRoutePatchDatabase(ref availableRoutefilePatches);

            RouteData Data = new RouteData
            {
                BlockInterval          = 25.0,
                AccurateObjectDisposal = false,
                FirstUsedBlock         = -1,
                Blocks = new List <Block>()
            };

            Data.Blocks.Add(new Block(PreviewOnly));
            Data.Blocks[0].Rails.Add(0, new Rail {
                RailStarted = true
            });
            Data.Blocks[0].RailType           = new[] { 0 };
            Data.Blocks[0].Accuracy           = 2.0;
            Data.Blocks[0].AdhesionMultiplier = 1.0;
            Data.Blocks[0].CurrentTrackState  = new TrackElement(0.0);
            if (!PreviewOnly)
            {
                Data.Blocks[0].Background = 0;
                Data.Blocks[0].Fog        = new Fog(CurrentRoute.NoFogStart, CurrentRoute.NoFogEnd, Color24.Grey, 0);
                Data.Blocks[0].Cycle      = new[] { -1 };
                Data.Blocks[0].RailCycles = new RailCycle[1];
                Data.Blocks[0].RailCycles[0].RailCycleIndex = -1;
                Data.Blocks[0].Height        = IsRW ? 0.3 : 0.0;
                Data.Blocks[0].RailFreeObj   = new Dictionary <int, List <FreeObj> >();
                Data.Blocks[0].GroundFreeObj = new List <FreeObj>();
                Data.Blocks[0].RailWall      = new Dictionary <int, WallDike>();
                Data.Blocks[0].RailDike      = new Dictionary <int, WallDike>();
                Data.Blocks[0].RailPole      = new Pole[] {};
                Data.Markers      = new Marker[] {};
                Data.RequestStops = new StopRequest[] { };
                string PoleFolder = Path.CombineDirectory(CompatibilityFolder, "Poles");
                Data.Structure.Poles = new PoleDictionary
                {
                    { 0, new ObjectDictionary() },
                    { 1, new ObjectDictionary() },
                    { 2, new ObjectDictionary() },
                    { 3, new ObjectDictionary() }
                };
                Data.Structure.Poles[0].Add(0, LoadStaticObject(Path.CombineFile(PoleFolder, "pole_1.csv"), System.Text.Encoding.UTF8, false));
                Data.Structure.Poles[1].Add(0, LoadStaticObject(Path.CombineFile(PoleFolder, "pole_2.csv"), System.Text.Encoding.UTF8, false));
                Data.Structure.Poles[2].Add(0, LoadStaticObject(Path.CombineFile(PoleFolder, "pole_3.csv"), System.Text.Encoding.UTF8, false));
                Data.Structure.Poles[3].Add(0, LoadStaticObject(Path.CombineFile(PoleFolder, "pole_4.csv"), System.Text.Encoding.UTF8, false));

                Data.Structure.RailObjects    = new ObjectDictionary();
                Data.Structure.RailObjects    = new ObjectDictionary();
                Data.Structure.Ground         = new ObjectDictionary();
                Data.Structure.WallL          = new ObjectDictionary();
                Data.Structure.WallR          = new ObjectDictionary();
                Data.Structure.DikeL          = new ObjectDictionary();
                Data.Structure.DikeR          = new ObjectDictionary();
                Data.Structure.FormL          = new ObjectDictionary();
                Data.Structure.FormR          = new ObjectDictionary();
                Data.Structure.FormCL         = new ObjectDictionary();
                Data.Structure.FormCR         = new ObjectDictionary();
                Data.Structure.RoofL          = new ObjectDictionary();
                Data.Structure.RoofR          = new ObjectDictionary();
                Data.Structure.RoofCL         = new ObjectDictionary();
                Data.Structure.RoofCR         = new ObjectDictionary();
                Data.Structure.CrackL         = new ObjectDictionary();
                Data.Structure.CrackR         = new ObjectDictionary();
                Data.Structure.FreeObjects    = new ObjectDictionary();
                Data.Structure.Beacon         = new ObjectDictionary();
                Data.Structure.Cycles         = new int[][] {};
                Data.Structure.RailCycles     = new int[][] { };
                Data.Structure.Run            = new int[] {};
                Data.Structure.Flange         = new int[] {};
                Data.Backgrounds              = new BackgroundDictionary();
                Data.TimetableDaytime         = new OpenBveApi.Textures.Texture[] { null, null, null, null };
                Data.TimetableNighttime       = new OpenBveApi.Textures.Texture[] { null, null, null, null };
                Data.Structure.WeatherObjects = new ObjectDictionary();
                // signals
                Data.Signals = new SignalDictionary();
                if (Plugin.CurrentOptions.CurrentCompatibilitySignalSet == null)                 //not selected via main form
                {
                    Plugin.CurrentOptions.CurrentCompatibilitySignalSet = Path.CombineFile(Plugin.FileSystem.GetDataFolder("Compatibility"), "Signals\\Japanese.xml");
                }
                CompatibilitySignalObject.ReadCompatibilitySignalXML(Plugin.CurrentHost, Plugin.CurrentOptions.CurrentCompatibilitySignalSet, out Data.CompatibilitySignals, out CompatibilityObjects.SignalPost, out Data.SignalSpeeds);
                // game data
                CurrentRoute.Sections = new[]
                {
                    new RouteManager2.SignalManager.Section(0, new[] { new SectionAspect(0, 0.0), new SectionAspect(4, double.PositiveInfinity) }, SectionType.IndexBased)
                };

                CurrentRoute.Sections[0].CurrentAspect = 0;
                CurrentRoute.Sections[0].StationIndex  = -1;
            }
            ParseRouteForData(FileName, Encoding, ref Data, PreviewOnly);
            if (Plugin.Cancel)
            {
                Plugin.IsLoading = false;
                return;
            }
            ApplyRouteData(FileName, ref Data, PreviewOnly);
        }
Exemple #23
0
        // render scene

        internal static void RenderScene(double TimeElapsed)
        {
            // initialize
            LibRender.Renderer.ResetOpenGlState();

            if (LibRender.Renderer.OptionWireframe)
            {
                if (CurrentRoute.CurrentFog.Start < CurrentRoute.CurrentFog.End)
                {
                    const float fogdistance = 600.0f;
                    float       n           = (fogdistance - CurrentRoute.CurrentFog.Start) / (CurrentRoute.CurrentFog.End - CurrentRoute.CurrentFog.Start);
                    float       cr          = n * inv255 * (float)CurrentRoute.CurrentFog.Color.R;
                    float       cg          = n * inv255 * (float)CurrentRoute.CurrentFog.Color.G;
                    float       cb          = n * inv255 * (float)CurrentRoute.CurrentFog.Color.B;
                    GL.ClearColor(cr, cg, cb, 1.0f);
                }
                else
                {
                    GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f);
                }
                GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
            }
            else
            {
                GL.Clear(ClearBufferMask.DepthBufferBit);
            }
            GL.PushMatrix();
            UpdateViewport(ViewPortChangeMode.ChangeToScenery);
            // set up camera
            double   dx     = Camera.AbsoluteDirection.X;
            double   dy     = Camera.AbsoluteDirection.Y;
            double   dz     = Camera.AbsoluteDirection.Z;
            double   ux     = Camera.AbsoluteUp.X;
            double   uy     = Camera.AbsoluteUp.Y;
            double   uz     = Camera.AbsoluteUp.Z;
            Matrix4d lookat = Matrix4d.LookAt(0.0, 0.0, 0.0, dx, dy, dz, ux, uy, uz);

            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadMatrix(ref lookat);
            GL.Light(LightName.Light0, LightParameter.Position, new float[] { (float)LibRender.Renderer.OptionLightPosition.X, (float)LibRender.Renderer.OptionLightPosition.Y, (float)LibRender.Renderer.OptionLightPosition.Z, 0.0f });
            // fog
            double fd = CurrentRoute.NextFog.TrackPosition - CurrentRoute.PreviousFog.TrackPosition;

            if (fd != 0.0)
            {
                float fr  = (float)((World.CameraTrackFollower.TrackPosition - CurrentRoute.PreviousFog.TrackPosition) / fd);
                float frc = 1.0f - fr;
                CurrentRoute.CurrentFog.Start   = CurrentRoute.PreviousFog.Start * frc + CurrentRoute.NextFog.Start * fr;
                CurrentRoute.CurrentFog.End     = CurrentRoute.PreviousFog.End * frc + CurrentRoute.NextFog.End * fr;
                CurrentRoute.CurrentFog.Color.R = (byte)((float)CurrentRoute.PreviousFog.Color.R * frc + (float)CurrentRoute.NextFog.Color.R * fr);
                CurrentRoute.CurrentFog.Color.G = (byte)((float)CurrentRoute.PreviousFog.Color.G * frc + (float)CurrentRoute.NextFog.Color.G * fr);
                CurrentRoute.CurrentFog.Color.B = (byte)((float)CurrentRoute.PreviousFog.Color.B * frc + (float)CurrentRoute.NextFog.Color.B * fr);
            }
            else
            {
                CurrentRoute.CurrentFog = CurrentRoute.PreviousFog;
            }
            // render background

            GL.Disable(EnableCap.DepthTest);
            CurrentRoute.UpdateBackground(TimeElapsed, Game.CurrentInterface != Game.InterfaceType.Normal);
            RenderEvents(Camera.AbsolutePosition);
            // fog
            float aa = CurrentRoute.CurrentFog.Start;
            float bb = CurrentRoute.CurrentFog.End;

            if (aa < bb & aa < Backgrounds.BackgroundImageDistance)
            {
                if (!LibRender.Renderer.FogEnabled)
                {
                    GL.Fog(FogParameter.FogMode, (int)FogMode.Linear);
                }
                GL.Fog(FogParameter.FogStart, aa);
                GL.Fog(FogParameter.FogEnd, bb);
                GL.Fog(FogParameter.FogColor, new float[] { inv255 *(float)CurrentRoute.CurrentFog.Color.R, inv255 * (float)CurrentRoute.CurrentFog.Color.G, inv255 * (float)CurrentRoute.CurrentFog.Color.B, 1.0f });
                if (!LibRender.Renderer.FogEnabled)
                {
                    GL.Enable(EnableCap.Fog); LibRender.Renderer.FogEnabled = true;
                }
            }
            else if (LibRender.Renderer.FogEnabled)
            {
                GL.Disable(EnableCap.Fog); LibRender.Renderer.FogEnabled = false;
            }
            // world layer
            bool optionLighting = LibRender.Renderer.OptionLighting;

            LibRender.Renderer.LastBoundTexture = null;
            if (LibRender.Renderer.OptionLighting)
            {
                if (!LibRender.Renderer.LightingEnabled)
                {
                    GL.Enable(EnableCap.Lighting); LibRender.Renderer.LightingEnabled = true;
                }
                if (Camera.CurrentRestriction == CameraRestrictionMode.NotAvailable)
                {
                    GL.Light(LightName.Light0, LightParameter.Ambient, new float[] { inv255 *(float)LibRender.Renderer.OptionAmbientColor.R, inv255 * (float)LibRender.Renderer.OptionAmbientColor.G, inv255 * (float)LibRender.Renderer.OptionAmbientColor.B, 1.0f });
                    GL.Light(LightName.Light0, LightParameter.Diffuse, new float[] { inv255 *(float)LibRender.Renderer.OptionDiffuseColor.R, inv255 * (float)LibRender.Renderer.OptionDiffuseColor.G, inv255 * (float)LibRender.Renderer.OptionDiffuseColor.B, 1.0f });
                }
            }
            else if (LibRender.Renderer.LightingEnabled)
            {
                GL.Disable(EnableCap.Lighting); LibRender.Renderer.LightingEnabled = false;
            }
            // static opaque
            if (Interface.CurrentOptions.DisableDisplayLists)
            {
                LibRender.Renderer.ResetOpenGlState();
                for (int i = 0; i < StaticOpaque.Length; i++)
                {
                    if (StaticOpaque[i] != null)
                    {
                        if (StaticOpaque[i].List != null)
                        {
                            for (int j = 0; j < StaticOpaque[i].List.FaceCount; j++)
                            {
                                if (StaticOpaque[i].List.Faces[j] != null)
                                {
                                    RenderFace(ref StaticOpaque[i].List.Faces[j], Camera.AbsolutePosition);
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                for (int i = 0; i < StaticOpaque.Length; i++)
                {
                    if (StaticOpaque[i] != null)
                    {
                        if (StaticOpaque[i].Update | StaticOpaqueForceUpdate)
                        {
                            StaticOpaque[i].Update = false;
                            if (StaticOpaque[i].OpenGlDisplayListAvailable)
                            {
                                GL.DeleteLists(StaticOpaque[i].OpenGlDisplayList, 1);
                                StaticOpaque[i].OpenGlDisplayListAvailable = false;
                            }
                            if (StaticOpaque[i].List.FaceCount != 0)
                            {
                                StaticOpaque[i].OpenGlDisplayList          = GL.GenLists(1);
                                StaticOpaque[i].OpenGlDisplayListAvailable = true;
                                LibRender.Renderer.ResetOpenGlState();
                                GL.NewList(StaticOpaque[i].OpenGlDisplayList, ListMode.Compile);
                                for (int j = 0; j < StaticOpaque[i].List.FaceCount; j++)
                                {
                                    if (StaticOpaque[i].List.Faces[j] != null)
                                    {
                                        RenderFace(ref StaticOpaque[i].List.Faces[j], Camera.AbsolutePosition);
                                    }
                                }
                                GL.EndList();
                            }
                            StaticOpaque[i].WorldPosition = Camera.AbsolutePosition;
                        }
                    }
                }
                StaticOpaqueForceUpdate = false;
                for (int i = 0; i < StaticOpaque.Length; i++)
                {
                    if (StaticOpaque[i] != null && StaticOpaque[i].OpenGlDisplayListAvailable)
                    {
                        LibRender.Renderer.ResetOpenGlState();
                        GL.PushMatrix();
                        GL.Translate(StaticOpaque[i].WorldPosition.X - Camera.AbsolutePosition.X, StaticOpaque[i].WorldPosition.Y - Camera.AbsolutePosition.Y, StaticOpaque[i].WorldPosition.Z - Camera.AbsolutePosition.Z);
                        GL.CallList(StaticOpaque[i].OpenGlDisplayList);
                        GL.PopMatrix();
                    }
                }
                //Update bounding box positions now we've rendered the objects
                int currentBox = 0;
                for (int i = 0; i < StaticOpaque.Length; i++)
                {
                    if (StaticOpaque[i] != null)
                    {
                        currentBox++;
                    }
                }
            }
            // dynamic opaque
            LibRender.Renderer.ResetOpenGlState();
            for (int i = 0; i < DynamicOpaque.FaceCount; i++)
            {
                RenderFace(ref DynamicOpaque.Faces[i], Camera.AbsolutePosition);
            }
            // dynamic alpha
            LibRender.Renderer.ResetOpenGlState();
            DynamicAlpha.SortPolygons();
            if (Interface.CurrentOptions.TransparencyMode == TransparencyMode.Performance)
            {
                GL.Enable(EnableCap.Blend); LibRender.Renderer.BlendEnabled = true;
                GL.DepthMask(false);
                LibRender.Renderer.SetAlphaFunc(AlphaFunction.Greater, 0.0f);
                for (int i = 0; i < DynamicAlpha.FaceCount; i++)
                {
                    RenderFace(ref DynamicAlpha.Faces[i], Camera.AbsolutePosition);
                }
            }
            else
            {
                GL.Disable(EnableCap.Blend); LibRender.Renderer.BlendEnabled = false;
                LibRender.Renderer.SetAlphaFunc(AlphaFunction.Equal, 1.0f);
                GL.DepthMask(true);
                for (int i = 0; i < DynamicAlpha.FaceCount; i++)
                {
                    int r = (int)ObjectManager.Objects[DynamicAlpha.Faces[i].ObjectIndex].Mesh.Faces[DynamicAlpha.Faces[i].FaceIndex].Material;
                    if (ObjectManager.Objects[DynamicAlpha.Faces[i].ObjectIndex].Mesh.Materials[r].BlendMode == MeshMaterialBlendMode.Normal & ObjectManager.Objects[DynamicAlpha.Faces[i].ObjectIndex].Mesh.Materials[r].GlowAttenuationData == 0)
                    {
                        if (ObjectManager.Objects[DynamicAlpha.Faces[i].ObjectIndex].Mesh.Materials[r].Color.A == 255)
                        {
                            RenderFace(ref DynamicAlpha.Faces[i], Camera.AbsolutePosition);
                        }
                    }
                }
                GL.Enable(EnableCap.Blend); LibRender.Renderer.BlendEnabled = true;
                LibRender.Renderer.SetAlphaFunc(AlphaFunction.Less, 1.0f);
                GL.DepthMask(false);
                bool additive = false;
                for (int i = 0; i < DynamicAlpha.FaceCount; i++)
                {
                    int r = (int)ObjectManager.Objects[DynamicAlpha.Faces[i].ObjectIndex].Mesh.Faces[DynamicAlpha.Faces[i].FaceIndex].Material;
                    if (ObjectManager.Objects[DynamicAlpha.Faces[i].ObjectIndex].Mesh.Materials[r].BlendMode == MeshMaterialBlendMode.Additive)
                    {
                        if (!additive)
                        {
                            LibRender.Renderer.UnsetAlphaFunc();
                            additive = true;
                        }
                        RenderFace(ref DynamicAlpha.Faces[i], Camera.AbsolutePosition);
                    }
                    else
                    {
                        if (additive)
                        {
                            LibRender.Renderer.SetAlphaFunc(AlphaFunction.Less, 1.0f);
                            additive = false;
                        }
                        RenderFace(ref DynamicAlpha.Faces[i], Camera.AbsolutePosition);
                    }
                }
            }
            // motion blur
            GL.Disable(EnableCap.DepthTest);
            GL.DepthMask(false);
            LibRender.Renderer.SetAlphaFunc(AlphaFunction.Greater, 0.0f);
            if (Interface.CurrentOptions.MotionBlur != MotionBlurMode.None)
            {
                if (LibRender.Renderer.LightingEnabled)
                {
                    GL.Disable(EnableCap.Lighting);
                    LibRender.Renderer.LightingEnabled = false;
                }
                LibRender.MotionBlur.RenderFullscreen(Interface.CurrentOptions.MotionBlur, LibRender.Renderer.FrameRate, Math.Abs(Camera.CurrentSpeed));
            }
            // overlay layer
            if (LibRender.Renderer.FogEnabled)
            {
                GL.Disable(EnableCap.Fog); LibRender.Renderer.FogEnabled = false;
            }
            GL.LoadIdentity();
            UpdateViewport(ViewPortChangeMode.ChangeToCab);
            lookat = Matrix4d.LookAt(0.0, 0.0, 0.0, dx, dy, dz, ux, uy, uz);
            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadMatrix(ref lookat);
            if (Camera.CurrentRestriction == CameraRestrictionMode.NotAvailable)
            {
                // 3d cab
                LibRender.Renderer.ResetOpenGlState();                 // TODO: inserted
                GL.DepthMask(true);
                GL.Enable(EnableCap.DepthTest);
                GL.Clear(ClearBufferMask.DepthBufferBit);
                if (!LibRender.Renderer.LightingEnabled)
                {
                    GL.Enable(EnableCap.Lighting); LibRender.Renderer.LightingEnabled = true;
                }
                LibRender.Renderer.OptionLighting = true;
                GL.Light(LightName.Light0, LightParameter.Ambient, new float[] { 0.7f, 0.7f, 0.7f, 1.0f });
                GL.Light(LightName.Light0, LightParameter.Diffuse, new float[] { 0.7f, 0.7f, 0.7f, 1.0f });
                // overlay opaque
                LibRender.Renderer.SetAlphaFunc(AlphaFunction.Greater, 0.9f);
                for (int i = 0; i < OverlayOpaque.FaceCount; i++)
                {
                    RenderFace(ref OverlayOpaque.Faces[i], Camera.AbsolutePosition);
                }
                // overlay alpha
                OverlayAlpha.SortPolygons();
                if (Interface.CurrentOptions.TransparencyMode == TransparencyMode.Performance)
                {
                    GL.Enable(EnableCap.Blend); LibRender.Renderer.BlendEnabled = true;
                    GL.DepthMask(false);
                    LibRender.Renderer.SetAlphaFunc(AlphaFunction.Greater, 0.0f);
                    for (int i = 0; i < OverlayAlpha.FaceCount; i++)
                    {
                        RenderFace(ref OverlayAlpha.Faces[i], Camera.AbsolutePosition);
                    }
                }
                else
                {
                    GL.Disable(EnableCap.Blend); LibRender.Renderer.BlendEnabled = false;
                    LibRender.Renderer.SetAlphaFunc(AlphaFunction.Equal, 1.0f);
                    GL.DepthMask(true);
                    for (int i = 0; i < OverlayAlpha.FaceCount; i++)
                    {
                        int r = (int)ObjectManager.Objects[OverlayAlpha.Faces[i].ObjectIndex].Mesh.Faces[OverlayAlpha.Faces[i].FaceIndex].Material;
                        if (ObjectManager.Objects[OverlayAlpha.Faces[i].ObjectIndex].Mesh.Materials[r].BlendMode == MeshMaterialBlendMode.Normal & ObjectManager.Objects[OverlayAlpha.Faces[i].ObjectIndex].Mesh.Materials[r].GlowAttenuationData == 0)
                        {
                            if (ObjectManager.Objects[OverlayAlpha.Faces[i].ObjectIndex].Mesh.Materials[r].Color.A == 255)
                            {
                                RenderFace(ref OverlayAlpha.Faces[i], Camera.AbsolutePosition);
                            }
                        }
                    }
                    GL.Enable(EnableCap.Blend); LibRender.Renderer.BlendEnabled = true;
                    LibRender.Renderer.SetAlphaFunc(AlphaFunction.Less, 1.0f);
                    GL.DepthMask(false);
                    bool additive = false;
                    for (int i = 0; i < OverlayAlpha.FaceCount; i++)
                    {
                        int r = (int)ObjectManager.Objects[OverlayAlpha.Faces[i].ObjectIndex].Mesh.Faces[OverlayAlpha.Faces[i].FaceIndex].Material;
                        if (ObjectManager.Objects[OverlayAlpha.Faces[i].ObjectIndex].Mesh.Materials[r].BlendMode == MeshMaterialBlendMode.Additive)
                        {
                            if (!additive)
                            {
                                LibRender.Renderer.UnsetAlphaFunc();
                                additive = true;
                            }
                            RenderFace(ref OverlayAlpha.Faces[i], Camera.AbsolutePosition);
                        }
                        else
                        {
                            if (additive)
                            {
                                LibRender.Renderer.SetAlphaFunc(AlphaFunction.Less, 1.0f);
                                additive = false;
                            }
                            RenderFace(ref OverlayAlpha.Faces[i], Camera.AbsolutePosition);
                        }
                    }
                }
            }
            else
            {
                /*
                 * Render 2D Cab
                 * This is actually an animated object generated on the fly and held in memory
                 */
                if (LibRender.Renderer.LightingEnabled)
                {
                    GL.Disable(EnableCap.Lighting); LibRender.Renderer.LightingEnabled = false;                     // TODO: was 'true' before
                }
                LibRender.Renderer.OptionLighting = false;
                if (!LibRender.Renderer.BlendEnabled)
                {
                    GL.Enable(EnableCap.Blend); LibRender.Renderer.BlendEnabled = true;
                }
                GL.DepthMask(false);
                GL.Disable(EnableCap.DepthTest);
                LibRender.Renderer.UnsetAlphaFunc();
                OverlayAlpha.SortPolygons();
                for (int i = 0; i < OverlayAlpha.FaceCount; i++)
                {
                    RenderFace(ref OverlayAlpha.Faces[i], Camera.AbsolutePosition);
                }
            }
            // render overlays
            LibRender.Renderer.OptionLighting = optionLighting;
            if (LibRender.Renderer.LightingEnabled)
            {
                GL.Disable(EnableCap.Lighting); LibRender.Renderer.LightingEnabled = false;
            }
            if (LibRender.Renderer.FogEnabled)
            {
                GL.Disable(EnableCap.Fog); LibRender.Renderer.FogEnabled = false;
            }
            if (LibRender.Renderer.BlendEnabled)
            {
                GL.Disable(EnableCap.Blend); LibRender.Renderer.BlendEnabled = false;
            }
            LibRender.Renderer.UnsetAlphaFunc();
            GL.Disable(EnableCap.DepthTest);
            RenderOverlays(TimeElapsed);
            // finalize rendering
            GL.PopMatrix();
        }
Exemple #24
0
        public static RouteStation ReadStationXML(CurrentRoute Route, string fileName, bool PreviewOnly, Texture[] daytimeTimetableTextures, Texture[] nighttimeTimetableTextures, int CurrentStation, ref bool passAlarm, ref StopRequest stopRequest)
        {
            RouteStation station = new RouteStation
            {
                Stops = new StationStop[] { }
            };

            stopRequest.Early              = new RequestStop();
            stopRequest.OnTime             = new RequestStop();
            stopRequest.Late               = new RequestStop();
            stopRequest.OnTime.Probability = 75;
            //The current XML file to load
            XmlDocument currentXML = new XmlDocument();

            //Load the object's XML file
            currentXML.Load(fileName);
            string Path = System.IO.Path.GetDirectoryName(fileName);

            //Check for null
            if (currentXML.DocumentElement != null)
            {
                XmlNodeList DocumentNodes = currentXML.DocumentElement.SelectNodes("/openBVE/Station");
                //Check this file actually contains OpenBVE station nodes
                if (DocumentNodes != null)
                {
                    foreach (XmlNode n in DocumentNodes)
                    {
                        if (n.ChildNodes.OfType <XmlElement>().Any())
                        {
                            foreach (XmlNode c in n.ChildNodes)
                            {
                                //string[] Arguments = c.InnerText.Split(new[] { ',' });
                                switch (c.Name.ToLowerInvariant())
                                {
                                case "name":
                                    if (!string.IsNullOrEmpty(c.InnerText))
                                    {
                                        station.Name = c.InnerText;
                                    }
                                    else
                                    {
                                        Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Station name was empty in XML file " + fileName);
                                    }
                                    break;

                                case "arrivaltime":
                                    if (!string.IsNullOrEmpty(c.InnerText))
                                    {
                                        if (!Parser.TryParseTime(c.InnerText, out station.ArrivalTime))
                                        {
                                            Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Station arrival time was invalid in XML file " + fileName);
                                        }
                                    }
                                    break;

                                case "departuretime":
                                    if (!string.IsNullOrEmpty(c.InnerText))
                                    {
                                        if (!Parser.TryParseTime(c.InnerText, out station.DepartureTime))
                                        {
                                            Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Station arrival time was invalid in XML file " + fileName);
                                        }
                                    }
                                    break;

                                case "type":
                                    switch (c.InnerText.ToLowerInvariant())
                                    {
                                    case "c":
                                    case "changeends":
                                        station.Type = StationType.ChangeEnds;
                                        break;

                                    case "j":
                                    case "jump":
                                        station.Type = StationType.Jump;
                                        break;

                                    case "t":
                                    case "terminal":
                                        station.Type = StationType.Terminal;
                                        break;

                                    default:
                                        station.Type = StationType.Normal;
                                        break;
                                    }
                                    break;

                                case "jumpindex":
                                    if (!string.IsNullOrEmpty(c.InnerText))
                                    {
                                        if (!NumberFormats.TryParseIntVb6(c.InnerText, out station.JumpIndex))
                                        {
                                            Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Station jump index was invalid in XML file " + fileName);
                                            station.Type = StationType.Normal;
                                        }
                                    }
                                    else
                                    {
                                        Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Station jump index was empty in XML file " + fileName);
                                        station.Type = StationType.Normal;
                                    }
                                    break;

                                case "passalarm":
                                    if (!string.IsNullOrEmpty(c.InnerText))
                                    {
                                        if (c.InnerText.ToLowerInvariant() == "1" || c.InnerText.ToLowerInvariant() == "true")
                                        {
                                            passAlarm = true;
                                        }
                                        else
                                        {
                                            passAlarm = false;
                                        }
                                    }
                                    break;

                                case "doors":
                                    Direction door = Direction.Both;
                                    if (!string.IsNullOrEmpty(c.InnerText))
                                    {
                                        door = Parser.FindDirection(c.InnerText, "StationXML:Doors", false, -1, System.IO.Path.GetFileName(fileName));
                                    }
                                    station.OpenLeftDoors  = door == Direction.Left | door == Direction.Both;
                                    station.OpenRightDoors = door == Direction.Right | door == Direction.Both;
                                    break;

                                case "forcedredsignal":
                                    if (!string.IsNullOrEmpty(c.InnerText))
                                    {
                                        if (c.InnerText.ToLowerInvariant() == "1" || c.InnerText.ToLowerInvariant() == "true")
                                        {
                                            station.ForceStopSignal = true;
                                        }
                                        else
                                        {
                                            station.ForceStopSignal = false;
                                        }
                                    }
                                    break;

                                case "system":
                                    switch (c.InnerText.ToLowerInvariant())
                                    {
                                    case "0":
                                    case "ATS":
                                        station.SafetySystem = SafetySystem.Ats;
                                        break;

                                    case "1":
                                    case "ATC":
                                        station.SafetySystem = SafetySystem.Atc;
                                        break;

                                    default:
                                        Plugin.CurrentHost.AddMessage(MessageType.Error, false, "An invalid station safety system was specified in XML file " + fileName);
                                        station.SafetySystem = SafetySystem.Ats;
                                        break;
                                    }
                                    break;

                                case "arrivalsound":
                                    string arrSound  = string.Empty;
                                    double arrRadius = 30.0;
                                    if (!c.ChildNodes.OfType <XmlElement>().Any())
                                    {
                                        foreach (XmlNode cc in c.ChildNodes)
                                        {
                                            switch (c.Name.ToLowerInvariant())
                                            {
                                            case "filename":
                                                try
                                                {
                                                    arrSound = OpenBveApi.Path.CombineFile(Path, cc.InnerText);
                                                }
                                                catch
                                                {
                                                    Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Arrival sound filename is invalid in XML file " + fileName);
                                                }
                                                break;

                                            case "radius":
                                                if (!double.TryParse(cc.InnerText, out arrRadius))
                                                {
                                                    Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Arrival sound radius was invalid in XML file " + fileName);
                                                }
                                                break;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        try
                                        {
                                            arrSound = OpenBveApi.Path.CombineFile(Path, c.InnerText);
                                        }
                                        catch
                                        {
                                            Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Arrival sound filename is invalid in XML file " + fileName);
                                        }
                                    }
                                    if (File.Exists(arrSound))
                                    {
                                        Plugin.CurrentHost.RegisterSound(arrSound, arrRadius, out station.ArrivalSoundBuffer);
                                    }
                                    else
                                    {
                                        Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Arrival sound file does not exist in XML file " + fileName);
                                    }
                                    break;

                                case "stopduration":
                                    double stopDuration;
                                    if (!double.TryParse(c.InnerText, out stopDuration))
                                    {
                                        Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Stop duration is invalid in XML file " + fileName);
                                    }
                                    else
                                    {
                                        if (stopDuration < 5.0)
                                        {
                                            stopDuration = 5.0;
                                        }
                                        station.StopTime = stopDuration;
                                    }
                                    break;

                                case "passengerratio":
                                    double ratio;
                                    if (!double.TryParse(c.InnerText, out ratio))
                                    {
                                        Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Passenger ratio is invalid in XML file " + fileName);
                                    }
                                    else
                                    {
                                        if (ratio < 0.0)
                                        {
                                            Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Passenger ratio must be non-negative in XML file " + fileName);
                                            ratio = 100.0;
                                        }
                                        station.PassengerRatio = ratio * 0.01;
                                    }
                                    break;

                                case "departuresound":
                                    string depSound  = string.Empty;
                                    double depRadius = 30.0;
                                    if (!c.ChildNodes.OfType <XmlElement>().Any())
                                    {
                                        foreach (XmlNode cc in c.ChildNodes)
                                        {
                                            switch (c.Name.ToLowerInvariant())
                                            {
                                            case "filename":
                                                try
                                                {
                                                    depSound = OpenBveApi.Path.CombineFile(Path, cc.InnerText);
                                                }
                                                catch
                                                {
                                                    Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Departure sound filename is invalid in XML file " + fileName);
                                                }
                                                break;

                                            case "radius":
                                                if (!double.TryParse(cc.InnerText, out depRadius))
                                                {
                                                    Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Departure sound radius was invalid in XML file " + fileName);
                                                }
                                                break;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        try
                                        {
                                            depSound = OpenBveApi.Path.CombineFile(Path, c.InnerText);
                                        }
                                        catch
                                        {
                                            Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Departure sound filename is invalid in XML file " + fileName);
                                        }
                                    }
                                    if (File.Exists(depSound))
                                    {
                                        Plugin.CurrentHost.RegisterSound(depSound, depRadius, out station.DepartureSoundBuffer);
                                    }
                                    else
                                    {
                                        Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Departure sound file does not exist in XML file " + fileName);
                                    }
                                    break;

                                case "timetableindex":
                                    if (!PreviewOnly)
                                    {
                                        int ttidx = -1;
                                        if (!string.IsNullOrEmpty(c.InnerText))
                                        {
                                            if (NumberFormats.TryParseIntVb6(c.InnerText, out ttidx))
                                            {
                                                if (ttidx < 0)
                                                {
                                                    Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Timetable index must be non-negative in XML file " + fileName);
                                                    ttidx = -1;
                                                }
                                                else if (ttidx >= daytimeTimetableTextures.Length & ttidx >= nighttimeTimetableTextures.Length)
                                                {
                                                    Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Timetable index references a non-loaded texture in XML file " + fileName);
                                                    ttidx = -1;
                                                }
                                                station.TimetableDaytimeTexture   = ttidx >= 0 & ttidx < daytimeTimetableTextures.Length ? daytimeTimetableTextures[ttidx] : null;
                                                station.TimetableNighttimeTexture = ttidx >= 0 & ttidx < nighttimeTimetableTextures.Length ? nighttimeTimetableTextures[ttidx] : null;
                                                break;
                                            }
                                        }
                                        if (ttidx == -1)
                                        {
                                            if (CurrentStation > 0)
                                            {
                                                station.TimetableDaytimeTexture   = Route.Stations[CurrentStation - 1].TimetableDaytimeTexture;
                                                station.TimetableNighttimeTexture = Route.Stations[CurrentStation - 1].TimetableNighttimeTexture;
                                            }
                                            else if (daytimeTimetableTextures.Length > 0 & nighttimeTimetableTextures.Length > 0)
                                            {
                                                station.TimetableDaytimeTexture   = daytimeTimetableTextures[0];
                                                station.TimetableNighttimeTexture = nighttimeTimetableTextures[0];
                                            }
                                        }
                                    }
                                    break;

                                case "reopendoor":
                                    double reopenDoor;
                                    if (!double.TryParse(c.InnerText, out reopenDoor))
                                    {
                                        Plugin.CurrentHost.AddMessage(MessageType.Error, false, "ReopenDoor is invalid in XML file " + fileName);
                                        reopenDoor = 0.0;
                                    }
                                    else
                                    {
                                        if (reopenDoor < 0.0)
                                        {
                                            Plugin.CurrentHost.AddMessage(MessageType.Error, false, "ReopenDoor must be non-negative in XML file " + fileName);
                                            reopenDoor = 0.0;
                                        }
                                    }
                                    station.ReopenDoor = 0.01 * reopenDoor;
                                    break;

                                case "reopenstationlimit":
                                    int reopenStationLimit;
                                    if (!int.TryParse(c.InnerText, out reopenStationLimit))
                                    {
                                        Plugin.CurrentHost.AddMessage(MessageType.Error, false, "ReopenStationLimit is invalid in XML file " + fileName);
                                        reopenStationLimit = 5;
                                    }
                                    else
                                    {
                                        if (reopenStationLimit < 0)
                                        {
                                            Plugin.CurrentHost.AddMessage(MessageType.Error, false, "ReopenStationLimit must be non-negative in XML file " + fileName);
                                            reopenStationLimit = 0;
                                        }
                                    }
                                    station.ReopenStationLimit = reopenStationLimit;
                                    break;

                                case "interferenceindoor":
                                    double interferenceInDoor;
                                    if (!double.TryParse(c.InnerText, out interferenceInDoor))
                                    {
                                        Plugin.CurrentHost.AddMessage(MessageType.Error, false, "InterferenceInDoor is invalid in XML file " + fileName);
                                        interferenceInDoor = 0.0;
                                    }
                                    else
                                    {
                                        if (interferenceInDoor < 0.0)
                                        {
                                            Plugin.CurrentHost.AddMessage(MessageType.Error, false, "InterferenceInDoor must be non-negative in XML file " + fileName);
                                            interferenceInDoor = 0.0;
                                        }
                                    }
                                    station.InterferenceInDoor = interferenceInDoor;
                                    break;

                                case "maxinterferingobjectrate":
                                    int maxInterferingObjectRate;
                                    if (!int.TryParse(c.InnerText, out maxInterferingObjectRate))
                                    {
                                        Plugin.CurrentHost.AddMessage(MessageType.Error, false, "MaxInterferingObjectRate is invalid in XML file " + fileName);
                                        maxInterferingObjectRate = Plugin.RandomNumberGenerator.Next(1, 99);
                                    }
                                    else
                                    {
                                        if (maxInterferingObjectRate <= 0 || maxInterferingObjectRate >= 100)
                                        {
                                            Plugin.CurrentHost.AddMessage(MessageType.Error, false, "MaxInterferingObjectRate must be positive, less than 100 in XML file " + fileName);
                                            maxInterferingObjectRate = Plugin.RandomNumberGenerator.Next(1, 99);
                                        }
                                    }
                                    station.MaxInterferingObjectRate = maxInterferingObjectRate;
                                    break;

                                case "requeststop":
                                    station.Type     = StationType.RequestStop;
                                    station.StopMode = StationStopMode.AllRequestStop;
                                    foreach (XmlNode cc in c.ChildNodes)
                                    {
                                        switch (cc.Name.ToLowerInvariant())
                                        {
                                        case "aibehaviour":
                                            switch (cc.InnerText.ToLowerInvariant())
                                            {
                                            case "fullspeed":
                                            case "0":
                                                //With this set, the AI driver will not attempt to brake, but pass through at linespeed
                                                stopRequest.FullSpeed = true;
                                                break;

                                            case "normalbrake":
                                            case "1":
                                                //With this set, the AI driver breaks to a near stop whilst passing through the station
                                                stopRequest.FullSpeed = false;
                                                break;
                                            }
                                            break;

                                        case "playeronly":
                                            station.StopMode = StationStopMode.PlayerRequestStop;
                                            break;

                                        case "distance":
                                            if (!string.IsNullOrEmpty(cc.InnerText))
                                            {
                                                double d;
                                                if (!NumberFormats.TryParseDoubleVb6(cc.InnerText, out d))
                                                {
                                                    Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Request stop distance is invalid in XML file " + fileName);
                                                    break;
                                                }
                                                stopRequest.TrackPosition -= Math.Abs(d);
                                            }
                                            break;

                                        case "earlytime":
                                            if (!string.IsNullOrEmpty(cc.InnerText))
                                            {
                                                if (!Parser.TryParseTime(cc.InnerText, out stopRequest.Early.Time))
                                                {
                                                    Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Request stop early time was invalid in XML file " + fileName);
                                                }
                                            }
                                            break;

                                        case "latetime":
                                            if (!string.IsNullOrEmpty(cc.InnerText))
                                            {
                                                if (!Parser.TryParseTime(cc.InnerText, out stopRequest.Late.Time))
                                                {
                                                    Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Request stop late time was invalid in XML file " + fileName);
                                                }
                                            }
                                            break;

                                        case "stopmessage":
                                            if (cc.ChildNodes.OfType <XmlElement>().Any())
                                            {
                                                foreach (XmlNode cd in cc.ChildNodes)
                                                {
                                                    switch (cd.Name.ToLowerInvariant())
                                                    {
                                                    case "early":
                                                        if (!string.IsNullOrEmpty(cd.InnerText))
                                                        {
                                                            stopRequest.Early.StopMessage = cd.InnerText;
                                                        }
                                                        break;

                                                    case "ontime":
                                                        if (!string.IsNullOrEmpty(cd.InnerText))
                                                        {
                                                            stopRequest.OnTime.StopMessage = cd.InnerText;
                                                        }
                                                        break;

                                                    case "late":
                                                        if (!string.IsNullOrEmpty(cd.InnerText))
                                                        {
                                                            stopRequest.Late.StopMessage = cd.InnerText;
                                                        }
                                                        break;

                                                    case "#text":
                                                        stopRequest.Early.StopMessage  = cc.InnerText;
                                                        stopRequest.OnTime.StopMessage = cc.InnerText;
                                                        stopRequest.Late.StopMessage   = cc.InnerText;
                                                        break;
                                                    }
                                                }
                                            }
                                            break;

                                        case "passmessage":
                                            if (cc.ChildNodes.OfType <XmlElement>().Any())
                                            {
                                                foreach (XmlNode cd in cc.ChildNodes)
                                                {
                                                    switch (cd.Name.ToLowerInvariant())
                                                    {
                                                    case "early":
                                                        if (!string.IsNullOrEmpty(cd.InnerText))
                                                        {
                                                            stopRequest.Early.PassMessage = cd.InnerText;
                                                        }
                                                        break;

                                                    case "ontime":
                                                        if (!string.IsNullOrEmpty(cd.InnerText))
                                                        {
                                                            stopRequest.OnTime.PassMessage = cd.InnerText;
                                                        }
                                                        break;

                                                    case "late":
                                                        if (!string.IsNullOrEmpty(cd.InnerText))
                                                        {
                                                            stopRequest.Late.PassMessage = cd.InnerText;
                                                        }
                                                        break;

                                                    case "#text":
                                                        stopRequest.Early.PassMessage  = cc.InnerText;
                                                        stopRequest.OnTime.PassMessage = cc.InnerText;
                                                        stopRequest.Late.PassMessage   = cc.InnerText;
                                                        break;
                                                    }
                                                }
                                            }
                                            break;

                                        case "probability":
                                            foreach (XmlNode cd in cc.ChildNodes)
                                            {
                                                switch (cd.Name.ToLowerInvariant())
                                                {
                                                case "early":
                                                    if (!string.IsNullOrEmpty(cd.InnerText))
                                                    {
                                                        if (!NumberFormats.TryParseIntVb6(cd.InnerText, out stopRequest.Early.Probability))
                                                        {
                                                            Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Request stop early probability was invalid in XML file " + fileName);
                                                        }
                                                    }
                                                    break;

                                                case "ontime":
                                                    if (!string.IsNullOrEmpty(cd.InnerText))
                                                    {
                                                        if (!NumberFormats.TryParseIntVb6(cd.InnerText, out stopRequest.OnTime.Probability))
                                                        {
                                                            Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Request stop ontime probability was invalid in XML file " + fileName);
                                                        }
                                                    }
                                                    break;

                                                case "late":
                                                    if (!string.IsNullOrEmpty(cd.InnerText))
                                                    {
                                                        if (!NumberFormats.TryParseIntVb6(cd.InnerText, out stopRequest.OnTime.Probability))
                                                        {
                                                            Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Request stop late probability was invalid in XML file " + fileName);
                                                        }
                                                    }
                                                    break;

                                                case "#text":
                                                    if (!NumberFormats.TryParseIntVb6(cd.InnerText, out stopRequest.OnTime.Probability))
                                                    {
                                                        Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Request stop probability was invalid in XML file " + fileName);
                                                    }
                                                    break;
                                                }
                                            }

                                            break;

                                        case "maxcars":
                                            if (!NumberFormats.TryParseIntVb6(cc.InnerText, out stopRequest.MaxNumberOfCars))
                                            {
                                                Plugin.CurrentHost.AddMessage(MessageType.Error, false, "Request stop maximum cars was invalid in XML file " + fileName);
                                            }
                                            break;
                                        }
                                    }

                                    break;
                                }
                            }
                        }
                    }
                    return(station);
                }
            }
            //We couldn't find any valid XML, so return false
            throw new InvalidDataException();
        }
Exemple #25
0
        internal static void Main(string[] args)
        {
            CurrentHost = new Host();
            // file system
            FileSystem = FileSystem.FromCommandLineArgs(args, CurrentHost);
            FileSystem.CreateFileSystem();
            Renderer     = new NewRenderer();
            CurrentRoute = new CurrentRoute(Renderer);
            Sounds       = new Sounds();

            Options.LoadOptions();
            Plugins.LoadPlugins();
            // command line arguments
            StringBuilder objectsToLoad = new StringBuilder();

            if (args.Length != 0)
            {
                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i] != null)
                    {
                        if (System.IO.File.Exists(args[i]))
                        {
                            for (int j = 0; j < CurrentHost.Plugins.Length; j++)
                            {
                                if (CurrentHost.Plugins[j].Object != null && CurrentHost.Plugins[j].Object.CanLoadObject(args[i]))
                                {
                                    objectsToLoad.Append(args[i] + " ");
                                    continue;
                                }

                                if (CurrentHost.Plugins[j].Route != null && CurrentHost.Plugins[j].Route.CanLoadRoute(args[i]))
                                {
                                    if (string.IsNullOrEmpty(CurrentRouteFile))
                                    {
                                        CurrentRouteFile       = args[i];
                                        processCommandLineArgs = true;
                                    }
                                }
                            }
                        }
                        else if (args[i].ToLowerInvariant() == "/enablehacks")
                        {
                            //Deliberately undocumented option for debugging use
                            Interface.CurrentOptions.EnableBveTsHacks = true;
                            for (int j = 0; j < CurrentHost.Plugins.Length; j++)
                            {
                                if (CurrentHost.Plugins[j].Object != null)
                                {
                                    CompatabilityHacks enabledHacks = new CompatabilityHacks
                                    {
                                        BveTsHacks        = true,
                                        CylinderHack      = false,
                                        BlackTransparency = true
                                    };
                                    CurrentHost.Plugins[j].Object.SetCompatibilityHacks(enabledHacks);
                                }
                            }
                        }
                    }
                }
            }

            if (objectsToLoad.Length != 0)
            {
                string File = System.IO.Path.Combine(Application.StartupPath, "ObjectViewer.exe");
                if (System.IO.File.Exists(File))
                {
                    System.Diagnostics.Process.Start(File, objectsToLoad.ToString());
                    if (string.IsNullOrEmpty(CurrentRouteFile))
                    {
                        //We only supplied objects, so launch Object Viewer instead
                        Environment.Exit(0);
                    }
                }
            }

            var options = new ToolkitOptions();

            Plugins.LoadPlugins();
            options.Backend = PlatformBackend.PreferX11;
            Toolkit.Init(options);
            string folder = Program.FileSystem.GetDataFolder("Languages");

            Translations.LoadLanguageFiles(folder);
            Interface.CurrentOptions.ObjectOptimizationBasicThreshold = 1000;
            Interface.CurrentOptions.ObjectOptimizationFullThreshold  = 250;
            // application
            currentGraphicsMode = new GraphicsMode(new ColorFormat(8, 8, 8, 8), 24, 8, Interface.CurrentOptions.AntiAliasingLevel);
            if (Renderer.Screen.Width == 0 || Renderer.Screen.Height == 0)
            {
                //Duff values saved, so reset to something sensible else we crash
                Renderer.Screen.Width  = 1024;
                Renderer.Screen.Height = 768;
            }
            Renderer.CameraTrackFollower            = new TrackFollower(Program.CurrentHost);
            currentGameWindow                       = new RouteViewer(Renderer.Screen.Width, Renderer.Screen.Height, currentGraphicsMode, "Route Viewer", GameWindowFlags.Default);
            currentGameWindow.Visible               = true;
            currentGameWindow.TargetUpdateFrequency = 0;
            currentGameWindow.TargetRenderFrequency = 0;
            currentGameWindow.Title                 = "Route Viewer";
            processCommandLineArgs                  = true;
            currentGameWindow.Run();
            //Unload
            Sounds.Deinitialize();
        }
Exemple #26
0
        private static void Main(string[] args)
        {
            // --- load options and controls ---
            try
            {
                FileSystem = FileSystem.FromCommandLineArgs(args, CurrentHost);
                FileSystem.CreateFileSystem();
                Interface.LoadOptions();
            }
            catch
            {
                // ignored
            }
            //Switch between SDL2 and native backends; use native backend by default
            var options = new ToolkitOptions();

            if (Interface.CurrentOptions.PreferNativeBackend)
            {
                options.Backend = PlatformBackend.PreferNative;
            }
            Toolkit.Init(options);

            // Add handler for UI thread exceptions
            Application.ThreadException += (CrashHandler.UIThreadException);

            // Force all WinForms errors to go through handler
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            // This handler is for catching non-UI thread exceptions
            AppDomain.CurrentDomain.UnhandledException += (CrashHandler.CurrentDomain_UnhandledException);


            //Determine the current CPU architecture-
            //ARM will generally only support OpenGL-ES
            PortableExecutableKinds peKind;

            typeof(object).Module.GetPEKind(out peKind, out CurrentCPUArchitecture);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            CurrentHost = new Host();
            if (IntPtr.Size == 4)
            {
                Joysticks = new JoystickManager32();
            }
            else
            {
                Joysticks = new JoystickManager64();
            }
            try {
                FileSystem = FileSystem.FromCommandLineArgs(args, CurrentHost);
                FileSystem.CreateFileSystem();
            } catch (Exception ex) {
                MessageBox.Show(Translations.GetInterfaceString("errors_filesystem_invalid") + Environment.NewLine + Environment.NewLine + ex.Message, Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }

            Renderer     = new NewRenderer(CurrentHost, Interface.CurrentOptions, FileSystem);
            Sounds       = new Sounds();
            CurrentRoute = new CurrentRoute(CurrentHost, Renderer);

            //Platform specific startup checks
            // --- Check if we're running as root, and prompt not to ---
            if (CurrentHost.Platform == HostPlatform.GNULinux && (getuid() == 0 || geteuid() == 0))
            {
                MessageBox.Show(
                    "You are currently running as the root user, or via the sudo command." + System.Environment.NewLine +
                    "This is a bad idea, please dont!", Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }



            TrainManager = new TrainManager(CurrentHost, Renderer, Interface.CurrentOptions, FileSystem);

            // --- load language ---
            string folder = Program.FileSystem.GetDataFolder("Languages");

            Translations.LoadLanguageFiles(folder);

            folder = Program.FileSystem.GetDataFolder("Cursors");
            Cursors.LoadCursorImages(folder);

            Interface.LoadControls(null, out Interface.CurrentControls);
            folder = Program.FileSystem.GetDataFolder("Controls");
            string file = OpenBveApi.Path.CombineFile(folder, "Default keyboard assignment.controls");

            Control[] controls;
            Interface.LoadControls(file, out controls);
            Interface.AddControls(ref Interface.CurrentControls, controls);

            InputDevicePlugin.LoadPlugins(Program.FileSystem);

            // --- check the command-line arguments for route and train ---
            formMain.MainDialogResult result = new formMain.MainDialogResult();
            CommandLine.ParseArguments(args, ref result);
            // --- check whether route and train exist ---
            if (result.RouteFile != null)
            {
                if (!System.IO.File.Exists(result.RouteFile))
                {
                    result.RouteFile = null;
                }
            }
            if (result.TrainFolder != null)
            {
                if (!System.IO.Directory.Exists(result.TrainFolder))
                {
                    result.TrainFolder = null;
                }
            }
            // --- if a route was provided but no train, try to use the route default ---
            if (result.RouteFile != null & result.TrainFolder == null)
            {
                string error;
                if (!CurrentHost.LoadPlugins(FileSystem, Interface.CurrentOptions, out error, TrainManager, Renderer))
                {
                    MessageBox.Show(error, @"OpenBVE", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    throw new Exception("Unable to load the required plugins- Please reinstall OpenBVE");
                }
                Game.Reset(false);
                bool loaded = false;
                for (int i = 0; i < Program.CurrentHost.Plugins.Length; i++)
                {
                    if (Program.CurrentHost.Plugins[i].Route != null && Program.CurrentHost.Plugins[i].Route.CanLoadRoute(result.RouteFile))
                    {
                        object Route = (object)Program.CurrentRoute;                         //must cast to allow us to use the ref keyword.
                        Program.CurrentHost.Plugins[i].Route.LoadRoute(result.RouteFile, result.RouteEncoding, null, null, null, true, ref Route);
                        Program.CurrentRoute = (CurrentRoute)Route;
                        Program.Renderer.Lighting.OptionAmbientColor  = CurrentRoute.Atmosphere.AmbientLightColor;
                        Program.Renderer.Lighting.OptionDiffuseColor  = CurrentRoute.Atmosphere.DiffuseLightColor;
                        Program.Renderer.Lighting.OptionLightPosition = CurrentRoute.Atmosphere.LightPosition;
                        loaded = true;
                        break;
                    }
                }

                if (!CurrentHost.UnloadPlugins(out error))
                {
                    MessageBox.Show(error, @"OpenBVE", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                if (!loaded)
                {
                    throw new Exception("No plugins capable of loading routefile " + result.RouteFile + " were found.");
                }
                if (!string.IsNullOrEmpty(Interface.CurrentOptions.TrainName))
                {
                    folder = System.IO.Path.GetDirectoryName(result.RouteFile);
                    while (true)
                    {
                        string trainFolder = OpenBveApi.Path.CombineDirectory(folder, "Train");
                        if (System.IO.Directory.Exists(trainFolder))
                        {
                            try
                            {
                                folder = OpenBveApi.Path.CombineDirectory(trainFolder, Interface.CurrentOptions.TrainName);
                            }
                            catch (Exception ex)
                            {
                                if (ex is ArgumentException)
                                {
                                    break;
                                }
                            }
                            if (System.IO.Directory.Exists(folder))
                            {
                                file = OpenBveApi.Path.CombineFile(folder, "train.dat");
                                if (System.IO.File.Exists(file))
                                {
                                    result.TrainFolder   = folder;
                                    result.TrainEncoding = System.Text.Encoding.UTF8;
                                    for (int j = 0; j < Interface.CurrentOptions.TrainEncodings.Length; j++)
                                    {
                                        if (string.Compare(Interface.CurrentOptions.TrainEncodings[j].Value, result.TrainFolder, StringComparison.InvariantCultureIgnoreCase) == 0)
                                        {
                                            result.TrainEncoding = System.Text.Encoding.GetEncoding(Interface.CurrentOptions.TrainEncodings[j].Codepage);
                                            break;
                                        }
                                    }
                                }
                            }
                            break;
                        }
                        if (folder == null)
                        {
                            continue;
                        }
                        System.IO.DirectoryInfo info = System.IO.Directory.GetParent(folder);
                        if (info != null)
                        {
                            folder = info.FullName;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                Game.Reset(false);
            }

            // --- show the main menu if necessary ---
            if (result.RouteFile == null | result.TrainFolder == null)
            {
                Joysticks.RefreshJoysticks();

                if (CurrentHost.Platform == HostPlatform.AppleOSX && IntPtr.Size != 4)
                {
                    //WinForms are not supported on 64-bit Apple, so show the experimental GL menu
                    result.ExperimentalGLMenu = true;
                }
                else
                {
                    if (!result.ExperimentalGLMenu)
                    {
                        result = formMain.ShowMainDialog(result);
                    }
                }
            }
            else
            {
                result.Start = true;
                //Apply translations
                Translations.SetInGameLanguage(Translations.CurrentLanguageCode);
            }

            if (result.ExperimentalGLMenu)
            {
                result.Start       = true;
                result.RouteFile   = null;
                result.TrainFolder = null;
            }

            // --- start the actual program ---
            if (result.Start)
            {
                if (Initialize())
                {
                                        #if !DEBUG
                    try {
                                                #endif
                    MainLoop.StartLoopEx(result);
                                                #if !DEBUG
                }
                catch (Exception ex) {
                    bool found = false;
                    for (int i = 0; i < TrainManager.Trains.Length; i++)
                    {
                        if (TrainManager.Trains[i] != null && TrainManager.Trains[i].Plugin != null)
                        {
                            if (TrainManager.Trains[i].Plugin.LastException != null)
                            {
                                CrashHandler.LoadingCrash(ex.Message, true);
                                MessageBox.Show("The train plugin " + TrainManager.Trains[i].Plugin.PluginTitle + " caused a runtime exception: " + TrainManager.Trains[i].Plugin.LastException.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                                found            = true;
                                RestartArguments = "";
                                break;
                            }
                        }
                    }
                    if (!found)
                    {
                        if (ex is System.DllNotFoundException)
                        {
                            Interface.AddMessage(MessageType.Critical, false, "The required system library " + ex.Message + " was not found on the system.");
                            switch (ex.Message)
                            {
                            case "libopenal.so.1":
                                MessageBox.Show("openAL was not found on this system. \n Please install libopenal1 via your distribtion's package management system.", Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                                break;

                            default:
                                MessageBox.Show("The required system library " + ex.Message + " was not found on this system.", Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                                break;
                            }
                        }
                        else
                        {
                            Interface.AddMessage(MessageType.Critical, false, "The route and train loader encountered the following critical error: " + ex.Message);
                            CrashHandler.LoadingCrash(ex + Environment.StackTrace, false);
                        }
                        RestartArguments = "";
                    }
                }
#endif
                }
                Deinitialize();
            }
            // --- restart the program if necessary ---
            if (RestartArguments != null)
            {
                string arguments;
                if (FileSystem.RestartArguments.Length != 0 & RestartArguments.Length != 0)
                {
                    arguments = FileSystem.RestartArguments + " " + RestartArguments;
                }
                else
                {
                    arguments = FileSystem.RestartArguments + RestartArguments;
                }
                try {
                    System.Diagnostics.Process.Start(System.IO.File.Exists(FileSystem.RestartProcess) ? FileSystem.RestartProcess : Application.ExecutablePath, arguments);
                } catch (Exception ex) {
                    MessageBox.Show(ex.Message + "\n\nProcess = " + FileSystem.RestartProcess + "\nArguments = " + arguments, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }