Beispiel #1
0
 public static void InitialSetup()
 {
     // FOR THE LOVE OF GOD PLEASE LET THIS WORK
     AudioDevice = Alc.OpenDevice (null); // Default device
     if (AudioDevice != null) {
         AudioCtx = Alc.CreateContext(AudioDevice, (int[])null);
         if(AudioCtx != ContextHandle.Zero)
         {
             Alc.GetError(AudioDevice);
             if(Alc.MakeContextCurrent( AudioCtx ))
             {
                 //LoadWaveFile ("camprespite_loop", "camprespite_loop.wav");
                 LoadWaveFile ("last_human_loop", "last_human_loop_limited.wav");//.DurationAdjust(0.01);
                 LoadWaveFile ("induction_loop", "induction_loop.wav");
                 LoadWaveFile ("sfx_bullet_impact", "sfx_bullet_impact.wav");
                 LoadWaveFile ("sfx_player_land_two_feet", "sfx_player_land_two_feet.wav");
                 LoadWaveFile ("sfx_shoot_gun", "sfx_shoot_gun.wav");
                 LoadWaveFile ("win", "win.wav");
             }
             else
                 throw new Exception("Failed to set current audio context");
         }
         else
             throw new Exception("Failed to create audio context.");
     }
     else
         throw new Exception("Failed to open default audio device.");
 }
Beispiel #2
0
		// initialize
		internal static void Initialize() {
			// openal
			OpenAlDevice = Alc.OpenDevice(null);
			if (OpenAlDevice != IntPtr.Zero) {
                OpenAlContext = Alc.CreateContext(OpenAlDevice, (int[])null);
				if (OpenAlContext != ContextHandle.Zero) {
					Alc.MakeContextCurrent(OpenAlContext);
					AL.SpeedOfSound(343.0f);
					AL.DistanceModel(ALDistanceModel.None);
				} else {
					Alc.CloseDevice(OpenAlDevice);
					OpenAlDevice = IntPtr.Zero;
					System.Windows.Forms.MessageBox.Show("The sound device could be opened, but the sound context could not be created.", "openBVE", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Hand);
				}
			} else {
				OpenAlContext = ContextHandle.Zero;
				System.Windows.Forms.MessageBox.Show("The sound device could not be opened.", "openBVE", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Hand);
			}
			// outer radius
			switch (Interface.CurrentOptions.SoundRange) {
				case Interface.SoundRange.Low:
					OuterRadiusFactorMinimum = 2.0;
					OuterRadiusFactorMaximum = 8.0;
					break;
				case Interface.SoundRange.Medium:
					OuterRadiusFactorMinimum = 4.0;
					OuterRadiusFactorMaximum = 16.0;
					break;
				case Interface.SoundRange.High:
					OuterRadiusFactorMinimum = 8.0;
					OuterRadiusFactorMaximum = 32.0;
					break;
			}
			OuterRadiusFactor = OuterRadiusFactorMaximum;
		}
 public override IGraphicsContext CreateGLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
 {
     X11WindowInfo x11_win = (X11WindowInfo)window;
     //EglWindowInfo egl_win = new OpenTK.Platform.Egl.EglWindowInfo(x11_win.WindowHandle, Egl.GetDisplay(x11_win.Display));
     EglWindowInfo egl_win = new OpenTK.Platform.Egl.EglWindowInfo(x11_win.WindowHandle, Egl.GetDisplay(new IntPtr(0)));
     return new EglContext(handle, egl_win, shareContext, major, minor, flags);
 }
 public override IGraphicsContext CreateGLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
 {
     WinWindowInfo win_win = (WinWindowInfo)window;
     IntPtr egl_display = GetDisplay(win_win.DeviceContext);
     EglWindowInfo egl_win = new OpenTK.Platform.Egl.EglWindowInfo(win_win.WindowHandle, egl_display);
     return new EglContext(handle, egl_win, shareContext, major, minor, flags);
 }
Beispiel #5
0
 public override IGraphicsContext CreateGLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
 {
     WinWindowInfo winWindowInfo = (WinWindowInfo) window;
       IntPtr display = this.GetDisplay(winWindowInfo.DeviceContext);
       EglWindowInfo window1 = new EglWindowInfo(winWindowInfo.WindowHandle, display);
       return (IGraphicsContext) new EglContext(handle, window1, shareContext, major, minor, flags);
 }
        public void CreateContext(bool direct, IGLContext source)
        {
            Debug.WriteLine(String.Format("OpenGL context is bound to handle: {0}", this.windowInfo.Handle));

            Debug.Write("Creating render context... ");
            // Do not rely on OpenTK.Platform.Windows.Wgl - the context is not ready yet,
            // and Wgl extensions will fail to load.
            renderContext = new ContextHandle(Wgl.Imports.CreateContext(deviceContext));
            if (renderContext == IntPtr.Zero)
                throw new ApplicationException("Could not create OpenGL render context (Wgl.CreateContext() return 0).");
            
            Debug.WriteLine(String.Format("done! (id: {0})", renderContext));

            Wgl.Imports.MakeCurrent(deviceContext, renderContext);
            Wgl.LoadAll();
            GL.LoadAll();
            Glu.LoadAll();

            vsync_supported = Wgl.Arb.SupportsExtension(this.deviceContext, "WGL_EXT_swap_control") &&
                Wgl.Load("wglGetSwapIntervalEXT") && Wgl.Load("wglSwapIntervalEXT");

            if (source != null)
            {
                Debug.Print("Sharing state with context {0}", (source as IGLContextInternal).Context);
                Wgl.Imports.ShareLists(renderContext, (source as IGLContextInternal).Context);
            }
        }
Beispiel #7
0
        static WinGLContext()
        {
            // Dynamically load the OpenGL32.dll in order to use the extension loading capabilities of Wgl.
            if (opengl32Handle == IntPtr.Zero)
            {
                opengl32Handle = Functions.LoadLibrary(opengl32Name);
                if (opengl32Handle == IntPtr.Zero)
                    throw new ApplicationException(String.Format("LoadLibrary(\"{0}\") call failed with code {1}",
                                                                 opengl32Name, Marshal.GetLastWin32Error()));
                Debug.WriteLine(String.Format("Loaded opengl32.dll: {0}", opengl32Handle));
            }

            // We need to create a temp context in order to load
            // wgl extensions (e.g. for multisampling or GL3).
            // We cannot rely on OpenTK.Platform.Wgl until we
            // create the context and call Wgl.LoadAll().
            Debug.Print("Creating temporary context for wgl extensions.");
            using (INativeWindow native = new NativeWindow())
            {
                // Create temporary context and load WGL entry points
                WinWindowInfo window = native.WindowInfo as WinWindowInfo;
                ContextHandle temp_context = new ContextHandle(Wgl.Imports.CreateContext(window.DeviceContext));
                Wgl.Imports.MakeCurrent(window.DeviceContext, temp_context.Handle);
                Wgl.LoadAll();

                // Query graphics modes
                ModeSelector = new WinGraphicsMode(temp_context, window.DeviceContext);
                
                // Destroy temporary context
                Wgl.Imports.MakeCurrent(IntPtr.Zero, IntPtr.Zero);
                Wgl.Imports.DeleteContext(temp_context.Handle);
                wgl_loaded = true;
            }
        }
        internal iPhoneOSGraphicsContext(ContextHandle handle, IWindowInfo window, IGraphicsContext sharedContext, int major, int minor, GraphicsContextFlags flags)
        {
            // ignore mode, window

            iPhoneOSGraphicsContext shared = sharedContext as iPhoneOSGraphicsContext;

            EAGLRenderingAPI version = 0;
            if (major == 1 && minor == 1)
                version = EAGLRenderingAPI.OpenGLES1;
            else if (major == 2 && minor == 0)
                version = EAGLRenderingAPI.OpenGLES2;
            else if (major == 3 && minor == 0)
                version = EAGLRenderingAPI.OpenGLES3;
            else
                throw new ArgumentException (string.Format("Unsupported GLES version {0}.{1}.", major, minor));

            if (handle.Handle == IntPtr.Zero) {
                EAGLContext = shared != null && shared.EAGLContext != null
                    ? new EAGLContext(version, shared.EAGLContext.ShareGroup)
                    : new EAGLContext(version);
                contextHandle = new ContextHandle(EAGLContext.Handle);
            } else {
                EAGLContext = (EAGLContext) Runtime.GetNSObject (handle.Handle);
                contextHandle = handle;
            }
        }
		private OpenALSoundController ()
		{
			alcMacOSXMixerOutputRate(PREFERRED_MIX_RATE);
			_device = Alc.OpenDevice (string.Empty);
			CheckALError ("Could not open AL device");
			if (_device != IntPtr.Zero) {
				int[] attribute = new int[0];
				_context = Alc.CreateContext (_device, attribute);
				CheckALError ("Could not open AL context");

				if (_context != ContextHandle.Zero) {
					Alc.MakeContextCurrent (_context);
					CheckALError ("Could not make AL context current");
				}
			} else {
				return;
			}

			allSourcesArray = new int[MAX_NUMBER_OF_SOURCES];
			AL.GenSources (allSourcesArray);

			availableSourcesCollection = new HashSet<int> ();
			inUseSourcesCollection = new HashSet<OALSoundBuffer> ();
			playingSourcesCollection = new HashSet<OALSoundBuffer> ();


			for (int x=0; x < MAX_NUMBER_OF_SOURCES; x++) {
				availableSourcesCollection.Add (allSourcesArray [x]);
			}
		}
Beispiel #10
0
		public static void Init () {
			var deviceName = Alc.GetString (IntPtr.Zero, AlcGetString.DefaultAllDevicesSpecifier);
			_device = Alc.OpenDevice (deviceName);
			_context = Alc.CreateContext (_device, (int[])null);
			Alc.MakeContextCurrent (_context);
			CheckError ();
		}
 // Necessary to allow creation of dummy GraphicsContexts (see CreateDummyContext static method).
 GraphicsContext(ContextHandle handle)
 {
     implementation = new OpenTK.Platform.Dummy.DummyGLContext(handle);
     lock (SyncRoot)
     {
         available_contexts.Add((implementation as IGraphicsContextInternal).Context, new WeakReference(this));
     }
 }
Beispiel #12
0
 public EglContext(ContextHandle handle, EglWindowInfo window, IGraphicsContext sharedContext, int major, int minor, GraphicsContextFlags flags)
 {
     if (handle == ContextHandle.Zero)
     throw new ArgumentException("handle");
       if (window == null)
     throw new ArgumentNullException("window");
       this.Handle = handle;
 }
 public void CreateContext(bool direct, IGraphicsContext source)
 {
     if (Handle == ContextHandle.Zero)
     {
         ++handle_count;
         Handle = new ContextHandle((IntPtr)handle_count);
     }
 }
Beispiel #14
0
        public SDL2GLContext(IntPtr ctxhandle, IWindowInfo windowInfo)
        {
			Console.WriteLine("WARNING! Creating context in a way we don't quite understand.");
            SDL2WindowInfo currentWindow = (SDL2WindowInfo)windowInfo;
			window = currentWindow.WindowHandle;
			context = ctxhandle;
			Handle = new ContextHandle(context);
			MakeCurrent(windowInfo);
        }
Beispiel #15
0
        // Necessary to allow creation of dummy GraphicsContexts (see CreateDummyContext static method).
        GraphicsContext(ContextHandle handle)
        {
            implementation = new OpenTK.Platform.Dummy.DummyGLContext(handle);

            lock (SyncRoot)
            {
                AddContext(this);
            }
        }
Beispiel #16
0
 public AglContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext)
 {
     if (handle == ContextHandle.Zero)
     throw new ArgumentException("handle");
       if (window == null)
     throw new ArgumentNullException("window");
       this.Handle = handle;
       this.carbonWindow = (CarbonWindowInfo) window;
 }
Beispiel #17
0
 public CocoaContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, int majorVersion, int minorVersion)
 {
     if (handle == ContextHandle.Zero)
         throw new ArgumentException("handle");
     if (window == null)
         throw new ArgumentNullException("window");
     
     Handle = handle;
     cocoaWindow = (CocoaWindowInfo)window;
 }
Beispiel #18
0
 public AglContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext)
     : base(DesktopBackend.OpenGL)
 {
     if (handle == ContextHandle.Zero)
         throw new ArgumentException("handle");
     if (window == null)
         throw new ArgumentNullException("window");
     Handle = handle;
     carbonWindow = (CarbonWindowInfo)window;
 }
Beispiel #19
0
 public DummyGLContext(ContextHandle handle, GraphicsContext.GetAddressDelegate loader)
     : this()
 {
     if (handle != ContextHandle.Zero)
     {
         Handle = handle;
     }
     Loader = loader;
     Mode = new GraphicsMode(new IntPtr(2), 32, 16, 0, 0, 0, 2, false);
 }
Beispiel #20
0
 public X11GLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shared, bool direct,
     int major, int minor, GraphicsContextFlags flags)
     : base(DesktopBackend.OpenGL)
 {
     if (handle == ContextHandle.Zero)
         throw new ArgumentException("handle");
     if (window == null)
         throw new ArgumentNullException("window");
     Handle = handle;
     currentWindow = (X11WindowInfo)window;
     Display = currentWindow.Display;
 }
Beispiel #21
0
 public WinGraphicsMode(ContextHandle context, IntPtr device)
 {
     lock (SyncRoot)
     {
         modes.AddRange(GetModesARB(context, device));
         if (modes.Count == 0)
             modes.AddRange(GetModesPFD(context, device));
         if (modes.Count == 0)
             throw new GraphicsModeException(
                 "No GraphicsMode available. This should never happen, please report a bug at http://www.opentk.com");
         modes.Sort(new GraphicsModeComparer());
     }
 }
Beispiel #22
0
        // Necessary to allow creation of dummy GraphicsContexts (see CreateDummyContext static method).
        GraphicsContext(ContextHandle handle)
        {
#if !IPHONE
            implementation = new OpenTK.Platform.Dummy.DummyGLContext(handle);
#else
            implementation = new OpenTK.Platform.iPhoneOS.iPhoneOSGraphicsContext(handle);
#endif

            lock (SyncRoot)
            {
                available_contexts.Add((implementation as IGraphicsContextInternal).Context, new WeakReference(this));
            }
        }
Beispiel #23
0
 public bool ProcessMouseEvent(RawInput rin)
 {
     RawMouse rawMouse = rin.Data.Mouse;
       ContextHandle key = new ContextHandle(rin.Header.Device);
       if (!this.rawids.ContainsKey(key))
     this.RefreshDevices();
       if (this.mice.Count == 0)
     return false;
       int index = this.rawids.ContainsKey(key) ? this.rawids[key] : 0;
       MouseState mouseState = this.mice[index];
       if ((rawMouse.ButtonFlags & RawInputMouseState.LEFT_BUTTON_DOWN) != (RawInputMouseState) 0)
     mouseState.EnableBit(0);
       if ((rawMouse.ButtonFlags & RawInputMouseState.LEFT_BUTTON_UP) != (RawInputMouseState) 0)
     mouseState.DisableBit(0);
       if ((rawMouse.ButtonFlags & RawInputMouseState.RIGHT_BUTTON_DOWN) != (RawInputMouseState) 0)
     mouseState.EnableBit(2);
       if ((rawMouse.ButtonFlags & RawInputMouseState.RIGHT_BUTTON_UP) != (RawInputMouseState) 0)
     mouseState.DisableBit(2);
       if ((rawMouse.ButtonFlags & RawInputMouseState.MIDDLE_BUTTON_DOWN) != (RawInputMouseState) 0)
     mouseState.EnableBit(1);
       if ((rawMouse.ButtonFlags & RawInputMouseState.MIDDLE_BUTTON_UP) != (RawInputMouseState) 0)
     mouseState.DisableBit(1);
       if ((rawMouse.ButtonFlags & RawInputMouseState.BUTTON_4_DOWN) != (RawInputMouseState) 0)
     mouseState.EnableBit(3);
       if ((rawMouse.ButtonFlags & RawInputMouseState.BUTTON_4_UP) != (RawInputMouseState) 0)
     mouseState.DisableBit(3);
       if ((rawMouse.ButtonFlags & RawInputMouseState.BUTTON_5_DOWN) != (RawInputMouseState) 0)
     mouseState.EnableBit(4);
       if ((rawMouse.ButtonFlags & RawInputMouseState.BUTTON_5_UP) != (RawInputMouseState) 0)
     mouseState.DisableBit(4);
       if ((rawMouse.ButtonFlags & RawInputMouseState.WHEEL) != (RawInputMouseState) 0)
     mouseState.WheelPrecise += (float) (short) rawMouse.ButtonData / 120f;
       if ((rawMouse.Flags & RawMouseFlags.MOUSE_MOVE_ABSOLUTE) != RawMouseFlags.MOUSE_MOVE_RELATIVE)
       {
     mouseState.X = rawMouse.LastX;
     mouseState.Y = rawMouse.LastY;
       }
       else
       {
     mouseState.X += rawMouse.LastX;
     mouseState.Y += rawMouse.LastY;
       }
       lock (this.UpdateLock)
       {
     this.mice[index] = mouseState;
     return true;
       }
 }
Beispiel #24
0
            public TemporaryContext(INativeWindow native)
            {
                Debug.WriteLine("[WGL] Creating temporary context to load extensions");

                if (native == null)
                    throw new ArgumentNullException();

                // Create temporary context and load WGL entry points
                // First, set a compatible pixel format to the device context
                // of the temp window
                WinWindowInfo window = native.WindowInfo as WinWindowInfo;
                WinGraphicsMode selector = new WinGraphicsMode(window.DeviceContext);
                WinGLContext.SetGraphicsModePFD(selector, GraphicsMode.Default, window);

                bool success = false;

                // Then, construct a temporary context and load all wgl extensions
                Context = new ContextHandle(Wgl.CreateContext(window.DeviceContext));
                if (Context != ContextHandle.Zero)
                {
                    // Make the context current.
                    // Note: on some video cards and on some virtual machines, wglMakeCurrent
                    // may fail with an errorcode of 6 (INVALID_HANDLE). The suggested workaround
                    // is to call wglMakeCurrent in a loop until it succeeds.
                    // See https://www.opengl.org/discussion_boards/showthread.php/171058-nVidia-wglMakeCurrent()-multiple-threads
                    // Sigh...
                    for (int retry = 0; retry < 5 && !success; retry++)
                    {
                        success = Wgl.MakeCurrent(window.DeviceContext, Context.Handle);
                        if (!success)
                        {
                            Debug.Print("wglMakeCurrent failed with error: {0}. Retrying", Marshal.GetLastWin32Error());
                            System.Threading.Thread.Sleep(10);
                        }
                    }
                }
                else
                {
                    Debug.Print("[WGL] CreateContext failed with error: {0}", Marshal.GetLastWin32Error());
                }

                if (!success)
                {
                    Debug.WriteLine("[WGL] Failed to create temporary context");
                }
            }
Beispiel #25
0
 public Sdl2GraphicsContext(GraphicsMode mode,
     IWindowInfo win, IGraphicsContext shareContext,
     int major, int minor,
     OpenTK.Graphics.GraphicsContextFlags flags)
     : this(win)
 {
     lock (SDL.Sync)
     {
         SetGLAttributes(mode, shareContext, major, minor, flags);
         SdlContext = new ContextHandle(SDL.SDL_GL_CreateContext(Window.Handle));
     }
     if (SdlContext == ContextHandle.Zero)
     {
         var error = SDL.SDL_GetError();
         Debug.Print("SDL2 failed to create OpenGL context: {0}", error);
         throw new GraphicsContextException(error);
     }
     Handle = GraphicsContext.GetCurrentContext();
 }
Beispiel #26
0
 public static void InitialSetup()
 {
     // FOR THE LOVE OF GOD PLEASE LET THIS WORK
     AudioDevice = Alc.OpenDevice (null); // Default device
     if (AudioDevice != null) {
         AudioCtx = Alc.CreateContext(AudioDevice, (int[])null);
         if(AudioCtx != ContextHandle.Zero)
         {
             Alc.GetError(AudioDevice);
             if(Alc.MakeContextCurrent( AudioCtx ))
             {
                 LoadWaveFile ("camprespite_loop", "camprespite_loop.wav");
                 LoadWaveFile ("last_human_loop", "last_human_loop.wav");
             }
             else
                 throw new Exception("Failed to set current audio context");
         }
         else
             throw new Exception("Failed to create audio context.");
     }
     else
         throw new Exception("Failed to open default audio device.");
 }
Beispiel #27
0
        public SDL2GLContext (GraphicsMode mode, IWindowInfo windowInfo, IGraphicsContext shared, bool direct,
            int major, int minor, GraphicsContextFlags flags)
		{
			SDL2WindowInfo currentWindow = (SDL2WindowInfo)windowInfo;
			window = currentWindow.WindowHandle;
            
			if (shared != null) {
				shared.MakeCurrent (windowInfo);
				lock (API.sdl_api_lock) {
					API.GL_SetAttribute (API.GLAttr.ShareWithCurrentContext, 1);
				}
			}

			lock (API.sdl_api_lock) {
				context = API.GL_CreateContext (currentWindow.WindowHandle);
			}

			MakeCurrent (windowInfo);

			if (shared != null) {
				shared.MakeCurrent (windowInfo);
			}
			Handle = new ContextHandle(context);
        }
Beispiel #28
0
        public Sdl2GraphicsContext(GraphicsMode mode,
            IWindowInfo win, IGraphicsContext shareContext,
            int major, int minor,
            OpenTK.Graphics.GraphicsContextFlags flags)
            : this(win)
        {
            lock (SDL.Sync)
            {
                bool retry = false;
                do
                {
                    SetGLAttributes(mode, shareContext, major, minor, flags);
                    SdlContext = new ContextHandle(SDL.GL.CreateContext(Window.Handle));

                    // If we failed to create a valid context, relax the GraphicsMode
                    // and try again.
                    retry =
                        SdlContext == ContextHandle.Zero &&
                        Utilities.RelaxGraphicsMode(ref mode);
                }
                while (retry);

                if (SdlContext == ContextHandle.Zero)
                {
                    var error = SDL.GetError();
                    Debug.Print("SDL2 failed to create OpenGL context: {0}", error);
                    throw new GraphicsContextException(error);
                }

                Mode = GetGLAttributes(SdlContext, out flags);
            }
            Handle = GraphicsContext.GetCurrentContext();
            Debug.Print("SDL2 created GraphicsContext (handle: {0})", Handle);
            Debug.Print("    GraphicsMode: {0}", Mode);
            Debug.Print("    GraphicsContextFlags: {0}", flags);
        }
Beispiel #29
0
        public X11GLContext(GraphicsMode mode, IWindowInfo window, IGraphicsContext shared, bool direct,
                            int major, int minor, GraphicsContextFlags flags)
        {
            if (mode == null)
            {
                throw new ArgumentNullException("mode");
            }
            if (window == null)
            {
                throw new ArgumentNullException("window");
            }

            // Do not move this lower, as almost everything requires the Display
            // property to be correctly set.
            Display = ((X11WindowInfo)window).Display;

            // Check that GLX is supported. We cannot proceed to create
            // an OpenGL context without the GLX extension.
            int error_base;
            int event_base;
            int glx_major;
            int glx_minor;

            using (new XLock(Display))
            {
                bool supported = Glx.QueryExtension(Display, out error_base, out event_base);
                supported &= Glx.QueryVersion(Display, out glx_major, out glx_minor);
                if (supported)
                {
                    Debug.Print("[X11] GLX supported. Version is {0}.{1}", glx_major, glx_minor);
                }
                else
                {
                    throw new NotSupportedException("[X11] GLX extension is not supported.");
                }
            }

            IntPtr visual   = IntPtr.Zero;
            IntPtr fbconfig = IntPtr.Zero;

            // Once a window has a visual, we cannot use a different
            // visual on the OpenGL context, or glXMakeCurrent might fail.
            // Note: we should only check X11WindowInfo.Visual, as that
            // is the only property that can be set by Utilities.CreateX11WindowInfo.
            currentWindow = (X11WindowInfo)window;
            if (currentWindow.Visual != IntPtr.Zero)
            {
                visual   = currentWindow.Visual;
                fbconfig = currentWindow.FBConfig;
                Mode     = currentWindow.GraphicsMode;
            }

            if (Mode == null || !Mode.Index.HasValue)
            {
                Mode = ModeSelector.SelectGraphicsMode(mode, out visual, out fbconfig);
            }

            ContextHandle shareHandle = shared != null ?
                                        (shared as IGraphicsContextInternal).Context : (ContextHandle)IntPtr.Zero;

            Debug.Write("Creating X11GLContext context: ");
            Debug.Write(direct ? "direct, " : "indirect, ");
            Debug.WriteLine(shareHandle.Handle == IntPtr.Zero ? "not shared... " :
                            String.Format("shared with ({0})... ", shareHandle));

            // Try using the new context creation method. If it fails, fall back to the old one.
            // For each of these methods, we try two times to create a context:
            // one with the "direct" flag intact, the other with the flag inversed.
            // HACK: It seems that Catalyst 9.1 - 9.4 on Linux have problems with contexts created through
            // GLX_ARB_create_context, including hideous input lag, no vsync and other madness.
            // Use legacy context creation if the user doesn't request a 3.0+ context.
            if (fbconfig != IntPtr.Zero && (major * 10 + minor >= 30) && SupportsCreateContextAttribs(Display, currentWindow))
            {
                Handle = CreateContextAttribs(Display, currentWindow.Screen,
                                              fbconfig, direct, major, minor, flags, shareHandle);
            }

            if (Handle == ContextHandle.Zero)
            {
                Handle = CreateContextLegacy(Display, visual, direct, shareHandle);
            }

            if (Handle != ContextHandle.Zero)
            {
                Debug.Print("Context created (id: {0}).", Handle);
            }
            else
            {
                throw new GraphicsContextException("Failed to create OpenGL context. Glx.CreateContext call returned 0.");
            }

            using (new XLock(Display))
            {
                if (!Glx.IsDirect(Display, Handle.Handle))
                {
                    Debug.Print("Warning: Context is not direct.");
                }
            }
        }
        // Loads all available audio devices into the available_*_devices lists.
        static AudioDeviceEnumerator()
        {
            IntPtr        dummy_device  = IntPtr.Zero;
            ContextHandle dummy_context = ContextHandle.Zero;

            try
            {
                Debug.WriteLine("Enumerating audio devices.");
                Debug.Indent();

                // need a dummy context for correct results
                dummy_device  = Alc.OpenDevice(null);
                dummy_context = Alc.CreateContext(dummy_device, (int[])null);
                bool     dummy_success = Alc.MakeContextCurrent(dummy_context);
                AlcError dummy_error   = Alc.GetError(dummy_device);
                if (!dummy_success || dummy_error != AlcError.NoError)
                {
                    throw new AudioContextException("Failed to create dummy Context. Device (" + dummy_device.ToString() +
                                                    ") Context (" + dummy_context.Handle.ToString() +
                                                    ") MakeContextCurrent " + (dummy_success ? "succeeded" : "failed") +
                                                    ", Alc Error (" + dummy_error.ToString() + ") " + Alc.GetString(IntPtr.Zero, (AlcGetString)dummy_error));
                }

                // Get a list of all known playback devices, using best extension available
                if (Alc.IsExtensionPresent(IntPtr.Zero, "ALC_ENUMERATION_EXT"))
                {
                    Version = AlcVersion.Alc1_1;
                    if (Alc.IsExtensionPresent(IntPtr.Zero, "ALC_ENUMERATE_ALL_EXT"))
                    {
                        available_playback_devices.AddRange(Alc.GetString(IntPtr.Zero, AlcGetStringList.AllDevicesSpecifier));
                        DefaultPlaybackDevice = Alc.GetString(IntPtr.Zero, AlcGetString.DefaultAllDevicesSpecifier);
                    }
                    else
                    {
                        available_playback_devices.AddRange(Alc.GetString(IntPtr.Zero, AlcGetStringList.DeviceSpecifier));
                        DefaultPlaybackDevice = Alc.GetString(IntPtr.Zero, AlcGetString.DefaultDeviceSpecifier);
                    }
                }
                else
                {
                    Version = AlcVersion.Alc1_0;
                    Debug.Print("Device enumeration extension not available. Failed to enumerate playback devices.");
                }
                AlcError playback_err = Alc.GetError(dummy_device);
                if (playback_err != AlcError.NoError)
                {
                    throw new AudioContextException("Alc Error occured when querying available playback devices. " + playback_err.ToString());
                }

                // Get a list of all known recording devices, at least ALC_ENUMERATION_EXT is needed too
                if (Version == AlcVersion.Alc1_1 && Alc.IsExtensionPresent(IntPtr.Zero, "ALC_EXT_CAPTURE"))
                {
                    available_recording_devices.AddRange(Alc.GetString(IntPtr.Zero, AlcGetStringList.CaptureDeviceSpecifier));
                    DefaultRecordingDevice = Alc.GetString(IntPtr.Zero, AlcGetString.CaptureDefaultDeviceSpecifier);
                }
                else
                {
                    Debug.Print("Capture extension not available. Failed to enumerate recording devices.");
                }
                AlcError record_err = Alc.GetError(dummy_device);
                if (record_err != AlcError.NoError)
                {
                    throw new AudioContextException("Alc Error occured when querying available recording devices. " + record_err.ToString());
                }

#if DEBUG
                Debug.WriteLine("Found playback devices:");
                foreach (string s in available_playback_devices)
                {
                    Debug.WriteLine(s);
                }

                Debug.WriteLine("Default playback device: " + DefaultPlaybackDevice);

                Debug.WriteLine("Found recording devices:");
                foreach (string s in available_recording_devices)
                {
                    Debug.WriteLine(s);
                }

                Debug.WriteLine("Default recording device: " + DefaultRecordingDevice);
#endif
            }
            catch (DllNotFoundException e)
            {
                Trace.WriteLine(e.ToString());
                IsOpenALSupported = false;
            }
            catch (AudioContextException ace)
            {
                Trace.WriteLine(ace.ToString());
                IsOpenALSupported = false;
            }
            finally
            {
                Debug.Unindent();

                if (IsOpenALSupported)
                {
                    try
                    {
                        // clean up the dummy context
                        Alc.MakeContextCurrent(ContextHandle.Zero);
                        if (dummy_context != ContextHandle.Zero && dummy_context.Handle != IntPtr.Zero)
                        {
                            Alc.DestroyContext(dummy_context);
                        }
                        if (dummy_device != IntPtr.Zero)
                        {
                            Alc.CloseDevice(dummy_device);
                        }
                    }
                    catch
                    {
                        IsOpenALSupported = false;
                    }
                }
            }
        }
Beispiel #31
0
        /// <summary>
        /// Open the sound device, sets up an audio context, and makes the new context
        /// the current context. Note that this method will stop the playback of
        /// music that was running prior to the game start. If any error occurs, then
        /// the state of the controller is reset.
        /// </summary>
        /// <returns>True if the sound controller was setup, and false if not.</returns>
        private bool OpenSoundController()
        {
#if MONOMAC
            alcMacOSXMixerOutputRate(PREFERRED_MIX_RATE);
#endif

            try
            {
                _device = Alc.OpenDevice(string.Empty);
#if DESKTOPGL
                EffectsExtension.device = _device;
#endif
            }
            catch (Exception ex)
            {
                _SoundInitException = ex;
                return(false);
            }
            if (CheckALError("Could not open AL device"))
            {
                return(false);
            }
            if (_device != IntPtr.Zero)
            {
#if ANDROID
                // Attach activity event handlers so we can pause and resume all playing sounds
                AndroidGameActivity.Paused  += Activity_Paused;
                AndroidGameActivity.Resumed += Activity_Resumed;

                // Query the device for the ideal frequency and update buffer size so
                // we can get the low latency sound path.

                /*
                 * The recommended sequence is:
                 *
                 * Check for feature "android.hardware.audio.low_latency" using code such as this:
                 * import android.content.pm.PackageManager;
                 * ...
                 * PackageManager pm = getContext().getPackageManager();
                 * boolean claimsFeature = pm.hasSystemFeature(PackageManager.FEATURE_AUDIO_LOW_LATENCY);
                 * Check for API level 17 or higher, to confirm use of android.media.AudioManager.getProperty().
                 * Get the native or optimal output sample rate and buffer size for this device's primary output stream, using code such as this:
                 * import android.media.AudioManager;
                 * ...
                 * AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                 * String sampleRate = am.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE));
                 * String framesPerBuffer = am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER));
                 * Note that sampleRate and framesPerBuffer are Strings. First check for null and then convert to int using Integer.parseInt().
                 * Now use OpenSL ES to create an AudioPlayer with PCM buffer queue data locator.
                 *
                 * See http://stackoverflow.com/questions/14842803/low-latency-audio-playback-on-android
                 */

                int frequency     = DEFAULT_FREQUENCY;
                int updateSize    = DEFAULT_UPDATE_SIZE;
                int updateBuffers = DEFAULT_UPDATE_BUFFER_COUNT;
                if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.JellyBeanMr1)
                {
                    Android.Util.Log.Debug("OAL", Game.Activity.PackageManager.HasSystemFeature(PackageManager.FeatureAudioLowLatency) ? "Supports low latency audio playback." : "Does not support low latency audio playback.");

                    var audioManager = Game.Activity.GetSystemService(Context.AudioService) as AudioManager;
                    if (audioManager != null)
                    {
                        var result = audioManager.GetProperty(AudioManager.PropertyOutputSampleRate);
                        if (!string.IsNullOrEmpty(result))
                        {
                            frequency = int.Parse(result, CultureInfo.InvariantCulture);
                        }
                        result = audioManager.GetProperty(AudioManager.PropertyOutputFramesPerBuffer);
                        if (!string.IsNullOrEmpty(result))
                        {
                            updateSize = int.Parse(result, CultureInfo.InvariantCulture);
                        }
                    }

                    // If 4.4 or higher, then we don't need to double buffer on the application side.
                    // See http://stackoverflow.com/a/15006327
                    // Use the explicit value rather than a constant as the 4.2 SDK (the build SDK) does not define a constant for 4.4.
                    if ((int)Android.OS.Build.VERSION.SdkInt >= 19)
                    {
                        updateBuffers = 1;
                    }
                }
                else
                {
                    Android.Util.Log.Debug("OAL", "Android 4.2 or higher required for low latency audio playback.");
                }
                Android.Util.Log.Debug("OAL", "Using sample rate " + frequency + "Hz and " + updateBuffers + " buffers of " + updateSize + " frames.");

                // These are missing and non-standard ALC constants
                const int AlcFrequency     = 0x1007;
                const int AlcUpdateSize    = 0x1014;
                const int AlcUpdateBuffers = 0x1015;

                int[] attribute = new[]
                {
                    AlcFrequency, frequency,
                    AlcUpdateSize, updateSize,
                    AlcUpdateBuffers, updateBuffers,
                    0
                };
#elif IOS
                EventHandler <AVAudioSessionInterruptionEventArgs> handler = delegate(object sender, AVAudioSessionInterruptionEventArgs e) {
                    switch (e.InterruptionType)
                    {
                    case AVAudioSessionInterruptionType.Began:
                        AVAudioSession.SharedInstance().SetActive(false);
                        Alc.MakeContextCurrent(ContextHandle.Zero);
                        Alc.SuspendContext(_context);
                        break;

                    case AVAudioSessionInterruptionType.Ended:
                        AVAudioSession.SharedInstance().SetActive(true);
                        Alc.MakeContextCurrent(_context);
                        Alc.ProcessContext(_context);
                        break;
                    }
                };
                AVAudioSession.Notifications.ObserveInterruption(handler);

                int[] attribute = new int[0];
#else
                int[] attribute = new int[0];
#endif

                _context = Alc.CreateContext(_device, attribute);
#if DESKTOPGL
                _oggstreamer = new OggStreamer();
#endif

                if (CheckALError("Could not create AL context"))
                {
                    CleanUpOpenAL();
                    return(false);
                }

                if (_context != NullContext)
                {
                    Alc.MakeContextCurrent(_context);
                    if (CheckALError("Could not make AL context current"))
                    {
                        CleanUpOpenAL();
                        return(false);
                    }
                    SupportsADPCM = AL.IsExtensionPresent("AL_SOFT_MSADPCM");
                    return(true);
                }
            }
            return(false);
        }
Beispiel #32
0
 public override IGraphicsContext CreateGLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags) =>
 new iOSGraphicsContext(handle);
Beispiel #33
0
        public WinGLContext(GraphicsMode format, WinWindowInfo window, IGraphicsContext sharedContext,
                            int major, int minor, GraphicsContextFlags flags)
        {
            if (window == null)
            {
                throw new ArgumentNullException("window", "Must point to a valid window.");
            }
            if (window.WindowHandle == IntPtr.Zero)
            {
                throw new ArgumentException("window", "Must be a valid window.");
            }

            Mode = format;

            Debug.Print("OpenGL will be bound to handle: {0}", window.WindowHandle);
            Debug.Write("Setting pixel format... ");
            this.SetGraphicsModePFD(format, (WinWindowInfo)window);

            if (!wgl_loaded)
            {
                // We need to create a temp context in order to load wgl extensions (e.g. for multisampling or GL3).
                // We cannot rely on OpenTK.Platform.Wgl until we create the context and call Wgl.LoadAll().
                Debug.Print("Creating temporary context for wgl extensions.");

                ContextHandle temp_context = new ContextHandle(Wgl.Imports.CreateContext(window.DeviceContext));
                Wgl.Imports.MakeCurrent(window.DeviceContext, temp_context.Handle);
                Wgl.LoadAll();
                Wgl.MakeCurrent(IntPtr.Zero, IntPtr.Zero);
                Wgl.DeleteContext(temp_context.Handle);
                wgl_loaded = true;
            }

            if (Wgl.Delegates.wglCreateContextAttribsARB != null)
            {
                try
                {
                    Debug.Write("Using WGL_ARB_create_context... ");

                    List <int> attributes = new List <int>();
                    attributes.Add((int)ArbCreateContext.MajorVersion);
                    attributes.Add(major);
                    attributes.Add((int)ArbCreateContext.MinorVersion);
                    attributes.Add(minor);
                    if (flags != 0)
                    {
                        attributes.Add((int)ArbCreateContext.Flags);
                        attributes.Add((int)flags);
                    }
                    attributes.Add(0);

                    Handle = new ContextHandle(
                        Wgl.Arb.CreateContextAttribs(
                            window.DeviceContext,
                            sharedContext != null ? (sharedContext as IGraphicsContextInternal).Context.Handle : IntPtr.Zero,
                            attributes.ToArray()));
                    if (Handle == ContextHandle.Zero)
                    {
                        Debug.Print("failed. (Error: {0})", Marshal.GetLastWin32Error());
                    }
                    else
                    {
                        Debug.Print("success!");
                    }
                }
                catch (EntryPointNotFoundException e) { Debug.Print(e.ToString()); }
                catch (NullReferenceException e) { Debug.Print(e.ToString()); }
            }

            if (Handle == ContextHandle.Zero)
            {
                // Failed to create GL3-level context, fall back to GL2.
                Debug.Write("Falling back to GL2... ");
                Handle = new ContextHandle(Wgl.Imports.CreateContext(window.DeviceContext));
                if (Handle == ContextHandle.Zero)
                {
                    Handle = new ContextHandle(Wgl.Imports.CreateContext(window.DeviceContext));
                }
                if (Handle == ContextHandle.Zero)
                {
                    throw new GraphicsContextException(
                              String.Format("Context creation failed. Wgl.CreateContext() error: {0}.",
                                            Marshal.GetLastWin32Error()));
                }
            }

            Debug.WriteLine(String.Format("success! (id: {0})", Handle));

            if (sharedContext != null)
            {
                Debug.Print("Sharing state with context {0}", sharedContext.ToString());
                Wgl.Imports.ShareLists((sharedContext as IGraphicsContextInternal).Context.Handle, Handle.Handle);
            }
        }
Beispiel #34
0
 public DummyGLContext()
 {
     Handle = new ContextHandle(
         new IntPtr(Interlocked.Increment(
                        ref handle_count)));
 }
Beispiel #35
0
 public static bool MakeCurrent(IntPtr display, IntPtr drawable, ContextHandle context)
 {
     return(MakeCurrent(display, drawable, context.Handle));
 }
Beispiel #36
0
        public void RefreshDevices()
        {
            lock (UpdateLock)
            {
                for (int i = 0; i < keyboards.Count; i++)
                {
                    KeyboardState state = keyboards[i];
                    state.IsConnected = false;
                    keyboards[i]      = state;
                }

                int count = WinRawInput.DeviceCount;
                RawInputDeviceList[] ridl = new RawInputDeviceList[count];
                for (int i = 0; i < count; i++)
                {
                    ridl[i] = new RawInputDeviceList();
                }
                Functions.GetRawInputDeviceList(ridl, ref count, API.RawInputDeviceListSize);

                // Discover keyboard devices:
                foreach (RawInputDeviceList dev in ridl)
                {
                    ContextHandle id = new ContextHandle(dev.Device);
                    if (rawids.ContainsKey(id))
                    {
                        // Device already registered, mark as connected
                        KeyboardState state = keyboards[rawids[id]];
                        state.IsConnected     = true;
                        keyboards[rawids[id]] = state;
                        continue;
                    }

                    string name = GetDeviceName(dev);
                    if (name.ToLower().Contains("root"))
                    {
                        // This is a terminal services device, skip it.
                        continue;
                    }
                    else if (dev.Type == RawInputDeviceType.KEYBOARD || dev.Type == RawInputDeviceType.HID)
                    {
                        // This is a keyboard or USB keyboard device. In the latter case, discover if it really is a
                        // keyboard device by qeurying the registry.
                        RegistryKey regkey      = GetRegistryKey(name);
                        string      deviceDesc  = (string)regkey.GetValue("DeviceDesc");
                        string      deviceClass = (string)regkey.GetValue("Class");

                        if (String.IsNullOrEmpty(deviceDesc))
                        {
                            Debug.Print("[Warning] Failed to retrieve device description, skipping this device.");
                            continue;
                        }
                        else
                        {
                            deviceDesc = deviceDesc.Substring(deviceDesc.LastIndexOf(';') + 1);
                        }

                        if (!String.IsNullOrEmpty(deviceClass) && deviceClass.ToLower().Equals("keyboard"))
                        {
                            // Register the keyboard:
                            RawInputDeviceInfo info = new RawInputDeviceInfo();
                            int devInfoSize         = API.RawInputDeviceInfoSize;
                            Functions.GetRawInputDeviceInfo(dev.Device, RawInputDeviceInfoEnum.DEVICEINFO,
                                                            info, ref devInfoSize);

                            //KeyboardDevice kb = new KeyboardDevice();
                            //kb.Description = deviceDesc;
                            //kb.NumberOfLeds = info.Device.Keyboard.NumberOfIndicators;
                            //kb.NumberOfFunctionKeys = info.Device.Keyboard.NumberOfFunctionKeys;
                            //kb.NumberOfKeys = info.Device.Keyboard.NumberOfKeysTotal;
                            //kb.DeviceID = dev.Device;

                            RegisterKeyboardDevice(window, deviceDesc);
                            KeyboardState state = new KeyboardState();
                            state.IsConnected = true;
                            keyboards.Add(state);
                            names.Add(deviceDesc);
                            rawids.Add(new ContextHandle(dev.Device), keyboards.Count - 1);
                        }
                    }
                }
            }
        }
Beispiel #37
0
        public bool ProcessKeyboardEvent(RawInput rin)
        {
            bool processed = false;

            bool pressed =
                rin.Data.Keyboard.Message == (int)WindowMessage.KEYDOWN ||
                rin.Data.Keyboard.Message == (int)WindowMessage.SYSKEYDOWN;

            ContextHandle handle = new ContextHandle(rin.Header.Device);
            KeyboardState keyboard;

            if (!rawids.ContainsKey(handle))
            {
                RefreshDevices();
            }

            if (keyboards.Count == 0)
            {
                return(false);
            }

            // Note:For some reason, my Microsoft Digital 3000 keyboard reports 0
            // as rin.Header.Device for the "zoom-in/zoom-out" buttons.
            // That's problematic, because no device has a "0" id.
            // As a workaround, we'll add those buttons to the first device (if any).
            int keyboard_handle = rawids.ContainsKey(handle) ? rawids[handle] : 0;

            keyboard = keyboards[keyboard_handle];

            // Generic control, shift, alt keys may be sent instead of left/right.
            // It seems you have to explicitly register left/right events.
            switch (rin.Data.Keyboard.VKey)
            {
            case VirtualKeys.SHIFT:
                keyboard[Input.Key.ShiftLeft] = keyboard[Input.Key.ShiftRight] = pressed;
                processed = true;
                break;

            case VirtualKeys.CONTROL:
                keyboard[Input.Key.ControlLeft] = keyboard[Input.Key.ControlRight] = pressed;
                processed = true;
                break;

            case VirtualKeys.MENU:
                keyboard[Input.Key.AltLeft] = keyboard[Input.Key.AltRight] = pressed;
                processed = true;
                break;

            default:
                if (!KeyMap.ContainsKey(rin.Data.Keyboard.VKey))
                {
                    Debug.Print("Virtual key {0} ({1}) not mapped.",
                                rin.Data.Keyboard.VKey, (int)rin.Data.Keyboard.VKey);
                }
                else
                {
                    keyboard[KeyMap[rin.Data.Keyboard.VKey]] = pressed;
                    processed = true;
                }
                break;
            }

            lock (UpdateLock)
            {
                keyboards[keyboard_handle] = keyboard;
                return(processed);
            }
        }
Beispiel #38
0
 public override IGraphicsContext CreateGLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
 {
     return(new WinGLContext(handle, (WinWindowInfo)window, shareContext, major, minor, flags));
 }
Beispiel #39
0
 public IGraphicsContext CreateGLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
 {
     throw new PlatformNotSupportedException(error_string);
 }
Beispiel #40
0
        /// <summary>
        /// Constructs a new GraphicsContext with the specified GraphicsMode, version and flags,  and attaches it to the specified window.
        /// </summary>
        /// <param name="mode">The OpenTK.Graphics.GraphicsMode of the GraphicsContext.</param>
        /// <param name="window">The OpenTK.Platform.IWindowInfo to attach the GraphicsContext to.</param>
        /// <param name="major">The major version of the new GraphicsContext.</param>
        /// <param name="minor">The minor version of the new GraphicsContext.</param>
        /// <param name="flags">The GraphicsContextFlags for the GraphicsContext.</param>
        /// <remarks>
        /// Different hardware supports different flags, major and minor versions. Invalid parameters will be silently ignored.
        /// </remarks>
        public GraphicsContext(GraphicsMode mode, IWindowInfo window, int major, int minor, GraphicsContextFlags flags)
        {
            lock (SyncRoot)
            {
                bool designMode = false;
                if (mode == null && window == null)
                {
                    designMode = true;
                }
                else if (mode == null)
                {
                    throw new ArgumentNullException("mode", "Must be a valid GraphicsMode.");
                }
                else if (window == null)
                {
                    throw new ArgumentNullException("window", "Must point to a valid window.");
                }

                // Silently ignore invalid major and minor versions.
                if (major <= 0)
                {
                    major = 1;
                }
                if (minor < 0)
                {
                    minor = 0;
                }

                Debug.Print("Creating GraphicsContext.");
                try
                {
                    Debug.Indent();
                    Debug.Print("GraphicsMode: {0}", mode);
                    Debug.Print("IWindowInfo: {0}", window);
                    Debug.Print("GraphicsContextFlags: {0}", flags);
                    Debug.Print("Requested version: {0}.{1}", major, minor);

                    IGraphicsContext shareContext = shareContext = FindSharedContext();

                    // Todo: Add a DummyFactory implementing IPlatformFactory.
                    if (designMode)
                    {
                        implementation = new Platform.Dummy.DummyGLContext();
                    }
                    else
                    {
                        IPlatformFactory factory = null;
                        switch ((flags & GraphicsContextFlags.Embedded) == GraphicsContextFlags.Embedded)
                        {
                        case false: factory = Factory.Default; break;

                        case true: factory = Factory.Embedded; break;
                        }

                        // Note: this approach does not allow us to mix native and EGL contexts in the same process.
                        // This should not be a problem, as this use-case is not interesting for regular applications.
                        // Note 2: some platforms may not support a direct way of getting the current context
                        // (this happens e.g. with DummyGLContext). In that case, we use a slow fallback which
                        // iterates through all known contexts and checks if any is current (check GetCurrentContext
                        // declaration).
                        if (GetCurrentContext == null)
                        {
                            GetCurrentContext = factory.CreateGetCurrentGraphicsContext();
                        }

                        implementation = factory.CreateGLContext(mode, window, shareContext, direct_rendering, major, minor, flags);
                        handle_cached  = ((IGraphicsContextInternal)implementation).Context;
                    }

                    AddContext(this);
                }
                finally
                {
                    Debug.Unindent();
                }
            }
        }
Beispiel #41
0
        public void RefreshDevices()
        {
            lock (UpdateLock)
            {
                for (int i = 0; i < keyboards.Count; i++)
                {
                    KeyboardState state = keyboards[i];
                    state.IsConnected = false;
                    keyboards[i] = state;
                }

                int count = WinRawInput.DeviceCount;
                RawInputDeviceList[] ridl = new RawInputDeviceList[count];
                for (int i = 0; i < count; i++)
                    ridl[i] = new RawInputDeviceList();
                Functions.GetRawInputDeviceList(ridl, ref count, API.RawInputDeviceListSize);

                // Discover keyboard devices:
                foreach (RawInputDeviceList dev in ridl)
                {
                    ContextHandle id = new ContextHandle(dev.Device);
                    if (rawids.ContainsKey(id))
                    {
                        // Device already registered, mark as connected
                        KeyboardState state = keyboards[rawids[id]];
                        state.IsConnected = true;
                        keyboards[rawids[id]] = state;
                        continue;
                    }

                    string name = GetDeviceName(dev);
                    if (name.ToLower().Contains("root"))
                    {
                        // This is a terminal services device, skip it.
                        continue;
                    }
                    else if (dev.Type == RawInputDeviceType.KEYBOARD || dev.Type == RawInputDeviceType.HID)
                    {
                        // This is a keyboard or USB keyboard device. In the latter case, discover if it really is a
                        // keyboard device by qeurying the registry.
                        RegistryKey regkey = GetRegistryKey(name);
                        string deviceDesc = (string)regkey.GetValue("DeviceDesc");
                        string deviceClass = (string)regkey.GetValue("Class");

                        if (String.IsNullOrEmpty(deviceDesc))
                        {
                            Debug.Print("[Warning] Failed to retrieve device description, skipping this device.");
                            continue;
                        }
                        else
                        {
                            deviceDesc = deviceDesc.Substring(deviceDesc.LastIndexOf(';') + 1);
                        }

                        if (!String.IsNullOrEmpty(deviceClass) && deviceClass.ToLower().Equals("keyboard"))
                        {
                            // Register the keyboard:
                            RawInputDeviceInfo info = new RawInputDeviceInfo();
                            int devInfoSize = API.RawInputDeviceInfoSize;
                            Functions.GetRawInputDeviceInfo(dev.Device, RawInputDeviceInfoEnum.DEVICEINFO,
                                    info, ref devInfoSize);

                            //KeyboardDevice kb = new KeyboardDevice();
                            //kb.Description = deviceDesc;
                            //kb.NumberOfLeds = info.Device.Keyboard.NumberOfIndicators;
                            //kb.NumberOfFunctionKeys = info.Device.Keyboard.NumberOfFunctionKeys;
                            //kb.NumberOfKeys = info.Device.Keyboard.NumberOfKeysTotal;
                            //kb.DeviceID = dev.Device;

                            RegisterKeyboardDevice(window, deviceDesc);
                            KeyboardState state = new KeyboardState();
                            state.IsConnected = true;
                            keyboards.Add(state);
                            names.Add(deviceDesc);
                            rawids.Add(new ContextHandle(dev.Device), keyboards.Count - 1);
                        }
                    }
                }
            }
        }
Beispiel #42
0
        public bool ProcessMouseEvent(RawInput rin)
        {
            RawMouse      raw    = rin.Data.Mouse;
            ContextHandle handle = new ContextHandle(rin.Header.Device);

            MouseState mouse;

            if (!rawids.ContainsKey(handle))
            {
                RefreshDevices();
            }

            if (mice.Count == 0)
            {
                return(false);
            }

            // Note:For some reason, my Microsoft Digital 3000 keyboard reports 0
            // as rin.Header.Device for the "zoom-in/zoom-out" buttons.
            // That's problematic, because no device has a "0" id.
            // As a workaround, we'll add those buttons to the first device (if any).
            int mouse_handle = rawids.ContainsKey(handle) ? rawids[handle] : 0;

            mouse = mice[mouse_handle];

            // Set and release capture of the mouse to fix http://www.opentk.com/node/2133, Patch by Artfunkel
            if ((raw.ButtonFlags & RawInputMouseState.LEFT_BUTTON_DOWN) != 0)
            {
                mouse.EnableBit((int)MouseButton.Left);
                Functions.SetCapture(Window);
            }
            if ((raw.ButtonFlags & RawInputMouseState.LEFT_BUTTON_UP) != 0)
            {
                mouse.DisableBit((int)MouseButton.Left);
                Functions.ReleaseCapture();
            }
            if ((raw.ButtonFlags & RawInputMouseState.RIGHT_BUTTON_DOWN) != 0)
            {
                mouse.EnableBit((int)MouseButton.Right);
                Functions.SetCapture(Window);
            }
            if ((raw.ButtonFlags & RawInputMouseState.RIGHT_BUTTON_UP) != 0)
            {
                mouse.DisableBit((int)MouseButton.Right);
                Functions.ReleaseCapture();
            }
            if ((raw.ButtonFlags & RawInputMouseState.MIDDLE_BUTTON_DOWN) != 0)
            {
                mouse.EnableBit((int)MouseButton.Middle);
                Functions.SetCapture(Window);
            }
            if ((raw.ButtonFlags & RawInputMouseState.MIDDLE_BUTTON_UP) != 0)
            {
                mouse.DisableBit((int)MouseButton.Middle);
                Functions.ReleaseCapture();
            }
            if ((raw.ButtonFlags & RawInputMouseState.BUTTON_4_DOWN) != 0)
            {
                mouse.EnableBit((int)MouseButton.Button1);
                Functions.SetCapture(Window);
            }
            if ((raw.ButtonFlags & RawInputMouseState.BUTTON_4_UP) != 0)
            {
                mouse.DisableBit((int)MouseButton.Button1);
                Functions.ReleaseCapture();
            }
            if ((raw.ButtonFlags & RawInputMouseState.BUTTON_5_DOWN) != 0)
            {
                mouse.EnableBit((int)MouseButton.Button2);
                Functions.SetCapture(Window);
            }
            if ((raw.ButtonFlags & RawInputMouseState.BUTTON_5_UP) != 0)
            {
                mouse.DisableBit((int)MouseButton.Button2);
                Functions.ReleaseCapture();
            }

            if ((raw.ButtonFlags & RawInputMouseState.WHEEL) != 0)
            {
                mouse.SetScrollRelative(0, (short)raw.ButtonData / 120.0f);
            }

            if ((raw.ButtonFlags & RawInputMouseState.HWHEEL) != 0)
            {
                mouse.SetScrollRelative((short)raw.ButtonData / 120.0f, 0);
            }

            if ((raw.Flags & RawMouseFlags.MOUSE_MOVE_ABSOLUTE) != 0)
            {
                mouse.X = raw.LastX;
                mouse.Y = raw.LastY;
            }
            else
            {   // Seems like MOUSE_MOVE_RELATIVE is the default, unless otherwise noted.
                mouse.X += raw.LastX;
                mouse.Y += raw.LastY;
            }

            lock (UpdateLock)
            {
                mice[mouse_handle] = mouse;
                return(true);
            }
        }
Beispiel #43
0
        public X11GLContext(GraphicsMode mode, IWindowInfo window, IGraphicsContext shared, bool direct,
                            int major, int minor, GraphicsContextFlags flags)
        {
            if (mode == null)
            {
                throw new ArgumentNullException("mode");
            }
            if (window == null)
            {
                throw new ArgumentNullException("window");
            }

            Mode = mode;

            currentWindow            = (X11WindowInfo)window;
            currentWindow.VisualInfo = SelectVisual(mode, currentWindow);

            ContextHandle shareHandle = shared != null ?
                                        (shared as IGraphicsContextInternal).Context : (ContextHandle)IntPtr.Zero;

            Debug.Write("Creating X11GLContext context: ");
            Debug.Write(direct ? "direct, " : "indirect, ");
            Debug.WriteLine(shareHandle.Handle == IntPtr.Zero ? "not shared... " :
                            String.Format("shared with ({0})... ", shareHandle));

            if (!glx_loaded)
            {
                Debug.WriteLine("Creating temporary context to load GLX extensions.");

                // Create a temporary context to obtain the necessary function pointers.
                XVisualInfo visual = currentWindow.VisualInfo;
                IntPtr      ctx    = Glx.CreateContext(currentWindow.Display, ref visual, IntPtr.Zero, true);
                if (ctx == IntPtr.Zero)
                {
                    ctx = Glx.CreateContext(currentWindow.Display, ref visual, IntPtr.Zero, false);
                }

                if (ctx != IntPtr.Zero)
                {
                    new Glx().LoadAll();
                    Glx.MakeCurrent(currentWindow.Display, IntPtr.Zero, IntPtr.Zero);
                    //Glx.DestroyContext(currentWindow.Display, ctx);
                    glx_loaded = true;
                }
            }

            // Try using the new context creation method. If it fails, fall back to the old one.
            // For each of these methods, we try two times to create a context:
            // one with the "direct" flag intact, the other with the flag inversed.
            // HACK: It seems that Catalyst 9.1 - 9.4 on Linux have problems with contexts created through
            // GLX_ARB_create_context, including hideous input lag, no vsync and other. Use legacy context
            // creation if the user doesn't request a 3.0+ context.
            if ((major * 10 + minor >= 30) && Glx.Delegates.glXCreateContextAttribsARB != null)
            {
                Debug.Write("Using GLX_ARB_create_context... ");

                unsafe
                {
                    // We need the FB config for the current GraphicsMode.
                    int     count;
                    IntPtr *fbconfigs = Glx.ChooseFBConfig(currentWindow.Display, currentWindow.Screen,
                                                           new int[] { (int)GLXAttribute.VISUAL_ID, (int)mode.Index, 0 }, out count);

                    if (count > 0)
                    {
                        List <int> attributes = new List <int>();
                        attributes.Add((int)ArbCreateContext.MajorVersion);
                        attributes.Add(major);
                        attributes.Add((int)ArbCreateContext.MinorVersion);
                        attributes.Add(minor);
                        if (flags != 0)
                        {
                            attributes.Add((int)ArbCreateContext.Flags);
                            attributes.Add((int)flags);
                        }
                        attributes.Add(0);

                        Handle = new ContextHandle(Glx.Arb.CreateContextAttribs(currentWindow.Display, *fbconfigs,
                                                                                shareHandle.Handle, direct, attributes.ToArray()));

                        if (Handle == ContextHandle.Zero)
                        {
                            Debug.Write(String.Format("failed. Trying direct: {0}... ", !direct));
                            Handle = new ContextHandle(Glx.Arb.CreateContextAttribs(currentWindow.Display, *fbconfigs,
                                                                                    shareHandle.Handle, !direct, attributes.ToArray()));
                        }

                        if (Handle == ContextHandle.Zero)
                        {
                            Debug.WriteLine("failed.");
                        }
                        else
                        {
                            Debug.WriteLine("success!");
                        }

                        Functions.XFree((IntPtr)fbconfigs);
                    }
                }
            }

            if (Handle == ContextHandle.Zero)
            {
                Debug.Write("Using legacy context creation... ");

                XVisualInfo info = currentWindow.VisualInfo;   // Cannot pass a Property by reference.
                Handle = new ContextHandle(Glx.CreateContext(currentWindow.Display, ref info, shareHandle.Handle, direct));

                if (Handle == ContextHandle.Zero)
                {
                    Debug.WriteLine(String.Format("failed. Trying direct: {0}... ", !direct));
                    Handle = new ContextHandle(Glx.CreateContext(currentWindow.Display, ref info, IntPtr.Zero, !direct));
                }
            }

            if (Handle != ContextHandle.Zero)
            {
                Debug.Print("Context created (id: {0}).", Handle);
            }
            else
            {
                throw new GraphicsContextException("Failed to create OpenGL context. Glx.CreateContext call returned 0.");
            }

            if (!Glx.IsDirect(currentWindow.Display, Handle.Handle))
            {
                Debug.Print("Warning: Context is not direct.");
            }
        }
Beispiel #44
0
        // --- initialization and deinitialization ---

        /// <summary>Initializes audio. A call to Deinitialize must be made when terminating the program.</summary>
        /// <returns>Whether initializing audio was successful.</returns>
        public void Initialize(HostInterface host, SoundRange range)
        {
            Deinitialize();

            CurrentHost = host;

            switch (range)
            {
            case SoundRange.Low:
                OuterRadiusFactorMinimum      = 2.0;
                OuterRadiusFactorMaximum      = 8.0;
                OuterRadiusFactorMaximumSpeed = 1.0;
                break;

            case SoundRange.Medium:
                OuterRadiusFactorMinimum      = 4.0;
                OuterRadiusFactorMaximum      = 16.0;
                OuterRadiusFactorMaximumSpeed = 2.0;
                break;

            case SoundRange.High:
                OuterRadiusFactorMinimum      = 6.0;
                OuterRadiusFactorMaximum      = 24.0;
                OuterRadiusFactorMaximumSpeed = 3.0;
                break;
            }
            OuterRadiusFactor      = Math.Sqrt(OuterRadiusFactorMinimum * OuterRadiusFactorMaximum);
            OuterRadiusFactorSpeed = 0.0;
            OpenAlDevice           = Alc.OpenDevice(null);
            try
            {
                OpenAlMic = new AudioCapture(AudioCapture.DefaultDevice, SamplingRate, ALFormat.Mono16, BufferSize);
            }
            catch
            {
            }

            if (OpenAlDevice != IntPtr.Zero)
            {
                OpenAlContext = Alc.CreateContext(OpenAlDevice, (int[])null);
                if (OpenAlContext != ContextHandle.Zero)
                {
                    Alc.MakeContextCurrent(OpenAlContext);
                    try
                    {
                        AL.SpeedOfSound(343.0f);
                    }
                    catch
                    {
                        MessageBox.Show(Translations.GetInterfaceString("errors_sound_openal_version"), Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
                    AL.DistanceModel(ALDistanceModel.None);
                    return;
                }
                Alc.CloseDevice(OpenAlDevice);
                OpenAlDevice = IntPtr.Zero;
                OpenAlMic.Dispose();
                OpenAlMic = null;
                MessageBox.Show(Translations.GetInterfaceString("errors_sound_openal_context"), Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }
            OpenAlContext = ContextHandle.Zero;
            MessageBox.Show(Translations.GetInterfaceString("errors_sound_openal_device"), Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
        }
Beispiel #45
0
 public static void DestroyContext(IntPtr dpy, ContextHandle context)
 {
     DestroyContext(dpy, context.Handle);
 }
Beispiel #46
0
 /// <summary>
 /// Constructs a new GraphicsContext from a pre-existing context created outside of OpenTK.
 /// </summary>
 /// <param name="handle">The handle of the existing context. This must be a valid, unique handle that is not known to OpenTK.</param>
 /// <param name="window">This parameter is reserved.</param>
 /// <param name="shareContext">This parameter is reserved.</param>
 /// <param name="major">This parameter is reserved.</param>
 /// <param name="minor">This parameter is reserved.</param>
 /// <param name="flags">This parameter is reserved..</param>
 public GraphicsContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, int major, int minor, GraphicsContextFlags flags)
     : this(handle, Platform.Utilities.CreateGetAddress(), Factory.Default.CreateGetCurrentGraphicsContext())
 {
 }
Beispiel #47
0
 public DummyGLContext(ContextHandle handle)
 {
     Handle = handle;
 }
Beispiel #48
0
 /// <summary>
 /// Constructs a new GraphicsContext from a pre-existing context created outside of OpenTK.
 /// </summary>
 /// <param name="handle">The handle of the existing context. This must be a valid, unique handle that is not known to OpenTK.</param>
 /// <param name="window">This parameter is reserved.</param>
 public GraphicsContext(ContextHandle handle, IWindowInfo window)
     : this(handle, window, null, 1, 0, GraphicsContextFlags.Default)
 {
 }
Beispiel #49
0
        public WinGLContext(GraphicsMode format, WinWindowInfo window, IGraphicsContext sharedContext,
                            int major, int minor, GraphicsContextFlags flags)
        {
            // There are many ways this code can break when accessed by multiple threads. The biggest offender is
            // the sharedContext stuff, which will only become valid *after* this constructor returns.
            // The easiest solution is to serialize all context construction - hence the big lock, below.
            lock (LoadLock)
            {
                if (window == null)
                {
                    throw new ArgumentNullException("window", "Must point to a valid window.");
                }
                if (window.Handle == IntPtr.Zero)
                {
                    throw new ArgumentException("window", "Must be a valid window.");
                }

                IntPtr           current_context = Wgl.GetCurrentContext();
                INativeWindow    temp_window     = null;
                TemporaryContext temp_context    = null;
                try
                {
                    if (current_context == IntPtr.Zero)
                    {
                        // Create temporary context to load WGL extensions
                        temp_window     = new NativeWindow();
                        temp_context    = new TemporaryContext(temp_window);
                        current_context = Wgl.GetCurrentContext();
                        if (current_context != IntPtr.Zero && current_context == temp_context.Context.Handle)
                        {
                            new Wgl().LoadEntryPoints();
                        }
                    }

                    Debug.Print("OpenGL will be bound to window:{0} on thread:{1}", window.Handle,
                                System.Threading.Thread.CurrentThread.ManagedThreadId);

                    ModeSelector = new WinGraphicsMode(window.DeviceContext);
                    Mode         = SetGraphicsModePFD(ModeSelector, format, (WinWindowInfo)window);

                    if (Wgl.SupportsFunction("wglCreateContextAttribsARB"))
                    {
                        try
                        {
                            Debug.Write("Using WGL_ARB_create_context... ");

                            List <int> attributes = new List <int>();
                            attributes.Add((int)ArbCreateContext.MajorVersion);
                            attributes.Add(major);
                            attributes.Add((int)ArbCreateContext.MinorVersion);
                            attributes.Add(minor);
                            if (flags != 0)
                            {
                                attributes.Add((int)ArbCreateContext.ContextFlags);
                                attributes.Add((int)GetARBContextFlags(flags));
                                attributes.Add((int)ArbCreateContext.ProfileMask);
                                attributes.Add((int)GetARBContextProfile(flags));
                            }
                            // According to the docs, " <attribList> specifies a list of attributes for the context.
                            // The list consists of a sequence of <name,value> pairs terminated by the
                            // value 0. [...]"
                            // Is this a single 0, or a <0, 0> pair? (Defensive coding: add two zeroes just in case).
                            attributes.Add(0);
                            attributes.Add(0);

                            Handle = new ContextHandle(
                                Wgl.Arb.CreateContextAttribs(
                                    window.DeviceContext,
                                    sharedContext != null ? (sharedContext as IGraphicsContextInternal).Context.Handle : IntPtr.Zero,
                                    attributes.ToArray()));
                            if (Handle == ContextHandle.Zero)
                            {
                                Debug.Print("failed. (Error: {0})", Marshal.GetLastWin32Error());
                            }
                        }
                        catch (Exception e) { Debug.Print(e.ToString()); }
                    }

                    if (Handle == ContextHandle.Zero)
                    {
                        // Failed to create GL3-level context, fall back to GL2.
                        Debug.Write("Falling back to GL2... ");
                        Handle = new ContextHandle(Wgl.CreateContext(window.DeviceContext));
                        if (Handle == ContextHandle.Zero)
                        {
                            Handle = new ContextHandle(Wgl.CreateContext(window.DeviceContext));
                        }
                        if (Handle == ContextHandle.Zero)
                        {
                            throw new GraphicsContextException(
                                      String.Format("Context creation failed. Wgl.CreateContext() error: {0}.",
                                                    Marshal.GetLastWin32Error()));
                        }
                    }

                    Debug.WriteLine(String.Format("success! (id: {0})", Handle));
                }
                finally
                {
                    if (temp_context != null)
                    {
                        temp_context.Dispose();
                        temp_context = null;
                    }
                    if (temp_window != null)
                    {
                        temp_window.Dispose();
                        temp_window = null;
                    }
                }
            }

            // Todo: is this comment still true?
            // On intel drivers, wgl entry points appear to change
            // when creating multiple contexts. As a workaround,
            // we reload Wgl entry points every time we create a
            // new context - this solves the issue without any apparent
            // side-effects (i.e. the old contexts can still be handled
            // using the new entry points.)
            // Sigh...
            MakeCurrent(window);
            new Wgl().LoadEntryPoints();

            if (sharedContext != null)
            {
                Marshal.GetLastWin32Error();
                Debug.Write(String.Format("Sharing state with context {0}: ", sharedContext));
                bool result = Wgl.ShareLists((sharedContext as IGraphicsContextInternal).Context.Handle, Handle.Handle);
                Debug.WriteLine(result ? "success!" : "failed with win32 error " + Marshal.GetLastWin32Error());
            }
        }
Beispiel #50
0
 public virtual IGraphicsContext CreateGLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
 {
     return((IGraphicsContext) new AglContext(handle, window, shareContext));
 }
Beispiel #51
0
        void CreateContext(GraphicsMode mode, CarbonWindowInfo carbonWindow, IntPtr shareContextRef, bool fullscreen)
        {
            Debug.Print("AGL pixel format attributes:");

            AGLPixelFormat myAGLPixelFormat;

            // Choose a pixel format with the attributes we specified.
            if (fullscreen)
            {
                IntPtr gdevice;
                IntPtr cgdevice = GetQuartzDevice(carbonWindow);

                if (cgdevice == IntPtr.Zero)
                {
                    cgdevice = (IntPtr)DisplayDevice.Default.Id;
                }

                OSStatus status = Carbon.API.DMGetGDeviceByDisplayID(cgdevice, out gdevice, false);

                if (status != OSStatus.NoError)
                {
                    throw new MacOSException(status, "DMGetGDeviceByDisplayID failed.");
                }

                myAGLPixelFormat = ModeSelector.SelectPixelFormat(
                    mode.ColorFormat, mode.Depth, mode.Stencil, mode.Samples,
                    mode.AccumulatorFormat, mode.Buffers, mode.Stereo,
                    true, gdevice);

                Agl.AglError err = Agl.GetError();
                if (myAGLPixelFormat == IntPtr.Zero || err == Agl.AglError.BadPixelFormat)
                {
                    Debug.Print("Failed to create full screen pixel format.");
                    Debug.Print("Trying again to create a non-fullscreen pixel format.");

                    CreateContext(mode, carbonWindow, shareContextRef, false);
                    return;
                }
            }
            else
            {
                myAGLPixelFormat = ModeSelector.SelectPixelFormat(
                    mode.ColorFormat, mode.Depth, mode.Stencil, mode.Samples,
                    mode.AccumulatorFormat, mode.Buffers, mode.Stereo,
                    false, IntPtr.Zero);
                MyAGLReportError("aglChoosePixelFormat");
            }

            Debug.Print("Creating AGL context.  Sharing with {0}", shareContextRef);

            // create the context and share it with the share reference.
            Handle = new ContextHandle(Agl.aglCreateContext(myAGLPixelFormat, shareContextRef));
            MyAGLReportError("aglCreateContext");

            Mode = ModeSelector.GetGraphicsModeFromPixelFormat(myAGLPixelFormat);

            // Free the pixel format from memory.
            Agl.aglDestroyPixelFormat(myAGLPixelFormat);
            MyAGLReportError("aglDestroyPixelFormat");

            Debug.Print("IsControl: {0}", carbonWindow.IsControl);

            SetDrawable(carbonWindow);
            SetBufferRect(carbonWindow);
            Update(carbonWindow);

            MakeCurrent(carbonWindow);
            Debug.Print("context: {0}", Handle.Handle);
        }
Beispiel #52
0
        public override IGraphicsContext CreateGLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
        {
            AndroidWindow android_win = (AndroidWindow)window;

            return(new Android.AndroidGraphicsContext(handle, android_win.CreateEglWindowInfo(), shareContext, major, minor, flags));
        }
Beispiel #53
0
        public X11GLContext(GraphicsMode mode, IWindowInfo window, IGraphicsContext shared, bool direct,
                            int major, int minor, GraphicsContextFlags flags)
        {
            if (mode == null)
            {
                throw new ArgumentNullException("mode");
            }
            if (window == null)
            {
                throw new ArgumentNullException("window");
            }

            Mode = ModeSelector.SelectGraphicsMode(
                mode.ColorFormat, mode.Depth, mode.Stencil, mode.Samples,
                mode.AccumulatorFormat, mode.Buffers, mode.Stereo);

            // Do not move this lower, as almost everything requires the Display
            // property to be correctly set.
            Display = ((X11WindowInfo)window).Display;

            currentWindow            = (X11WindowInfo)window;
            currentWindow.VisualInfo = SelectVisual(Mode, currentWindow);

            ContextHandle shareHandle = shared != null ?
                                        (shared as IGraphicsContextInternal).Context : (ContextHandle)IntPtr.Zero;

            Debug.Write("Creating X11GLContext context: ");
            Debug.Write(direct ? "direct, " : "indirect, ");
            Debug.WriteLine(shareHandle.Handle == IntPtr.Zero ? "not shared... " :
                            String.Format("shared with ({0})... ", shareHandle));

            // Try using the new context creation method. If it fails, fall back to the old one.
            // For each of these methods, we try two times to create a context:
            // one with the "direct" flag intact, the other with the flag inversed.
            // HACK: It seems that Catalyst 9.1 - 9.4 on Linux have problems with contexts created through
            // GLX_ARB_create_context, including hideous input lag, no vsync and other madness.
            // Use legacy context creation if the user doesn't request a 3.0+ context.
            if ((major * 10 + minor >= 30) && SupportsCreateContextAttribs(Display, currentWindow))
            {
                Debug.Write("Using GLX_ARB_create_context... ");

                unsafe
                {
                    // We need the FB config for the current GraphicsMode.
                    int     count;
                    IntPtr *fbconfigs = Glx.ChooseFBConfig(Display, currentWindow.Screen,
                                                           new int[] {
                        (int)GLXAttribute.VISUAL_ID,
                        (int)Mode.Index,
                        0
                    }, out count);

                    if (count > 0)
                    {
                        List <int> attributes = new List <int>();
                        attributes.Add((int)ArbCreateContext.MajorVersion);
                        attributes.Add(major);
                        attributes.Add((int)ArbCreateContext.MinorVersion);
                        attributes.Add(minor);
                        if (flags != 0)
                        {
                            attributes.Add((int)ArbCreateContext.Flags);
                            attributes.Add((int)GetARBContextFlags(flags));
                            attributes.Add((int)ArbCreateContext.ProfileMask);
                            attributes.Add((int)GetARBProfileFlags(flags));
                        }
                        // According to the docs, " <attribList> specifies a list of attributes for the context.
                        // The list consists of a sequence of <name,value> pairs terminated by the
                        // value 0. [...]"
                        // Is this a single 0, or a <0, 0> pair? (Defensive coding: add two zeroes just in case).
                        attributes.Add(0);
                        attributes.Add(0);

                        using (new XLock(Display))
                        {
                            Handle = new ContextHandle(Glx.Arb.CreateContextAttribs(Display, *fbconfigs,
                                                                                    shareHandle.Handle, direct, attributes.ToArray()));

                            if (Handle == ContextHandle.Zero)
                            {
                                Debug.Write(String.Format("failed. Trying direct: {0}... ", !direct));
                                Handle = new ContextHandle(Glx.Arb.CreateContextAttribs(Display, *fbconfigs,
                                                                                        shareHandle.Handle, !direct, attributes.ToArray()));
                            }
                        }

                        if (Handle == ContextHandle.Zero)
                        {
                            Debug.WriteLine("failed.");
                        }
                        else
                        {
                            Debug.WriteLine("success!");
                        }

                        using (new XLock(Display))
                        {
                            Functions.XFree((IntPtr)fbconfigs);
                        }
                    }
                }
            }

            if (Handle == ContextHandle.Zero)
            {
                Debug.Write("Using legacy context creation... ");

                XVisualInfo info = currentWindow.VisualInfo;
                using (new XLock(Display))
                {
                    // Cannot pass a Property by reference.
                    Handle = new ContextHandle(Glx.CreateContext(Display, ref info, shareHandle.Handle, direct));

                    if (Handle == ContextHandle.Zero)
                    {
                        Debug.WriteLine(String.Format("failed. Trying direct: {0}... ", !direct));
                        Handle = new ContextHandle(Glx.CreateContext(Display, ref info, IntPtr.Zero, !direct));
                    }
                }
            }

            if (Handle != ContextHandle.Zero)
            {
                Debug.Print("Context created (id: {0}).", Handle);
            }
            else
            {
                throw new GraphicsContextException("Failed to create OpenGL context. Glx.CreateContext call returned 0.");
            }

            using (new XLock(Display))
            {
                if (!Glx.IsDirect(Display, Handle.Handle))
                {
                    Debug.Print("Warning: Context is not direct.");
                }
            }
        }
Beispiel #54
0
        // --- initialization and deinitialization ---

        /// <summary>Initializes audio. A call to Deinitialize must be made when terminating the program.</summary>
        /// <returns>Whether initializing audio was successful.</returns>
        public void Initialize(HostInterface host, SoundRange range)
        {
            if (host.Platform == HostPlatform.MicrosoftWindows)
            {
                /*
                 *  If shipping an AnyCPU build and OpenALSoft / SDL, these are architecture specific PInvokes
                 *  Add the appropriate search path so this will work (common convention)
                 */
                string path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                path = Path.Combine(path, IntPtr.Size == 4 ? "x86" : "x64");
                bool ok = SetDllDirectory(path);
                if (!ok)
                {
                    throw new System.ComponentModel.Win32Exception();
                }
            }
            Deinitialize();

            CurrentHost = host;

            switch (range)
            {
            case SoundRange.Low:
                OuterRadiusFactorMinimum      = 2.0;
                OuterRadiusFactorMaximum      = 8.0;
                OuterRadiusFactorMaximumSpeed = 1.0;
                break;

            case SoundRange.Medium:
                OuterRadiusFactorMinimum      = 4.0;
                OuterRadiusFactorMaximum      = 16.0;
                OuterRadiusFactorMaximumSpeed = 2.0;
                break;

            case SoundRange.High:
                OuterRadiusFactorMinimum      = 6.0;
                OuterRadiusFactorMaximum      = 24.0;
                OuterRadiusFactorMaximumSpeed = 3.0;
                break;
            }
            OuterRadiusFactor      = Math.Sqrt(OuterRadiusFactorMinimum * OuterRadiusFactorMaximum);
            OuterRadiusFactorSpeed = 0.0;
            OpenAlDevice           = Alc.OpenDevice(null);
            string deviceName = Alc.GetString(OpenAlDevice, AlcGetString.DefaultDeviceSpecifier);

            if ((Environment.OSVersion.Platform == PlatformID.Win32S | Environment.OSVersion.Platform == PlatformID.Win32Windows | Environment.OSVersion.Platform == PlatformID.Win32NT) && deviceName == "Generic Software")
            {
                /*
                 * Creative OpenAL implementation on Windows seems to be limited to max 16 simulataneous sounds
                 * Now shipping OpenAL Soft, but detect this and don't glitch
                 * Further note that the current version of OpenAL Soft (1.20.0 at the time of writing) does not like OpenTK
                 * The version in use is 1.17.0 found here: https://openal-soft.org/openal-binaries/
                 */
                systemMaxSounds = 16;
            }
            try
            {
                OpenAlMic = new AudioCapture(AudioCapture.DefaultDevice, SamplingRate, ALFormat.Mono16, BufferSize);
            }
            catch
            {
                OpenAlMic = null;
            }

            if (OpenAlDevice != IntPtr.Zero)
            {
                OpenAlContext = Alc.CreateContext(OpenAlDevice, (int[])null);
                if (OpenAlContext != ContextHandle.Zero)
                {
                    Alc.MakeContextCurrent(OpenAlContext);
                    try
                    {
                        AL.SpeedOfSound(343.0f);
                    }
                    catch
                    {
                        MessageBox.Show(Translations.GetInterfaceString("errors_sound_openal_version"), Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
                    AL.DistanceModel(ALDistanceModel.None);
                    return;
                }
                Alc.CloseDevice(OpenAlDevice);
                OpenAlDevice = IntPtr.Zero;
                if (OpenAlMic != null)
                {
                    OpenAlMic.Dispose();
                    OpenAlMic = null;
                }
                MessageBox.Show(Translations.GetInterfaceString("errors_sound_openal_context"), Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }
            OpenAlContext = ContextHandle.Zero;
            MessageBox.Show(Translations.GetInterfaceString("errors_sound_openal_device"), Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
        }
Beispiel #55
0
        void CreateContext(GraphicsMode mode, CarbonWindowInfo carbonWindow,
                           IntPtr shareContextRef, bool fullscreen)
        {
            List <int> aglAttributes = new  List <int>();

            Debug.Print("AGL pixel format attributes:");
            Debug.Indent();

            AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_RGBA);
            AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_DOUBLEBUFFER);
            AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_RED_SIZE, mode.ColorFormat.Red);
            AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_GREEN_SIZE, mode.ColorFormat.Green);
            AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_BLUE_SIZE, mode.ColorFormat.Blue);
            AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_ALPHA_SIZE, mode.ColorFormat.Alpha);

            if (mode.Depth > 0)
            {
                AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_DEPTH_SIZE, mode.Depth);
            }

            if (mode.Stencil > 0)
            {
                AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_STENCIL_SIZE, mode.Stencil);
            }

            if (mode.AccumulatorFormat.BitsPerPixel > 0)
            {
                AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_ACCUM_RED_SIZE, mode.AccumulatorFormat.Red);
                AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_ACCUM_GREEN_SIZE, mode.AccumulatorFormat.Green);
                AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_ACCUM_BLUE_SIZE, mode.AccumulatorFormat.Blue);
                AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_ACCUM_ALPHA_SIZE, mode.AccumulatorFormat.Alpha);
            }

            if (mode.Samples > 0)
            {
                AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_SAMPLE_BUFFERS_ARB, 1);
                AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_SAMPLES_ARB, mode.Samples);
            }

            if (fullscreen)
            {
                AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_FULLSCREEN);
            }
            AddPixelAttrib(aglAttributes, Agl.PixelFormatAttribute.AGL_NONE);

            Debug.Unindent();

            Debug.Write("Attribute array:  ");
            for (int i = 0; i < aglAttributes.Count; i++)
            {
                Debug.Write(aglAttributes[i].ToString() + "  ");
            }
            Debug.WriteLine("");

            AGLPixelFormat myAGLPixelFormat;

            // Choose a pixel format with the attributes we specified.
            if (fullscreen)
            {
                IntPtr gdevice;

                OSStatus status = Carbon.API.DMGetGDeviceByDisplayID(
                    QuartzDisplayDeviceDriver.MainDisplay, out gdevice, false);

                if (status != OSStatus.NoError)
                {
                    throw new MacOSException(status, "DMGetGDeviceByDisplayID failed.");
                }

                myAGLPixelFormat = Agl.aglChoosePixelFormat(
                    ref gdevice, 1,
                    aglAttributes.ToArray());

                Agl.AglError err = Agl.GetError();

                if (err == Agl.AglError.BadPixelFormat)
                {
                    Debug.Print("Failed to create full screen pixel format.");
                    Debug.Print("Trying again to create a non-fullscreen pixel format.");

                    CreateContext(mode, carbonWindow, shareContextRef, false);
                    return;
                }
            }
            else
            {
                myAGLPixelFormat = Agl.aglChoosePixelFormat(
                    IntPtr.Zero, 0,
                    aglAttributes.ToArray());

                MyAGLReportError("aglChoosePixelFormat");
            }


            // create the context and share it with the share reference.
            Handle = new ContextHandle(Agl.aglCreateContext(myAGLPixelFormat, shareContextRef));
            MyAGLReportError("aglCreateContext");

            // Free the pixel format from memory.
            Agl.aglDestroyPixelFormat(myAGLPixelFormat);
            MyAGLReportError("aglDestroyPixelFormat");

            Debug.Print("IsControl: {0}", carbonWindow.IsControl);

            SetDrawable(carbonWindow);
            SetBufferRect(carbonWindow);
            Update(carbonWindow);

            MakeCurrent(carbonWindow);

            Debug.Print("context: {0}", Handle.Handle);
        }
Beispiel #56
0
 public override IGraphicsContext CreateGLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
 {
     throw new NotImplementedException();
 }
Beispiel #57
0
        public void RefreshDevices()
        {
            lock (UpdateLock)
            {
                // Mark all devices as disconnected. We will check which of those
                // are connected later on.
                for (int i = 0; i < mice.Count; i++)
                {
                    MouseState state = mice[i];
                    state.IsConnected = false;
                    mice[i]           = state;
                }

                int count = WinRawInput.DeviceCount;
                RawInputDeviceList[] ridl = new RawInputDeviceList[count];
                for (int i = 0; i < count; i++)
                {
                    ridl[i] = new RawInputDeviceList();
                }
                Functions.GetRawInputDeviceList(ridl, ref count, API.RawInputDeviceListSize);

                // Discover mouse devices
                foreach (RawInputDeviceList dev in ridl)
                {
                    ContextHandle id = new ContextHandle(dev.Device);
                    if (rawids.ContainsKey(id))
                    {
                        // Device already registered, mark as connected
                        MouseState state = mice[rawids[id]];
                        state.IsConnected = true;
                        mice[rawids[id]]  = state;
                        continue;
                    }

                    // Unregistered device, find what it is
                    string name = GetDeviceName(dev);
                    if (name.ToLower().Contains("root"))
                    {
                        // This is a terminal services device, skip it.
                        continue;
                    }
                    else if (dev.Type == RawInputDeviceType.MOUSE || dev.Type == RawInputDeviceType.HID)
                    {
                        // This is a mouse or a USB mouse device. In the latter case, discover if it really is a
                        // mouse device by qeurying the registry.
                        RegistryKey regkey = FindRegistryKey(name);
                        if (regkey == null)
                        {
                            continue;
                        }

                        string deviceDesc  = (string)regkey.GetValue("DeviceDesc");
                        string deviceClass = (string)regkey.GetValue("Class") as string;
                        if (deviceClass == null)
                        {
                            // Added to address OpenTK issue 3198 with mouse on Windows 8
                            string      deviceClassGUID = (string)regkey.GetValue("ClassGUID");
                            RegistryKey classGUIDKey    = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Class\" + deviceClassGUID);
                            deviceClass = classGUIDKey != null ? (string)classGUIDKey.GetValue("Class") : string.Empty;
                        }

                        // deviceDesc remained null on a new Win7 system - not sure why.
                        // Since the description is not vital information, use a dummy description
                        // when that happens.
                        if (String.IsNullOrEmpty(deviceDesc))
                        {
                            deviceDesc = "Windows Mouse " + mice.Count;
                        }
                        else
                        {
                            deviceDesc = deviceDesc.Substring(deviceDesc.LastIndexOf(';') + 1);
                        }

                        if (!String.IsNullOrEmpty(deviceClass) && deviceClass.ToLower().Equals("mouse"))
                        {
                            if (!rawids.ContainsKey(new ContextHandle(dev.Device)))
                            {
                                // Register the device:
                                RawInputDeviceInfo info = new RawInputDeviceInfo();
                                int devInfoSize         = API.RawInputDeviceInfoSize;
                                Functions.GetRawInputDeviceInfo(dev.Device, RawInputDeviceInfoEnum.DEVICEINFO,
                                                                info, ref devInfoSize);

                                RegisterRawDevice(Window, deviceDesc);
                                MouseState state = new MouseState();
                                state.IsConnected = true;
                                mice.Add(state);
                                names.Add(deviceDesc);
                                rawids.Add(new ContextHandle(dev.Device), mice.Count - 1);
                            }
                        }
                    }
                }
            }
        }
Beispiel #58
0
        public WinGLContext(GraphicsMode format, WinWindowInfo window, IGraphicsContext sharedContext,
                            int major, int minor, GraphicsContextFlags flags)
        {
            // There are many ways this code can break when accessed by multiple threads. The biggest offender is
            // the sharedContext stuff, which will only become valid *after* this constructor returns.
            // The easiest solution is to serialize all context construction - hence the big lock, below.
            lock (SyncRoot)
            {
                if (window == null)
                {
                    throw new ArgumentNullException("window", "Must point to a valid window.");
                }
                if (window.WindowHandle == IntPtr.Zero)
                {
                    throw new ArgumentException("window", "Must be a valid window.");
                }

                Mode = format;

                Debug.Print("OpenGL will be bound to window:{0} on thread:{1}", window.WindowHandle,
                            System.Threading.Thread.CurrentThread.ManagedThreadId);
                this.SetGraphicsModePFD(format, (WinWindowInfo)window);

                lock (LoadLock)
                {
                    if (!wgl_loaded)
                    {
                        // We need to create a temp context in order to load wgl extensions (e.g. for multisampling or GL3).
                        // We cannot rely on OpenTK.Platform.Wgl until we create the context and call Wgl.LoadAll().
                        Debug.Print("Creating temporary context for wgl extensions.");
                        ContextHandle temp_context = new ContextHandle(Wgl.Imports.CreateContext(window.DeviceContext));
                        Wgl.Imports.MakeCurrent(window.DeviceContext, temp_context.Handle);
                        Wgl.LoadAll();
                        Wgl.Imports.MakeCurrent(IntPtr.Zero, IntPtr.Zero);
                        Wgl.Imports.DeleteContext(temp_context.Handle);
                        wgl_loaded = true;
                    }

                    if (Wgl.Delegates.wglCreateContextAttribsARB != null)
                    {
                        try
                        {
                            Debug.Write("Using WGL_ARB_create_context... ");

                            List <int> attributes = new List <int>();
                            attributes.Add((int)ArbCreateContext.MajorVersion);
                            attributes.Add(major);
                            attributes.Add((int)ArbCreateContext.MinorVersion);
                            attributes.Add(minor);
                            if (flags != 0)
                            {
                                attributes.Add((int)ArbCreateContext.Flags);
#warning "This is not entirely correct: Embedded is not a valid flag! We need to add a GetARBContextFlags(GraphicsContextFlags) method."
                                attributes.Add((int)flags);
                            }
                            // According to the docs, " <attribList> specifies a list of attributes for the context.
                            // The list consists of a sequence of <name,value> pairs terminated by the
                            // value 0. [...]"
                            // Is this a single 0, or a <0, 0> pair? (Defensive coding: add two zeroes just in case).
                            attributes.Add(0);
                            attributes.Add(0);

                            Handle = new ContextHandle(
                                Wgl.Arb.CreateContextAttribs(
                                    window.DeviceContext,
                                    sharedContext != null ? (sharedContext as IGraphicsContextInternal).Context.Handle : IntPtr.Zero,
                                    attributes.ToArray()));
                            if (Handle == ContextHandle.Zero)
                            {
                                Debug.Print("failed. (Error: {0})", Marshal.GetLastWin32Error());
                            }
                        }
                        catch (EntryPointNotFoundException e) { Debug.Print(e.ToString()); }
                        catch (NullReferenceException e) { Debug.Print(e.ToString()); }
                    }
                }

                if (Handle == ContextHandle.Zero)
                {
                    // Failed to create GL3-level context, fall back to GL2.
                    Debug.Write("Falling back to GL2... ");
                    Handle = new ContextHandle(Wgl.Imports.CreateContext(window.DeviceContext));
                    if (Handle == ContextHandle.Zero)
                    {
                        Handle = new ContextHandle(Wgl.Imports.CreateContext(window.DeviceContext));
                    }
                    if (Handle == ContextHandle.Zero)
                    {
                        throw new GraphicsContextException(
                                  String.Format("Context creation failed. Wgl.CreateContext() error: {0}.",
                                                Marshal.GetLastWin32Error()));
                    }
                }

                Debug.WriteLine(String.Format("success! (id: {0})", Handle));

                if (sharedContext != null)
                {
                    Marshal.GetLastWin32Error();
                    Debug.Write(String.Format("Sharing state with context {0}: ", sharedContext));
                    bool result = Wgl.Imports.ShareLists((sharedContext as IGraphicsContextInternal).Context.Handle, Handle.Handle);
                    Debug.WriteLine(result ? "success!" : "failed with win32 error " + Marshal.GetLastWin32Error());
                }
            }
        }
Beispiel #59
0
 public virtual IGraphicsContext CreateGLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
 {
     return new X11GLContext(handle, window, shareContext, directRendering, major, minor, flags);
 }
Beispiel #60
0
 public IGraphicsContext CreateGLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
 {
     return(default_implementation.CreateGLContext(handle, window, shareContext, directRendering, major, minor, flags));
 }