Ejemplo n.º 1
0
        // Detects the underlying OS and runtime.
        internal static void Init(ToolkitOptions options)
        {
            lock (InitLock)
            {
                if (!initialized)
                {
                    RunningOnMono    = DetectMono();
                    RunningOnWindows = DetectWindows();
                    if (!RunningOnWindows)
                    {
                        DetectUnix(out runningOnUnix, out runningOnLinux, out runningOnMacOS);
                    }

                    if ((runningOnLinux) || options.Backend == PlatformBackend.PreferX11)
                    {
                        RunningOnX11 = DetectX11();
                    }

                    initialized = true;
                    Debug.Print("Detected configuration: {0} / {1}",
                                RunningOnWindows ? "Windows" : RunningOnLinux ? "Linux" : RunningOnMacOS ? "MacOS" :
                                runningOnUnix ? "Unix" : RunningOnX11 ? "X11" : "Unknown Platform",
                                RunningOnMono ? "Mono" : ".Net");
                }
            }
        }
Ejemplo n.º 2
0
        public FastEngine(string windowName, int width, int height, int fps)
        {
            // disabling HiDPI support
            var options = new ToolkitOptions
            {
                EnableHighResolution = false
            };
            OpenTK.Toolkit.Init(options);
            window = new GameWindow (width, height, OpenTK.Graphics.GraphicsMode.Default, windowName);

            // call it AFTER GameWindow initialization to avoid problems with Windows.Forms
            this.Initialize (windowName, width, height, fps);

            // create a new texture
            texture = GL.GenTexture ();
            // use the texure (as a 2d one)
            GL.BindTexture (TextureTarget.Texture2D, texture);
            GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
            GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
            this.textureRect = new Rectangle (0, 0, width, height);

            GL.Enable (EnableCap.Texture2D);

            window.Resize += this.Game_Resize;
            window.RenderFrame += this.Game_RenderFrame;

            // initialize OpenAL context (No ! do it lazily)
            // audioContext = new AudioContext ();
        }
Ejemplo n.º 3
0
        // Detects the underlying OS and runtime.
        internal static void Init(ToolkitOptions options)
        {
            lock (InitLock)
            {
                if (!initialized)
                {
#if ANDROID || IPHONE
                    RunningOnMono = true;
#else
                    RunningOnMono    = DetectMono();
                    RunningOnWindows = DetectWindows();
                    if (!RunningOnWindows)
                    {
                        DetectUnix(out runningOnUnix, out runningOnLinux, out runningOnMacOS);
                    }

                    //if (options.Backend == PlatformBackend.Default)
                    //{
                    //    RunningOnSdl2 = DetectSdl2();
                    //}

                    if ((runningOnLinux && !RunningOnSdl2) || options.Backend == PlatformBackend.PreferX11)
                    {
                        RunningOnX11 = DetectX11();
                    }

                    initialized = true;
#endif
                    Debug.Print("Detected configuration: {0} / {1}",
                                RunningOnWindows ? "Windows" : RunningOnLinux ? "Linux" : RunningOnMacOS ? "MacOS" :
                                runningOnUnix ? "Unix" : RunningOnX11 ? "X11" : "Unknown Platform",
                                RunningOnMono ? "Mono" : ".Net");
                }
            }
        }
Ejemplo n.º 4
0
        static void LaunchExample(string type)
        {
            try
            {
                if (File.Exists("debug.log"))
                    File.Delete("debug.log");
                if (File.Exists("trace.log"))
                    File.Delete("trace.log");
            }
            catch (Exception e)
            {
                Trace.WriteLine(String.Format("Could not access debug.log", e.ToString()));
            }

            ToolkitOptions options = ToolkitOptions.Default;
            if (type.Contains("GLControl") || type.Contains("Form"))
            {
                // SDL does not currently support embedding in foreign windows
                // such as GLControl. We need to use a native OpenTK.Platform
                // backend in that case. This hack is specific to the example-browser
                // architecture - you do not need to do anything like this in your
                // own code (it will just work).
                options = new ToolkitOptions
                {
                    Backend = PlatformBackend.PreferNative
                };
            }

            using (TextWriterTraceListener dbg = new TextWriterTraceListener("debug.log"))
            using (Toolkit.Init(options))
            {
                Trace.Listeners.Add(dbg);

                try
                {
                    var example = Type.GetType(type);
                    if (example != null)
                    {
                        example.InvokeMember("Main",
                            BindingFlags.InvokeMethod | BindingFlags.Static |
                            BindingFlags.Public | BindingFlags.NonPublic,
                            null, null, null);
                    }
                }
                catch (Exception e)
                {
                    Trace.WriteLine(String.Format("Exception occured in example {0}: {1}",
                        type, e.ToString()));
                }

                Trace.Listeners.Remove(dbg);

                dbg.Flush();
                dbg.Close();
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Initializes OpenTK with the specified options. Use this method
        /// to influence the OpenTK.Platform implementation that will be used.
        /// </summary>
        /// <remarks>
        /// <para>
        /// You *must* call this method if you are combining OpenTK with a
        /// third-party windowing toolkit (e.g. GTK#). In this case, this should be the
        /// first method called by your application:
        /// <code>
        /// static void Main()
        /// {
        ///     using (OpenTK.Toolkit.Init())
        ///     {
        ///      ...
        ///     }
        /// }
        /// </code>
        /// </para>
        /// <para>
        /// The reason is that some toolkits do not configure the underlying platform
        /// correctly or configure it in a way that is incompatible with OpenTK.
        /// Calling this method first ensures that OpenTK is given the chance to
        /// initialize itself and configure the platform correctly.
        /// </para>
        /// </remarks>
        /// <param name="options">A <c>ToolkitOptions</c> instance
        /// containing the desired options.</param>
        /// <returns>
        /// An IDisposable instance that you can use to dispose of the resources
        /// consumed by OpenTK.
        /// </returns>
        public static Toolkit Init(ToolkitOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            lock (InitLock)
            {
                if (!initialized)
                {
                    initialized = true;
                    Configuration.Init(options);
                    Options = options;

                    // The actual initialization takes place in the
                    // platform-specific factory constructors.
                    toolkit = new Toolkit(new Factory());
                }
                return(toolkit);
            }
        }
Ejemplo n.º 6
0
        protected override void InitPlugin()
        {
            base.InitPlugin();

            mainThread = Thread.CurrentThread;

            // Initialize OpenTK
            {
                bool inEditor = DualityApp.ExecEnvironment == DualityApp.ExecutionEnvironment.Editor;
                ToolkitOptions options = new ToolkitOptions
                {
                    // Prefer the native backend in the editor, because it supports GLControl. SDL doesn't.
                    Backend = inEditor ? PlatformBackend.PreferNative : PlatformBackend.Default,
                    // Disable High Resolution support in the editor, because it's not DPI-Aware
                    EnableHighResolution = !inEditor
                };
                Toolkit.Init(options);
            }

            // Register global / non-windowbound input devices
            GlobalGamepadInputSource.UpdateAvailableDecives(DualityApp.Gamepads);
            GlobalJoystickInputSource.UpdateAvailableDecives(DualityApp.Joysticks);
        }
Ejemplo n.º 7
0
        internal static void InitOpenTK()
        {
            if (openTKInitialized) return;
            openTKInitialized = true;

            Assembly execAssembly = Assembly.GetEntryAssembly() ?? typeof(DualityApp).Assembly;
            string execAssemblyDir = PathOp.GetFullPath(PathOp.GetDirectoryName(execAssembly.Location));

            bool inEditor = DualityApp.ExecEnvironment == DualityApp.ExecutionEnvironment.Editor;
            bool isWindows =
                Environment.OSVersion.Platform == PlatformID.Win32NT ||
                Environment.OSVersion.Platform == PlatformID.Win32S ||
                Environment.OSVersion.Platform == PlatformID.Win32Windows ||
                Environment.OSVersion.Platform == PlatformID.WinCE;
            bool genericFolderSDL = isWindows && !FileOp.Exists("SDL2.dll") && !FileOp.Exists(PathOp.Combine(execAssemblyDir, "SDL2.dll"));

            ToolkitOptions options = new ToolkitOptions
            {
                // Prefer the native backend in the editor, because it supports GLControl. SDL doesn't.
                // Also, never use SDL if it isn't in the local game folder, because it might be in PATH on some machines.
                Backend = (inEditor || genericFolderSDL) ? PlatformBackend.PreferNative : PlatformBackend.Default,
                // Disable High Resolution support in the editor, because it's not DPI-Aware
                EnableHighResolution = !inEditor
            };

            Log.Core.Write("Initializing OpenTK...");
            Log.Core.PushIndent();
            Log.Core.Write(
                "Platform Backend: {0}" + Environment.NewLine +
                "EnableHighResolution: {1}",
                options.Backend,
                options.EnableHighResolution);

            Toolkit.Init(options);

            Log.Core.PopIndent();
        }
Ejemplo n.º 8
0
        // Detects the underlying OS and runtime.
        internal static void Init(ToolkitOptions options)
        {
            lock (InitLock)
            {
                if (!initialized)
                {
#if ANDROID
                    runningOnMono = true;
                    runningOnAnroid = true;
#elif IPHONE
                    runningOnMono = true;
                    runningOnIOS = true;
#else
                    runningOnMono = DetectMono();
                    runningOnWindows = DetectWindows();
                    if (!runningOnWindows)
                    {
                        DetectUnix(out runningOnUnix, out runningOnLinux, out runningOnMacOS);
                    }

                    if (options.Backend == PlatformBackend.Default)
                    {
                        RunningOnSdl2 = DetectSdl2();
                    }
                    
                    if ((runningOnLinux && !RunningOnSdl2) || options.Backend == PlatformBackend.PreferX11)
                    {
                        runningOnX11 = DetectX11();
                    }

                    initialized = true;
#endif
                    Debug.Print("Detected configuration: {0} / {1}",
                        RunningOnWindows ? "Windows" : RunningOnLinux ? "Linux" : RunningOnMacOS ? "MacOS" :
                        runningOnUnix ? "Unix" : RunningOnX11 ? "X11" : "Unknown Platform",
                        RunningOnMono ? "Mono" : ".Net");
                }
            }
        }
Ejemplo n.º 9
0
 static ToolkitOptions()
 {
     Default = new ToolkitOptions();
 }
Ejemplo n.º 10
0
 static ToolkitOptions()
 {
     Default = new ToolkitOptions();
     Default.EnableHighResolution = true;
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Initializes OpenTK with the specified options. Use this method
        /// to influence the OpenTK.Platform implementation that will be used.
        /// </summary>
        /// <remarks>
        /// <para>
        /// You *must* call this method if you are combining OpenTK with a
        /// third-party windowing toolkit (e.g. GTK#). In this case, this should be the
        /// first method called by your application:
        /// <code>
        /// static void Main()
        /// {
        ///     using (OpenTK.Toolkit.Init())
        ///     {
        ///      ...
        ///     }
        /// }
        /// </code>
        /// </para>
        /// <para>
        /// The reason is that some toolkits do not configure the underlying platform
        /// correctly or configure it in a way that is incompatible with OpenTK.
        /// Calling this method first ensures that OpenTK is given the chance to
        /// initialize itself and configure the platform correctly.
        /// </para>
        /// </remarks>
        /// <param name="options">A <c>ToolkitOptions</c> instance
        /// containing the desired options.</param>
        /// <returns>
        /// An IDisposable instance that you can use to dispose of the resources
        /// consumed by OpenTK.
        /// </returns>
        public static Toolkit Init(ToolkitOptions options)
        {
            if (options == null)
                throw new ArgumentNullException("options");

            lock (InitLock)
            {
                if (!initialized)
                {
                    initialized = true;
                    Configuration.Init(options);
                    Options = options;

                    // The actual initialization takes place in the
                    // platform-specific factory constructors.
                    toolkit = new Toolkit(new Factory());
                }
                return toolkit;
            }
        }
Ejemplo n.º 12
0
		private static void Main(string[] args) {

#if !DEBUG            
			// Add handler for UI thread exceptions
			Application.ThreadException += new ThreadExceptionEventHandler(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 += new UnhandledExceptionEventHandler(CrashHandler.CurrentDomain_UnhandledException);
#endif

			//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;
			CurrentHost = new Host();
			try {
				FileSystem = FileSystem.FromCommandLineArgs(args);
				FileSystem.CreateFileSystem();
			} catch (Exception ex) {
				MessageBox.Show(Interface.GetInterfaceString("errors_filesystem_invalid") + Environment.NewLine + Environment.NewLine + ex.Message, Interface.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
				return;
			}

			//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!", Interface.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
				}
			}
			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.", Interface.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);

					ProcessStartInfo info = new ProcessStartInfo(System.IO.Path.Combine(FileSystem.DataFolder, "Dependencies\\Win32\\oalinst.exe"));
					info.UseShellExecute = true;
					if (Environment.OSVersion.Version.Major >= 6)
					{
						info.Verb = "runas";
					}
					try
					{
						System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
						p.WaitForExit();
					}
					catch (Win32Exception)
					{
						MessageBox.Show(
						"An error occured during OpenAL installation....", Interface.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");
				try
				{
					string[] LanguageFiles = Directory.GetFiles(folder, "*.cfg");
					foreach (var File in LanguageFiles)
					{
						Interface.AddLanguage(File);
					}
				}
				catch
				{
					MessageBox.Show(@"An error occured whilst attempting to load the default language files.");
					//Environment.Exit(0);
				}
			}
			Interface.LoadControls(null, out Interface.CurrentControls);
			{
				string 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);
			}
			
			// --- 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) {
				bool isRW = string.Equals(System.IO.Path.GetExtension(result.RouteFile), ".rw", StringComparison.OrdinalIgnoreCase);
				CsvRwRouteParser.ParseRoute(result.RouteFile, isRW, result.RouteEncoding, null, null, null, true);
				if (!string.IsNullOrEmpty(Game.TrainName)) {
					string folder = System.IO.Path.GetDirectoryName(result.RouteFile);
					while (true) {
						string trainFolder = OpenBveApi.Path.CombineDirectory(folder, "Train");
						if (System.IO.Directory.Exists(trainFolder)) {
							folder = OpenBveApi.Path.CombineDirectory(trainFolder, Game.TrainName);
							if (System.IO.Directory.Exists(folder)) {
								string file = OpenBveApi.Path.CombineFile(folder, "train.dat");
								if (System.IO.File.Exists(file)) {
									result.TrainFolder = folder;
									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
				Interface.SetInGameLanguage(Interface.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;
						//Thread.Sleep(20);
						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)
						{
							MessageBox.Show("The route and train loader encountered the following critical error: " + Environment.NewLine + ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
							CrashHandler.LoadingCrash(ex.ToString(), 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(FileSystem.RestartProcess, arguments);
				} catch (Exception ex) {
					MessageBox.Show(ex.Message + "\n\nProcess = " + FileSystem.RestartProcess + "\nArguments = " + arguments, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
		}
Ejemplo n.º 13
0
 static ToolkitOptions()
 {
     Default = new ToolkitOptions();
     Default.EnableHighResolution = true;
 }