Beispiel #1
0
        public GL(IntPtr windowHandle)
        {
            if (GetCurrent(false) != null)
            {
                throw new GLException("GLContext already exists in current thread. Try launching in different thread");
            }

            if (windowHandle == IntPtr.Zero)
            {
                throw new ArgumentException("windowHandle");
            }

            lock (_locker) {
                NativeMethods.LoadDLLs();

                _deviceContextPtr = NativeMethods.GetDeviceContext(windowHandle);
                Assert.False(_deviceContextPtr == IntPtr.Zero);

                var pixelFormatDescriptor = PixelFormatDescriptor.CreateDefault();
                var pixelformat           = NativeMethods.ChoosePixelFormat(_deviceContextPtr, ref pixelFormatDescriptor);
                Assert.False(pixelformat == 0);

                var success = NativeMethods.SetPixelFormat(_deviceContextPtr, pixelformat, ref pixelFormatDescriptor);
                Assert.True(success);

                _renderingContextPtr = NativeMethods.CreateContext(_deviceContextPtr);

                if (MakeCurrent() == false)
                {
                    MakeCurrentEmpty();
                    NativeMethods.DeleteContext(_renderingContextPtr);

                    var error = "Error making created context current.";
                    Log.Error(error);
                    throw new GLException(error);
                }

                LoadExtensions();
                LoadConstants();

                Log.Info(string.Format("Initialized GL context version: {0}.", Version));
                if (Version < new GLVersion(4, 0))
                {
                    Dispose();

                    var error = string.Format("Only OpenGL 4.0 and higher versions supported. You have {0}", Version);
                    Log.Error(error);
                    throw new GLException(error);
                }

                SetupDebugCallback();

                _currentContext.Value = this;

                _textures = new uint[MaxTextureUnits];
                ActiveTexture(TextureUnit.Texture0);

                CheckForError();
            }
        }
Beispiel #2
0
        public static RenderingContext FromBitmapInfo(
            BitmapInfo bitmapInfo,
            PixelFormatDescriptor pfd,
            out IntPtr bitmapHandle)
        {
            IntPtr dc           = WGL.GetDC(IntPtr.Zero);
            IntPtr compatibleDc = WGL.CreateCompatibleDC(dc);

            WGL.ReleaseDC(IntPtr.Zero, dc);
            IntPtr ppvBits;

            bitmapHandle = WGL.CreateDIBSection(compatibleDc, ref bitmapInfo, DIBDataType.RgbColors, out ppvBits, IntPtr.Zero, 0U);
            if (bitmapHandle == IntPtr.Zero)
            {
                throw new InternalException("Error in CreateDIBSection", (Exception) new Win32Exception(Marshal.GetLastWin32Error()));
            }
            if (WGL.SelectObject(compatibleDc, bitmapHandle) == IntPtr.Zero)
            {
                throw new InternalException("SelectObject failed");
            }
            int    pixelFormatIndex = RenderingContext.smethod_0(compatibleDc, pfd);
            IntPtr context          = WGL.wglCreateContext(compatibleDc);

            if (context == IntPtr.Zero)
            {
                throw new InternalException("Error in wglCreateContext", (Exception) new Win32Exception(Marshal.GetLastWin32Error()));
            }
            return(new RenderingContext(IntPtr.Zero, compatibleDc, true, context, pixelFormatIndex));
        }
Beispiel #3
0
        // Note: there is no relevant ARB function.
        internal static GraphicsMode SetGraphicsModePFD(WinGraphicsMode mode_selector,
                                                        GraphicsMode mode, WinWindowInfo window)
        {
            Debug.Write("Setting pixel format... ");
            if (window == null)
            {
                throw new ArgumentNullException("window", "Must point to a valid window.");
            }

            if (!mode.Index.HasValue)
            {
                mode = mode_selector.SelectGraphicsMode(
                    mode.ColorFormat, mode.Depth, mode.Stencil,
                    mode.Samples, mode.AccumulatorFormat,
                    mode.Buffers, mode.Stereo);
            }

            PixelFormatDescriptor pfd = new PixelFormatDescriptor();

            Functions.DescribePixelFormat(
                window.DeviceContext, (int)mode.Index.Value,
                API.PixelFormatDescriptorSize, ref pfd);

            Debug.WriteLine(mode.Index.ToString());

            if (!Functions.SetPixelFormat(window.DeviceContext, (int)mode.Index.Value, ref pfd))
            {
                throw new GraphicsContextException(String.Format(
                                                       "Requested GraphicsMode not available. SetPixelFormat error: {0}",
                                                       Marshal.GetLastWin32Error()));
            }

            return(mode);
        }
 public PixelFormat(DeviceContext dc, ref PixelFormatDescriptor pfd)
 {
     m_Index              = 0;
     m_Descriptor         = pfd;
     m_Descriptor.Size    = PixelFormatDescriptor.StructSize;
     m_Descriptor.Version = 1;
     m_Index              = IGE.Platform.Win32.API.Externals.ChoosePixelFormat(dc.Handle, ref m_Descriptor);
 }
Beispiel #5
0
        public static IntPtr CreateContext(ref IntPtr windowHandle, FramebufferFormat framebufferFormat, int major, int minor, OpenGLContextFlags flags, bool directRendering, IntPtr shareContext)
        {
            EnsureInit();

            bool hasTempWindow = windowHandle == IntPtr.Zero;

            if (hasTempWindow)
            {
                windowHandle = Win32Helper.CreateNativeWindow(WindowStylesEx.WS_EX_OVERLAPPEDWINDOW,
                                                              WindowStyles.WS_CLIPSIBLINGS | WindowStyles.WS_CLIPCHILDREN,
                                                              "SPB intermediary context",
                                                              0, 0, 1, 1);
            }

            IntPtr dcHandle = GetDC(windowHandle);

            int pixelFormat = FindPerfectFormat(dcHandle, framebufferFormat);

            // Perfect match not availaible, search for the closest
            if (pixelFormat == -1)
            {
                pixelFormat = FindClosestFormat(dcHandle, framebufferFormat);
            }

            if (pixelFormat == -1)
            {
                throw new PlatformException("Cannot find a valid pixel format");
            }

            PixelFormatDescriptor pfd = PixelFormatDescriptor.Create();

            int res = DescribePixelFormat(dcHandle, pixelFormat, Marshal.SizeOf <PixelFormatDescriptor>(), ref pfd);

            if (res == 0)
            {
                throw new PlatformException($"DescribePixelFormat failed: {Marshal.GetLastWin32Error()}");
            }

            res = SetPixelFormat(dcHandle, pixelFormat, ref pfd);

            if (res == 0)
            {
                throw new PlatformException($"DescribePixelFormat failed: {Marshal.GetLastWin32Error()}");
            }

            List <int> contextAttributes = GetContextCreationARBAttribute(major, minor, flags);

            IntPtr context = CreateContextAttribsArb(dcHandle, shareContext, contextAttributes.ToArray());

            ReleaseDC(windowHandle, dcHandle);

            if (hasTempWindow)
            {
                DestroyWindow(windowHandle);
            }

            return(context);
        }
 public PixelFormat(DeviceContext dc, int index)
 {
     m_Index      = 0;
     m_Descriptor = new PixelFormatDescriptor();
     if (dc.Disposed || 0 == IGE.Platform.Win32.API.Externals.DescribePixelFormat(dc.Handle, index, PixelFormatDescriptor.StructSize, ref m_Descriptor))
     {
         return;
     }
     m_hDC   = dc.Handle;
     m_Index = index;
 }
Beispiel #7
0
        private void Form1_Load(object sender, EventArgs e)
        {
            Graphics g = this.CreateGraphics();

            hdc = g.GetHdc();

            PixelFormatDescriptor m_pfd = new PixelFormatDescriptor();

            m_pfd.Flags     = (uint)(WGL.PFD_FLAGS.DOUBLEBUFFER | WGL.PFD_FLAGS.DRAW_TO_WINDOW | WGL.PFD_FLAGS.SUPPORT_OPENGL | WGL.PFD_FLAGS.TYPE_RGBA);
            m_pfd.PixelType = 0;
            m_pfd.ColorBits = 24;
            m_pfd.DepthBits = 32;
            m_pfd.LayerType = 0;

            Int32 pf = m_wgl.ChoosePixelFormat(hdc, m_pfd);

            if (pf == 0)
            {
                throw new Exception("ChoosePixelFormat failed");
            }

            Int32 spf = m_wgl.SetPixelFormat(hdc, pf, m_pfd);

            if (spf != 1)
            {
                throw new Exception("SetPixelFormat failed");
            }

            IntPtr ctx = m_wgl.CreateContext(hdc);

            m_wgl.MakeCurrent(hdc, ctx);

            m_gl.MatrixMode(GL.GL_FLAGS.PROJECTION);
            m_gl.Frustum(-0.5F, 0.5F, -0.5F, 0.5F, 1.0F, 3.0F);

            m_gl.MatrixMode(GL.GL_FLAGS.MODELVIEW);
            m_gl.Translatef(0.0F, 0.0F, -2.0F);

            m_gl.Rotatef(30.0F, 1.0F, 0.0F, 0.0F);
            m_gl.Rotatef(30.0F, 0.0F, 1.0F, 0.0F);

            m_gl.Enable(GL.GL_FLAGS.DEPTH_TEST);
            m_gl.Enable(GL.GL_FLAGS.COLOR_MATERIAL);
            m_gl.Enable(GL.GL_FLAGS.LIGHTING);
            m_gl.Enable(GL.GL_FLAGS.LIGHT0);

            m_gl.ColorMaterial(GL.GL_FLAGS.FRONT_AND_BACK, GL.GL_FLAGS.AMBIENT_AND_DIFFUSE);

            this.Invalidate();
        }
Beispiel #8
0
        private static int smethod_0(IntPtr hdc, PixelFormatDescriptor pfd)
        {
            int iPixelFormat = WGL.ChoosePixelFormat(hdc, ref pfd);

            if (iPixelFormat == 0)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            if (WGL.SetPixelFormat(hdc, iPixelFormat, ref pfd) == 0)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            return(iPixelFormat);
        }
Beispiel #9
0
        public static RenderingContext FromWindowHandle(
            IntPtr windowHandle,
            PixelFormatDescriptor pfd)
        {
            IntPtr dc = WGL.GetDC(windowHandle);

            WGL.wglSwapBuffers(dc);
            int    pixelFormatIndex = RenderingContext.smethod_0(dc, pfd);
            IntPtr context          = WGL.wglCreateContext(dc);

            if (context == IntPtr.Zero)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            return(new RenderingContext(windowHandle, dc, false, context, pixelFormatIndex));
        }
Beispiel #10
0
        public static int CreateWindow(string title)
        {
            // Window class
            WindowClassEx windowClass = new WindowClassEx
            {
                Size           = (uint)Marshal.SizeOf <WindowClassEx>(),
                WindowProc     = _wndProc,
                InstanceHandle = GetModuleHandle(null),
                CursorHandle   = LoadCursor(IntPtr.Zero, new IntPtr(IDC_ARROW)),
                ClassName      = ClassName
            };

            RegisterClassEx(ref windowClass);

            // Window
            Rectangle rect = new Rectangle {
                Left = 0, Top = 0, Right = _width, Bottom = _height
            };

            AdjustWindowRect(ref rect, WS_OVERLAPPEDWINDOW, false);
            _hWnd = CreateWindowEx(0, ClassName, title, WS_OVERLAPPEDWINDOW,
                                   CW_USEDEFAULT, CW_USEDEFAULT, rect.Right - rect.Left, rect.Bottom - rect.Top,
                                   IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);

            // GL Context
            PixelFormatDescriptor pfd = new PixelFormatDescriptor
            {
                Size        = (short)Marshal.SizeOf <PixelFormatDescriptor>(),
                Version     = 1,
                Flags       = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
                PixelType   = PFD_TYPE_RGBA,
                ColorBits   = 24,
                StencilBits = 8
            };

            _hDC = GetDC(_hWnd);
            int pixelFormat = ChoosePixelFormat(_hDC, ref pfd);

            SetPixelFormat(_hDC, pixelFormat, ref pfd);

            IntPtr hRC = wglCreateContext(_hDC);

            wglMakeCurrent(_hDC, hRC);

            return(0);
        }
Beispiel #11
0
        private static AccelerationType GetAccelerationType(ref PixelFormatDescriptor pfd)
        {
            AccelerationType type = AccelerationType.ICD;

            if ((pfd.Flags & PixelFormatDescriptorFlags.GENERIC_FORMAT) != 0)
            {
                if ((pfd.Flags & PixelFormatDescriptorFlags.GENERIC_ACCELERATED) != 0)
                {
                    type = AccelerationType.MCD;
                }
                else
                {
                    type = AccelerationType.None;
                }
            }
            return(type);
        }
Beispiel #12
0
        public GLTexture Read()
        {
            int size = _header.ImageWidth * _header.ImageHeight * _header.BytesPerPixel;
            PixelFormatDescriptor format = GetColorFormat();

            if (format != null)
            {
                return(ReadTexture(_input, format));
            }

            using (SafeHGlobalHandle pixels = _input.ReadBuff(size))
            {
                TexPixelFormatsConverter converter = new TexPixelFormatsConverter(_header, pixels, PixelFormats.Bgra32);
                using (SafeHGlobalHandle newPixels = converter.Convert())
                    using (UnmanagedMemoryStream input = newPixels.OpenStream(FileAccess.Read))
                        return(ReadTexture(input, PixelFormat.Format32bppArgb));
            }
        }
Beispiel #13
0
        private static GraphicsMode DescribePixelFormatPFD(IntPtr device, ref PixelFormatDescriptor pfd,
                                                           int pixelformat)
        {
            GraphicsMode created_mode = null;

            if (Functions.DescribePixelFormat(device, pixelformat, pfd.Size, ref pfd) > 0)
            {
                created_mode = new GraphicsMode(
                    new IntPtr(pixelformat),
                    new ColorFormat(pfd.RedBits, pfd.GreenBits, pfd.BlueBits, pfd.AlphaBits),
                    pfd.DepthBits,
                    pfd.StencilBits,
                    0, // MSAA not supported when using PixelFormatDescriptor
                    new ColorFormat(pfd.AccumRedBits, pfd.AccumGreenBits, pfd.AccumBlueBits, pfd.AccumAlphaBits),
                    (pfd.Flags & PixelFormatDescriptorFlags.DOUBLEBUFFER) != 0 ? 2 : 1,
                    (pfd.Flags & PixelFormatDescriptorFlags.STEREO) != 0);
            }
            return(created_mode);
        }
Beispiel #14
0
        public static RenderingContext FromWindowHandle(
            IntPtr windowHandle,
            int pixelFormatIndex)
        {
            IntPtr dc = WGL.GetDC(windowHandle);

            WGL.wglSwapBuffers(dc);
            PixelFormatDescriptor empty = PixelFormatDescriptor.Empty;

            if (WGL.SetPixelFormat(dc, pixelFormatIndex, ref empty) == 0)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            IntPtr context = WGL.wglCreateContext(dc);

            if (context == IntPtr.Zero)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            return(new RenderingContext(windowHandle, dc, false, context, pixelFormatIndex));
        }
Beispiel #15
0
 public WglContext(WglContext sharedWith, GlVersion version, IntPtr context, IntPtr hWnd, IntPtr dc, int pixelFormat,
                   PixelFormatDescriptor formatDescriptor)
 {
     Version           = version;
     _sharedWith       = sharedWith;
     _context          = context;
     _hWnd             = hWnd;
     _dc               = dc;
     _pixelFormat      = pixelFormat;
     _formatDescriptor = formatDescriptor;
     StencilSize       = formatDescriptor.StencilBits;
     using (MakeCurrent())
         GlInterface = new GlInterface(version, proc =>
         {
             var ext = wglGetProcAddress(proc);
             if (ext != IntPtr.Zero)
             {
                 return(ext);
             }
             return(GetProcAddress(WglDisplay.OpenGl32Handle, proc));
         });
 }
Beispiel #16
0
        private void Form1_Load(object sender, EventArgs e)
        {
            Graphics g = this.CreateGraphics();
            hdc = g.GetHdc();

            PixelFormatDescriptor m_pfd = new PixelFormatDescriptor();
            m_pfd.Flags = (uint)(WGL.PFD_FLAGS.DOUBLEBUFFER | WGL.PFD_FLAGS.DRAW_TO_WINDOW | WGL.PFD_FLAGS.SUPPORT_OPENGL | WGL.PFD_FLAGS.TYPE_RGBA);
            m_pfd.PixelType = 0;
            m_pfd.ColorBits = 24;
            m_pfd.DepthBits = 32;
            m_pfd.LayerType = 0;

            Int32 pf = m_wgl.ChoosePixelFormat(hdc, m_pfd);
            if (pf == 0) throw new Exception("ChoosePixelFormat failed");

            Int32 spf = m_wgl.SetPixelFormat(hdc, pf, m_pfd);
            if (spf != 1) throw new Exception("SetPixelFormat failed");

            IntPtr ctx = m_wgl.CreateContext(hdc);
            m_wgl.MakeCurrent(hdc, ctx);

            m_gl.MatrixMode(GL.GL_FLAGS.PROJECTION);
            m_gl.Frustum(-0.5F, 0.5F, -0.5F, 0.5F, 1.0F, 3.0F);

            m_gl.MatrixMode(GL.GL_FLAGS.MODELVIEW);
            m_gl.Translatef(0.0F, 0.0F, -2.0F);

            m_gl.Rotatef(30.0F, 1.0F, 0.0F, 0.0F);
            m_gl.Rotatef(30.0F, 0.0F, 1.0F, 0.0F);

            m_gl.Enable(GL.GL_FLAGS.DEPTH_TEST);
            m_gl.Enable(GL.GL_FLAGS.COLOR_MATERIAL);
            m_gl.Enable(GL.GL_FLAGS.LIGHTING);
            m_gl.Enable(GL.GL_FLAGS.LIGHT0);

            m_gl.ColorMaterial(GL.GL_FLAGS.FRONT_AND_BACK, GL.GL_FLAGS.AMBIENT_AND_DIFFUSE);

            this.Invalidate();
        }
Beispiel #17
0
 internal static extern bool SetPixelFormat(IntPtr deviceContext, uint pixelFormat, [In] ref PixelFormatDescriptor ppfd);
Beispiel #18
0
 public static extern int DescribePixelFormat(IntPtr hdc, int ipfd, uint cjpfd, ref PixelFormatDescriptor ppfd);
Beispiel #19
0
 internal static extern bool SetPixelFormat(IntPtr deviceContextHandle, int pixelFormatIndex, ref PixelFormatDescriptor pixelFormatDescriptor);
Beispiel #20
0
 internal static extern int ChoosePixelFormat(IntPtr deviceContextHandle, ref PixelFormatDescriptor pixelFormatDescriptor);
Beispiel #21
0
 public extern static unsafe int wglChoosePixelFormat(IntPtr hdc, ref PixelFormatDescriptor ppfd);
Beispiel #22
0
 public static extern int SetPixelFormat(IntPtr hdc, int iPixelFormat, ref PixelFormatDescriptor ppfd);
Beispiel #23
0
 private static extern bool SetPixelFormat(IntPtr hdc, int format, ref PixelFormatDescriptor ppfd);
Beispiel #24
0
        private void Init()
        {
            var pfd = new PixelFormatDescriptor();
            pfd.Initialize();

            this.InitializePixelFormatDescriptor( ref pfd );

            this.hDC = WindowsOpenGLNative.GetDC( this.Handle );
            if (this.hDC == IntPtr.Zero)
                throw new Win32Exception( Marshal.GetLastWin32Error() );

            var iPixelformat = WindowsOpenGLNative.ChoosePixelFormat( this.hDC, ref pfd );
            if (iPixelformat == 0)
                throw new Win32Exception( Marshal.GetLastWin32Error() );

            // Set the pixel format
            if (!WindowsOpenGLNative.SetPixelFormat( this.hDC, iPixelformat, ref pfd ))
                throw new Win32Exception( Marshal.GetLastWin32Error() );

            // Create a new OpenGL rendering context
            this.hRC = WindowsOpenGLNative.wglCreateContext( this.hDC );
            if (this.hRC == IntPtr.Zero)
                throw new Win32Exception( Marshal.GetLastWin32Error() );
        }
Beispiel #25
0
 internal static extern uint ChoosePixelFormat(IntPtr deviceContext, [In] ref PixelFormatDescriptor ppfd);
Beispiel #26
0
 protected virtual void InitializePixelFormatDescriptor( ref PixelFormatDescriptor pfd )
 {
 }
Beispiel #27
0
 // Something for the contexts
 private bool setPixelFormat(IntPtr pmdevice, int pixelFormat, ref PixelFormatDescriptor pfd)
 {
     LoadLibrary("opengl32.dll");
     return _SetPixelFormat(pmdevice, pixelFormat, ref pfd);
 }
Beispiel #28
0
 private static extern int ChoosePixelFormat(IntPtr hdc, [In] ref PixelFormatDescriptor ppfd);
Beispiel #29
0
 public static extern int ChoosePixelFormat(IntPtr deviceContext, ref PixelFormatDescriptor pixelFormatDescriptor);
Beispiel #30
0
 public static extern bool SetPixelFormat(IntPtr dc, int format, ref PixelFormatDescriptor pfd);
Beispiel #31
0
 public static extern bool SetPixelFormat(IntPtr deviceContext, int pixelFormat, ref PixelFormatDescriptor pixelFormatDescriptor);
Beispiel #32
0
 public static extern int ChoosePixelFormat(IntPtr hdc, ref PixelFormatDescriptor ppfd);
Beispiel #33
0
 private static extern bool _SetPixelFormat(IntPtr pmdevice, int pixelFormat, ref PixelFormatDescriptor pfd);
Beispiel #34
0
 internal static extern int ChoosePixelFormat(IntPtr deviceContextHandle, ref PixelFormatDescriptor pixelFormatDescriptor);
Beispiel #35
0
        public OpenGLWindow(INativeWindow parent, int x, int y, int width, int height) : base(new WindowCreateStruct {
            WindowTitle  = GameConfig.GameWindowTitle,                    //"IGE OpenGLWindow",
            X            = x,
            Y            = y,
            Width        = width,
            Height       = height,
            Style        = GameConfig.FullScreen ? WindowStyleFlags.Popup : Win32NativeWindow.DefaultStyle,
            ExStyle      = ExtendedWindowStyleFlags.ApplicationWindow,
            ParentWindow = (Win32NativeWindow)parent,
            Menu         = IntPtr.Zero,
            Param        = IntPtr.Zero,

            ClassName   = "IGEOpenGLWindow",
            ClassStyle  = WindowClassStyle.HREDRAW | WindowClassStyle.VREDRAW | WindowClassStyle.OWNDC,
            Background  = (IntPtr)0,                                                                                                                                                                                                                      // no background brush is needed since opengl has its own renderer
            Icon        = (GameConfig.IconResourceId != 0) ? IGE.Platform.Win32.API.Externals.LoadIcon(Win32Application.GetInstanceHandle(), (IntPtr)GameConfig.IconResourceId) : IGE.Platform.Win32.API.Externals.LoadIcon(IntPtr.Zero, (IntPtr) 32512), // 32512 = IDI_APPLICATION
            Cursor      = IGE.Platform.Win32.API.Externals.LoadCursor(IntPtr.Zero, (IntPtr) 32512),                                                                                                                                                       // 32512 = IDC_ARROW
            ClassMenu   = IntPtr.Zero,
            ClassExtra  = 0,
            WindowExtra = 0
        })
        {
            m_DeviceContext = null;
            if (!Exists)
            {
                return;
            }

            m_DeviceContext = new DeviceContext(this);
            if (m_DeviceContext.Disposed)
            {
                GameDebugger.EngineLog(LogLevel.Error, "Failed to properly create a device context");
                throw new UserFriendlyException("Failed to properly create a device context", "Graphics initialization error");
            }

            /*
             * // This enumerates all pixel formats, supported by the device context to the log file
             * for( int i = PixelFormat.GetCount(m_DeviceContext); i > 0; i-- ) {
             *      PixelFormat dpf = new PixelFormat(m_DeviceContext, i);
             *      GameDebugger.Log(dpf);
             * }
             */

            // change pixelformat for the window's device context
            //  | PixelFormatDescriptorFlags.SWAP_EXCHANGE
            PixelFormatDescriptor pfd = new PixelFormatDescriptor {
                Flags       = PixelFormatDescriptorFlags.DOUBLEBUFFER | PixelFormatDescriptorFlags.SUPPORT_OPENGL | PixelFormatDescriptorFlags.DRAW_TO_WINDOW,
                PixelType   = ApiPixelType.RGBA,
                ColorBits   = (byte)GameConfig.ColorBits,
                RedBits     = 8, GreenBits = 8, BlueBits = 8, AlphaBits = 8,
                RedShift    = 0, GreenShift = 0, BlueShift = 0, AlphaShift = 0,
                DepthBits   = (byte)GameConfig.DepthBufferBits,
                StencilBits = (byte)GameConfig.StencilBufferBits,
                AccumBits   = (byte)GameConfig.AccumBufferBits, AccumRedBits = 0, AccumGreenBits = 0, AccumBlueBits = 0, AccumAlphaBits = 0,
                AuxBuffers  = 0, LayerType = 0, LayerMask = 0, VisibleMask = 0, DamageMask = 0
            };

            PixelFormat pf = new PixelFormat(m_DeviceContext, ref pfd);

            GameDebugger.EngineLog(LogLevel.Debug, "{0}", pf);

            if (!pf.Exists)
            {
                throw new Exception("Could not find a suitable pixel format for an OpenGL window.");
            }

            bool res = pf.Apply();

            //GameDebugger.Log("Chosen: {0} {1}", pf.Exists, pf.ToString());
            //GameDebugger.Log("Apply result: {0}", res);
            if (!res)
            {
                GameDebugger.EngineLog(LogLevel.Debug, "Failed applying requested pixel format, trying to apply by a found index");

                PixelFormat pf2 = new PixelFormat(m_DeviceContext, pf.Index);

                GameDebugger.EngineLog(LogLevel.Debug, "{0}", pf2);

                res = pf2.Apply();
                //GameDebugger.Log("Real: {0} {1}", pf2.Exists, pf2.ToString());
                //GameDebugger.Log("Apply result: {0}", res);
                if (!res)
                {
                    throw new Exception(String.Format("Error trying to set {0}", pf2.ToString()));
                }
            }

            m_ResourceContext = new ResourceContext(m_DeviceContext);
            if (m_ResourceContext.Disposed)
            {
                int pixelFormats = PixelFormat.GetCount(m_DeviceContext);
                GameDebugger.EngineLog(LogLevel.Debug, "Supported pixel formats:");
                for (int i = 0; i < pixelFormats; i++)
                {
                    pf = new PixelFormat(m_DeviceContext, i);
                    GameDebugger.EngineLog(LogLevel.Debug, "{0}", pf);
                }
                throw new Exception("Could not create a resource context for the OpenGLWindow");
            }
            m_ResourceContext.Activate();

            // "reload" because we want context specific extension functions to be loaded as well
            WGL.RuntimeImport();
            GL.RuntimeImport();

            Application.IdleEvent += OnIdle;
        }
Beispiel #36
0
        public async override Task <GLTexture> ReadTextureAsync(CancellationToken cancelationToken)
        {
            if (cancelationToken.IsCancellationRequested)
            {
                return(RaiseTextureReaded(null));
            }

            using (SafeHGlobalHandle pixels = new SafeHGlobalHandle(_map.Width * _map.Height * 3))
            {
                using (Stream stream = pixels.OpenStream(FileAccess.ReadWrite))
                {
                    if (cancelationToken.IsCancellationRequested)
                    {
                        return(RaiseTextureReaded(null));
                    }

                    CreateBackground(stream);

                    foreach (MimTile tile in _map.LayredTiles[0])
                    {
                        if (cancelationToken.IsCancellationRequested)
                        {
                            return(RaiseTextureReaded(null));
                        }

                        //if (tile.Layered.Z < _map.LayredTiles[0][0].Layered.Z)
                        //    break;

                        int position = tile.Layered.GetPositionInImage(_map, _map.Width * 3);
                        stream.Seek(position, SeekOrigin.Begin);

                        Color[] colors = ReadTileColors(tile);
                        for (int i = 0; i < 16; i++)
                        {
                            for (int k = 0; k < 16; k++)
                            {
                                WriteColor(colors[i * 16 + k], tile.Layered.BlendType, stream);
                            }

                            if (i < 15)
                            {
                                stream.Seek((_map.Width - 16) * 3, SeekOrigin.Current);
                            }
                        }
                    }
                }

                if (cancelationToken.IsCancellationRequested)
                {
                    return(RaiseTextureReaded(null));
                }

                PixelFormatDescriptor pixelFormat = System.Drawing.Imaging.PixelFormat.Format24bppRgb;

                int textureId;
                using (GLService.AcquireContext())
                {
                    GL.GenTextures(1, out textureId);
                    GL.BindTexture(TextureTarget.Texture2D, textureId);
                    GL.TexImage2D(TextureTarget.Texture2D, 0, pixelFormat, _map.Width, _map.Height, 0, pixelFormat, pixelFormat, pixels.DangerousGetHandle());

                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
                }

                if (cancelationToken.IsCancellationRequested)
                {
                    return(RaiseTextureReaded(null));
                }

                return(new GLTexture(textureId, _map.Width, _map.Height, pixelFormat));
            }
        }
Beispiel #37
0
 public static extern int ChoosePixelFormat(IntPtr hDc, ref PixelFormatDescriptor pfd);
Beispiel #38
0
 internal static extern bool SetPixelFormat(IntPtr deviceContextHandle, int pixelFormatIndex, ref PixelFormatDescriptor pixelFormatDescriptor);
Beispiel #39
0
 public static extern int DescribePixelFormat(IntPtr hdc, int ipfd, uint cjpfd, ref PixelFormatDescriptor pfd);
Beispiel #40
0
        // Initializes the contexts
        public void initContexts()
        {
            bContextsInitiated=	true;
            windowHandle=	Handle;
            if(windowHandle== IntPtr.Zero)
            {
                MessageBox.Show("Window creation error. No window handle.", "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                Environment.Exit(-1);
            }

            // Variables
            PixelFormatDescriptor	pfd=	new PixelFormatDescriptor();
            int	pixelFormat;

            pfd.nSize=	(short)Marshal.SizeOf(pfd);
            pfd.nVersion=	1;
            pfd.dwFlags=	0x25;
            pfd.iPixelType=	0;
            pfd.cColorBits=	colorBits;
            pfd.cRedBits=	0;
            pfd.cRedShift=	0;
            pfd.cGreenBits=	0;
            pfd.cGreenShift=	0;
            pfd.cBlueBits=	0;
            pfd.cBlueShift=	0;
            pfd.cAlphaBits=	0;
            pfd.cAlphaShift=	0;
            pfd.cAccumBits=	accumBits;
            pfd.cAccumRedBits=	0;
            pfd.cAccumGreenBits=	0;
            pfd.cAccumBlueBits=	0;
            pfd.cAccumAlphaBits=	0;
            pfd.cDepthBits=	depthBits;
            pfd.cStencilBits=	stencilBits;
            pfd.cAuxBuffers=	0;
            pfd.iLayerType=	0;
            pfd.bReserved=	0;
            pfd.dwLayerMask=	0;
            pfd.dwVisibleMask=	0;
            pfd.dwDamageMask=	0;

            device=	GetDC(windowHandle);
            if(device== IntPtr.Zero)
            {
                MessageBox.Show("Can not create a GL device context", "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                Environment.Exit(-1);
            }

            pixelFormat=	ChoosePixelFormat(device, ref pfd);
            if(pixelFormat== 0)
            {
                MessageBox.Show("Can not find a suitable PixelFormat", "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                Environment.Exit(-1);
            }
            if(!setPixelFormat(device, pixelFormat, ref pfd))
            {
                MessageBox.Show("Can not set the chosen PixelFormat. Chosen PixelFormat was"+pixelFormat, "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                Environment.Exit(-1);
            }

            logScaleX=	GetDeviceCaps(device, 0x58);
            logScaleY=	GetDeviceCaps(device, 90);
            renderingContext=	wglCreateContext(device);
            if(renderingContext== IntPtr.Zero)
            {
                MessageBox.Show("Can not create a GL rendering context", "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                Environment.Exit(-1);
            }

            makeCurrent();
            SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1);
        }
Beispiel #41
0
 private static extern int ChoosePixelFormat(IntPtr pmdevice, ref PixelFormatDescriptor pfd);
Beispiel #42
0
        static bool InitializeCore()
        {
            var wndClassEx = new WNDCLASSEX
            {
                cbSize        = Marshal.SizeOf <WNDCLASSEX>(),
                hInstance     = GetModuleHandle(null),
                lpfnWndProc   = _wndProcDelegate,
                lpszClassName = "AvaloniaGlWindow-" + Guid.NewGuid(),
                style         = (int)ClassStyles.CS_OWNDC
            };

            _windowClass     = RegisterClassEx(ref wndClassEx);
            _bootstrapWindow = CreateOffscreenWindow();
            _bootstrapDc     = GetDC(_bootstrapWindow);
            _defaultPfd      = new PixelFormatDescriptor
            {
                Size    = (ushort)Marshal.SizeOf <PixelFormatDescriptor>(),
                Version = 1,
                Flags   = PixelFormatDescriptorFlags.PFD_DRAW_TO_WINDOW |
                          PixelFormatDescriptorFlags.PFD_SUPPORT_OPENGL | PixelFormatDescriptorFlags.PFD_DOUBLEBUFFER,
                DepthBits   = 24,
                StencilBits = 8,
                ColorBits   = 32
            };
            _defaultPixelFormat = ChoosePixelFormat(_bootstrapDc, ref _defaultPfd);
            SetPixelFormat(_bootstrapDc, _defaultPixelFormat, ref _defaultPfd);

            _bootstrapContext = wglCreateContext(_bootstrapDc);
            if (_bootstrapContext == IntPtr.Zero)
            {
                return(false);
            }

            wglMakeCurrent(_bootstrapDc, _bootstrapContext);
            WglCreateContextAttribsArb = Marshal.GetDelegateForFunctionPointer <WglCreateContextAttribsARBDelegate>(
                wglGetProcAddress("wglCreateContextAttribsARB"));

            WglChoosePixelFormatArb =
                Marshal.GetDelegateForFunctionPointer <WglChoosePixelFormatARBDelegate>(
                    wglGetProcAddress("wglChoosePixelFormatARB"));

            GlDebugMessageCallback =
                Marshal.GetDelegateForFunctionPointer <GlDebugMessageCallbackDelegate>(
                    wglGetProcAddress("glDebugMessageCallback"));


            var formats = new int[1];

            WglChoosePixelFormatArb(_bootstrapDc, new int[]
            {
                WGL_DRAW_TO_WINDOW_ARB, 1,
                WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
                WGL_SUPPORT_OPENGL_ARB, 1,
                WGL_DOUBLE_BUFFER_ARB, 1,
                WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
                WGL_COLOR_BITS_ARB, 32,
                WGL_ALPHA_BITS_ARB, 8,
                WGL_DEPTH_BITS_ARB, 0,
                WGL_STENCIL_BITS_ARB, 0,
                0, // End
            }, null, 1, formats, out int numFormats);
            if (numFormats != 0)
            {
                DescribePixelFormat(_bootstrapDc, formats[0], Marshal.SizeOf <PixelFormatDescriptor>(), ref _defaultPfd);
                _defaultPixelFormat = formats[0];
            }


            wglMakeCurrent(IntPtr.Zero, IntPtr.Zero);
            return(true);
        }
Beispiel #43
0
 public static extern bool SetPixelFormat(IntPtr hdc, int iPixelFormat, PixelFormatDescriptor* ppfd);