public void Attach(RenderingSurface xiSurface) { if (xiSurface.IsInDesignMode) { return; } Detach(); mSurface = xiSurface; try { mRenderingContext = Wgl.wglCreateContext(mSurface.DeviceContext); if (mRenderingContext == IntPtr.Zero) { throw new Exception("Could not create rendering context"); } lock (mRenderingContexts) { if (mRenderingContexts.Count != 0) { Wgl.wglShareLists(mRenderingContexts[0], mRenderingContext); } mRenderingContexts.Add(mRenderingContext); } } catch { Detach(); throw; } mSurface.Resize += Surface_Resize; mSurface.ReleaseDeviceContext += Surface_ReleaseDeviceContext; mSurface.Paint += Surface_Paint; SetViewPort(mSurface.Width, mSurface.Height); Init(); }
static GLExtensions() { var extstr = Gl.glGetString(Gl.GL_EXTENSIONS).ToLower(); GLExtensions.GLMultiTexture = extstr.Contains("gl_arb_multitexture"); GLExtensions.GLFragProg = extstr.Contains("gl_arb_fragment_program"); GLExtensions.GLAnisotropic = extstr.Contains("gl_ext_texture_filter_anisotropic"); GLExtensions.GLSL = extstr.Contains("gl_arb_fragment_shader"); GLExtensions.GLMultiSample = extstr.Contains("gl_arb_multisample"); if (GLExtensions.GLAnisotropic) { Gl.glGetFloatv(Gl.GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, out var anisotropicSamples); GLExtensions.AnisotropicSamples = anisotropicSamples; } GLExtensions.WGLMultiSample = Wgl.wglGetProcAddress("WGL_ARB_Multisample") != null; }
void killGLWindow() { if (RC != IntPtr.Zero) { // Do We Have A Rendering Context? if (!Wgl.wglMakeCurrent(IntPtr.Zero, IntPtr.Zero)) { // Are We Able To Release The DC and RC Contexts? MessageBox.Show("Release Of DC And RC Failed.", "SHUTDOWN ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } if (!Wgl.wglDeleteContext(RC)) { // Are We Able To Delete The RC? MessageBox.Show("Release Rendering Context Failed.", "SHUTDOWN ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } RC = IntPtr.Zero; // Set RC To Null } if (DC != IntPtr.Zero) { // Do We Have A Device Context? if (form != null && !form.IsDisposed) { // Do We Have A Window? if (form.Handle != IntPtr.Zero) { // Do We Have A Window Handle? if (!User.ReleaseDC(form.Handle, DC)) { // Are We Able To Release The DC? MessageBox.Show("Release Device Context Failed.", "SHUTDOWN ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } DC = IntPtr.Zero; // Set DC To Null } if (form != null) { // Do We Have A Windows Form? form.Hide(); // Hide The Window form.Close(); // Close The Form form = null; // Set form To Null } }
/// <summary> /// Kreiranje fonta kao displej lisete koristeci wgl metode. /// </summary> private bool CreateFont() { // Generisi mesta za 256 karaktera m_ID = Gl.glGenLists(256); // Selektuj kreirani font kao aktivni Gdi.SelectObject(Wgl.wglGetCurrentDC(), m_font.ToHfont()); // Kreiraj na osnovu izabranog fonta bitmape za svaki karakter bool success = Wgl.wglUseFontBitmapsW(Wgl.wglGetCurrentDC(), // aktivni DC 0, // pocetni karakter 255, // broj DL koji se kreiraju m_ID); // DL identifikator // Deselektuj aktivni font Gdi.SelectObject(Wgl.wglGetCurrentDC(), IntPtr.Zero); return(success); }
static void init_graphics() { //Gl.glEnable(Gl.GL_LIGHTING); //Gl.glEnable(Gl.GL_LIGHT0); //float[] light_pos = new float[3] { 1, 0.5F, 1 }; //Gl.glLightfv(Gl.GL_LIGHT0, Gl.GL_POSITION, light_pos); Gl.glEnable(Gl.GL_COLOR_MATERIAL); Gl.glEnable(Gl.GL_DEPTH_TEST); //Gl.glEnable(Gl.GL_STENCIL_TEST); Gl.glEnable(Gl.GL_BLEND); RendererWrapper.SetBlendMode(RendererWrapper.BlendModes.Normal); Gl.glClearColor(0.1f, 0.1f, 0.1f, 0.0f); Gl.glClearDepth(1.0); Wgl.wglSwapIntervalEXT(-1); Globals.thserial.Start(); Globals.thapp.Start(); Debug.Print(Wgl.wglGetSwapIntervalEXT().ToString()); }
protected bool RegisterDxDevice() { // Device already registered? if (_glDeviceHandle != IntPtr.Zero) { return(true); } // No device or DXInterop not supported, fallback to base // implementation of rendering to a GL texture. if (_dxDevice == null || !Wgl.CurrentExtensions.DXInterop_NV) { _glDeviceHandle = IntPtr.Zero; return(false); } // Register the dx device _glDeviceHandle = Wgl.DXOpenDeviceNV(_dxDevice.NativePointer); return(_glDeviceHandle != IntPtr.Zero); }
private void DestroyGL() { if (_defaultProgram != null) { _defaultProgram.Dispose(); } _defaultProgram = null; Wgl.wglMakeCurrent(IntPtr.Zero, IntPtr.Zero); if (_hRC != IntPtr.Zero) { Wgl.wglDeleteContext(_hRC); } _hRC = IntPtr.Zero; if ((_controlHandle != IntPtr.Zero) && (_hDC != IntPtr.Zero)) { User.ReleaseDC(_controlHandle, _hDC); } _hDC = IntPtr.Zero; }
public override GLContext Clone() { // Create new context based on own HDC IntPtr newCtx = Wgl.wglCreateContext(_hDeviceContext); if (newCtx == IntPtr.Zero) { throw new Exception("Error calling wglCreateContext"); } Wgl.wglMakeCurrent(IntPtr.Zero, IntPtr.Zero); // Share lists with old context if (!Wgl.wglShareLists(_hRenderingContext, newCtx)) { Wgl.wglDeleteContext(newCtx); throw new Exception("wglShareLists() failed: "); } return(new Win32Context(_hDeviceContext, newCtx)); }
/// <summary> /// Handles the Paint event. /// </summary> /// <param name="e">Standard PaintEventArgs</param> protected override void OnPaint(PaintEventArgs e) { if (fresh) { if (this.deviceContext == IntPtr.Zero || this.renderContext == IntPtr.Zero) { MessageBox.Show("No device or rendering context available!"); return; } base.OnPaint(e); //Only switch contexts if this is already not the current context if (this.renderContext != Wgl.wglGetCurrentContext()) { this.MakeCurrentContext(); } this.RenderScene(); this.SwapBuffers(); } }
public override void Dispose() { base.Dispose(); if (hRC != IntPtr.Zero) // Do We Not Have A Rendering Context? { if (!Wgl.wglMakeCurrent(IntPtr.Zero, IntPtr.Zero)) // Are We Able To Release The DC And RC Contexts? { MessageBox.Show("Release Of DC And RC Failed.", "SHUTDOWN ERROR", MessageBoxButtons.OK, MessageBoxIcon.Information); } if (!Wgl.wglDeleteContext(hRC)) // Are We Not Able To Delete The RC? { MessageBox.Show("Release Rendering Context Failed.", "SHUTDOWN ERROR", MessageBoxButtons.OK, MessageBoxIcon.Information); } hRC = IntPtr.Zero; // Set RC To NULL } // if(hDC != IntPtr.Zero && !User.ReleaseDC(control.Handle, hDC)) { // Are We Not Able To Release The DC // MessageBox.Show("Release Device Context Failed.", "SHUTDOWN ERROR", MessageBoxButtons.OK, MessageBoxIcon.Information); // hDC = IntPtr.Zero; // Set DC To NULL // } // // if the control is a form, then close it // if(control is System.Windows.Forms.Form) { // form = control as System.Windows.Forms.Form; // form.Close(); // } // else { // if(control.Parent != null) { // form = (Form)control.Parent; // form.Close(); // } // } //form.Dispose(); // make sure this window is no longer active this.isActive = false; }
protected override void OnPaint(PaintEventArgs e) { if (DesignMode) { base.OnPaint(e); } else { if (flgroup != null) { if (Wgl.wglMakeCurrent(hdc, hglrc)) { flgroup.AnimateOneFrame(); CopyFrontBufferToBack(); if (Types.iSettingBufferMode == Types.BUFFER.BUFFER_MODE_SINGLE) { Gdi.SwapBuffers(hdc); } } } } }
protected ScopedLock LockContext() { ScopedLock lLock = ScopedLock.Lock(mRenderingContext); try { if (Wgl.wglGetCurrentContext() != mRenderingContext) { if (!Wgl.wglMakeCurrent(mSurface.DeviceContext, mRenderingContext)) { throw new Exception("Could not set the rendering context"); } } } catch { lLock.Dispose(); throw; } return(lLock); }
public void Render(DrawingContext drawingContext) { if (_framebuffer == null) { return; } var curFrameStamp = _stopwatch.Elapsed; var deltaT = curFrameStamp - _lastFrameStamp; _lastFrameStamp = curFrameStamp; // Set up framebuffer GL.BindFramebuffer(FramebufferTarget.Framebuffer, _framebuffer.GLFramebufferHandle); GL.Viewport(0, 0, _framebuffer.FramebufferWidth, _framebuffer.FramebufferHeight); GLRender?.Invoke(deltaT); GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0); GL.Flush(); GLAsyncRender?.Invoke(); // Copy dirty area to front buffer _framebuffer.D3dImage.Lock(); _framebuffer.D3dImage.SetBackBuffer(D3DResourceType.IDirect3DSurface9, _framebuffer.DxRenderTargetHandle); _framebuffer.D3dImage.AddDirtyRect(new Int32Rect(0, 0, _framebuffer.FramebufferWidth, _framebuffer.FramebufferHeight)); _framebuffer.D3dImage.Unlock(); // Transforms are applied in reverse order drawingContext.PushTransform(_framebuffer.TranslateTransform); // Apply translation to the image on the Y axis by the height. This assures that in the next step, where we apply a negative scale the image is still inside of the window drawingContext.PushTransform(_framebuffer.FlipYTransform); // Apply a scale where the Y axis is -1. This will rotate the image by 180 deg // dpi scaled rectangle from the image var rect = new Rect(0, 0, _framebuffer.D3dImage.Width, _framebuffer.D3dImage.Height); Wgl.DXUnlockObjectsNV(_context.GlDeviceHandle, 1, new[] { _framebuffer.DxInteropRegisteredHandle }); drawingContext.DrawImage(_framebuffer.D3dImage, rect); // Draw the image source Wgl.DXLockObjectsNV(_context.GlDeviceHandle, 1, new[] { _framebuffer.DxInteropRegisteredHandle }); // Enable GL access to the framebuffer drawingContext.Pop(); // Remove the scale transform drawingContext.Pop(); // Remove the translation transform }
/// <summary> /// Kreiranje fonta kao displej lisete koristeci wgl metode. /// </summary> private bool CreateFont() { // Generisi DL za 256 karaktera m_ID = Gl.glGenLists(256); // Selektuj kreirani font kao aktivni Gdi.SelectObject(Wgl.wglGetCurrentDC(), m_font.ToHfont()); bool success = Wgl.wglUseFontOutlinesW(Wgl.wglGetCurrentDC(), // selektuje aktivni DC 0, // pocetni karakter 255, // broj DL koji se kreiraju m_ID, // identifikator DLa 0.0f, // koliko se razlikuju od originalnog fonta m_depth, // debljina fonta (po Z osi) Wgl.WGL_FONT_POLYGONS, // koristi poligone, a ne linije m_gmf); // bafer u koji se smestaju podaci // Deselektuj aktivni font Gdi.SelectObject(Wgl.wglGetCurrentDC(), IntPtr.Zero); return(success); }
void AttachGLToWindow(/*FlurryAnimateChildInfo *child*/) { Gdi.PIXELFORMATDESCRIPTOR pfd = new Gdi.PIXELFORMATDESCRIPTOR(); //HACK pfd.nSize = (short)System.Runtime.InteropServices.Marshal.SizeOf(pfd); pfd.nVersion = 1; pfd.dwFlags = Gdi.PFD_DRAW_TO_WINDOW | Gdi.PFD_SUPPORT_OPENGL; pfd.iPixelType = Gdi.PFD_TYPE_RGBA; pfd.iLayerType = Gdi.PFD_MAIN_PLANE; pfd.cDepthBits = 16; pfd.cColorBits = 24; #if !USEFADEHACK if (Types.iSettingBufferMode != Types.BUFFER.BUFFER_MODE_SINGLE) { pfd.dwFlags |= Gdi.PFD_DOUBLEBUFFER; } #endif hdc = User.GetDC(this.Handle); //Win32.GDI.SetBkColor(hdc, 0); int iPixelFormat = Gdi.ChoosePixelFormat(hdc, ref pfd); Gdi.SetPixelFormat(hdc, iPixelFormat, ref pfd); // then use this to create a rendering context hglrc = Wgl.wglCreateContext(hdc); Wgl.wglMakeCurrent(hdc, hglrc); // tell Flurry to use the whole window as viewport //GetClientRect(child->hWnd, &rc); flgroup.SetSize(this.Width, this.Height); // some nice debug output //_RPT4(_CRT_WARN, " child 0x%08x: hWnd 0x%08x, hdc 0x%08x, hglrc 0x%08x\n", // child, child->hWnd, child->hdc, child->hglrc); //_RPT1(_CRT_WARN, " GL vendor: %s\n", glGetString(GL_VENDOR)); //_RPT1(_CRT_WARN, " GL renderer: %s\n", glGetString(GL_RENDERER)); //_RPT1(_CRT_WARN, " GL version: %s\n", glGetString(GL_VERSION)); //_RPT1(_CRT_WARN, " GL extensions: %s\n", glGetString(GL_EXTENSIONS)); //_RPT0(_CRT_WARN, "\n"); }
private void KillGLWindow() { if (this.Fullscreen) { User.ChangeDisplaySettings(IntPtr.Zero, 0); // switch Back To The Desktop //Cursor.Show(); } if (this._hRC != IntPtr.Zero) // Do We Have A Rendering Context? { if (!Wgl.wglMakeCurrent(IntPtr.Zero, IntPtr.Zero)) { // Are We Able To Release The DC and RC Contexts? throw new Exception("Release Of DC And RC Failed."); } if (!Wgl.wglDeleteContext(this._hRC)) // Are We Able To Delete The RC? { throw new Exception("Release Rendering Context Failed."); } this._hRC = IntPtr.Zero; // Set RC To Null } if (this._hDC != IntPtr.Zero) // Do We Have A Device Context? { if (this.RenderControl != null && !this.RenderControl.IsDisposed) // Do We Have A Window? { if (this.RenderControl.Handle != IntPtr.Zero) // Do We Have A Window Handle? { if (!User.ReleaseDC(this.RenderControl.Handle, this._hDC)) // Are We Able To Release The DC? { throw new Exception("Release Device Context Failed."); } } } this._hDC = IntPtr.Zero; // Set DC To Null } }
public void TestGetExtensionsStringARB() { if (Wgl.HasGetExtensionsStringARB == false) { Assert.Inconclusive("WGL_ARB_extensions_string not supported"); } using (Device device = new Device()) using (new GLContext(device)) { DeviceContextWGL winDeviceContext = (DeviceContextWGL)device.Context; string extensions = Wgl.GetExtensionsStringARB(winDeviceContext.DeviceContext); Assert.IsNotNull(extensions); // No exposed extensions? No more assertion if (extensions == String.Empty) { return; } string[] extensionIds = Regex.Split(extensions, " "); // Filter empty IDs extensionIds = Array.FindAll(extensionIds, delegate(string item) { return(item.Trim().Length > 0); }); Console.WriteLine("Found {0} WGL extensions:", extensionIds.Length); foreach (string extensionId in extensionIds) { Console.WriteLine("- {0}", extensionId); } // Assert.IsTrue(Regex.IsMatch(extensions, @"(WGL_(\w+)( +)?)+")); } }
///// <summary> ///// Properly kill the window. ///// </summary> protected void KillGLWindow() { if (hRC != IntPtr.Zero) { // Do We Have A Rendering Context? if (!Wgl.wglMakeCurrent(IntPtr.Zero, IntPtr.Zero)) { // Are We Able To Release The DC and RC Contexts? MessageBox.Show("Release Of DC And RC Failed.", "SHUTDOWN ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } if (!Wgl.wglDeleteContext(hRC)) { // Are We Able To Delete The RC? MessageBox.Show("Release Rendering Context Failed.", "SHUTDOWN ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } hRC = IntPtr.Zero; // Set RC To Null } if (hDC != IntPtr.Zero) { // Do We Have A Device Context? if (parent != null && !parent.IsDisposed) { // Do We Have A Window? if (parent.Handle != IntPtr.Zero) { // Do We Have A Window Handle? if (!User.ReleaseDC(parent.Handle, hDC)) { // Are We Able To Release The DC? MessageBox.Show("Release Device Context Failed.", "SHUTDOWN ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } hDC = IntPtr.Zero; // Set DC To Null } }
protected override void Create() { int pixelFormat = Gdi.ChoosePixelFormat(this.hdc, ref this.present.pfd); if (pixelFormat == 0) { this.Dispose(); throw new Exception("Can't Find A Suitable PixelFormat."); } if (!Gdi.SetPixelFormat(this.hdc, pixelFormat, ref this.present.pfd)) { this.Dispose(); throw new Exception("Can't Set The PixelFormat."); } this.hrc = Wgl.wglCreateContext(this.hdc); if (this.hrc == IntPtr.Zero) { this.Dispose(); throw new Exception("Can't Create A GL Rendering Context."); } if (!Wgl.wglMakeCurrent(this.hdc, this.hrc)) { this.Dispose(); throw new Exception("Can't Activate The GL Rendering Context."); } this.state = new State(); }
protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); using (var wglRes = new WglHandleResolver()) { wgl = new Wgl(wglRes); } deviceContext = GetDC(this.Handle); InitPixelFormat(deviceContext); using (var glRes = new GlHandleResolver()) { gl = new Gl(glRes); } var str = gl.GetString(StringName.Version); var s = Marshal.PtrToStringAnsi(str.Pointer); }
internal GLContext(IntPtr handle) { _handle = handle; var descriptor = new Gdi.PIXELFORMATDESCRIPTOR(); descriptor.nSize = (short)Marshal.SizeOf(descriptor); descriptor.nVersion = 1; descriptor.dwFlags = Gdi.PFD_DRAW_TO_WINDOW | Gdi.PFD_SUPPORT_OPENGL | Gdi.PFD_DOUBLEBUFFER | Gdi.PFD_SWAP_EXCHANGE; descriptor.iPixelType = Gdi.PFD_TYPE_RGBA; descriptor.cColorBits = 32; descriptor.cRedBits = 0; descriptor.cRedShift = 0; descriptor.cGreenBits = 0; descriptor.cGreenShift = 0; descriptor.cBlueBits = 0; descriptor.cBlueShift = 0; descriptor.cAlphaBits = 0; descriptor.cAlphaShift = 0; descriptor.cAccumBits = 0; descriptor.cAccumRedBits = 0; descriptor.cAccumGreenBits = 0; descriptor.cAccumBlueBits = 0; descriptor.cAccumAlphaBits = 0; descriptor.cDepthBits = 24; descriptor.cStencilBits = 8; descriptor.cAuxBuffers = 0; descriptor.iLayerType = Gdi.PFD_MAIN_PLANE; descriptor.bReserved = 0; descriptor.dwLayerMask = 0; descriptor.dwVisibleMask = 0; descriptor.dwDamageMask = 0; // Attempt to get the device context DeviceContext = User.GetDC(_handle); // Did we not get a device context? if (DeviceContext == IntPtr.Zero) { throw new GLContextException("Can not create a GL device context."); } // Attempt to find an appropriate pixel format var pixelFormat = Gdi.ChoosePixelFormat(DeviceContext, ref descriptor); // Did windows not find a matching pixel format? if (pixelFormat == 0) { throw new GLContextException("Can not find a suitable PixelFormat."); } // Are we not able to set the pixel format? if (!Gdi.SetPixelFormat(DeviceContext, pixelFormat, ref descriptor)) { throw new GLContextException($"Can not set the chosen PixelFormat. Chosen PixelFormat was {pixelFormat}."); } // Attempt to get the rendering context RenderingContext = Wgl.wglCreateContext(DeviceContext); if (RenderingContext == IntPtr.Zero) { throw new GLContextException("Can not create a GL rendering context."); } // Attempt to activate the rendering context MakeCurrent(); }
/// <summary> /// Creates and sets the pixel format and creates and connects the deviceContext and renderContext. /// </summary> public void InitContexts() { int selectedPixelFormat; //Make sure the handle for this control has been created if (this.Handle == IntPtr.Zero) { throw new Exception("InitContexts: The control's window handle has not been created!"); } //Setup pixel format Gdi.PIXELFORMATDESCRIPTOR pixelFormat = new Gdi.PIXELFORMATDESCRIPTOR(); pixelFormat.nSize = (short)Marshal.SizeOf(pixelFormat); //Größe in Byte der Struktur pixelFormat.nVersion = 1; //Versionsnummer pixelFormat.dwFlags = Gdi.PFD_DRAW_TO_WINDOW | Gdi.PFD_SUPPORT_OPENGL | //Kennzeichen Gdi.PFD_DOUBLEBUFFER; pixelFormat.iPixelType = (byte)Gdi.PFD_TYPE_RGBA; //Echtfarb- bzw. Farbindexwerte pixelFormat.cColorBits = 32; //Anzahl der Farbbits pro Pixel; 4,8,16,24,32 = Summe von cRedBits+cGreenBits+cBlueBits pixelFormat.cRedBits = 0; //Anzahl Bits pro Pixel für Rotanteil pixelFormat.cRedShift = 0; //Verschiebung der Rotbits in der Farbe pixelFormat.cGreenBits = 0; //Anzahl Bits pro Pixel für Grünanteil pixelFormat.cGreenShift = 0; //Verschiebung der Grünbits in der Farbe pixelFormat.cBlueBits = 0; //Anzahl Bits pro Pixel für Blauanteil pixelFormat.cBlueShift = 0; //Verschiebung der Blaubits in der Farbe pixelFormat.cAlphaBits = 0; //nicht in der generischen Version pixelFormat.cAlphaShift = 0; //nicht in der generischen Version pixelFormat.cAccumBits = 0; //Anzahl Bits pro Pixel im Akkumulationsbuffer = Summe der folgenden vier Angaben pixelFormat.cAccumRedBits = 0; //BpP für Rot pixelFormat.cAccumGreenBits = 0; //BpP für Grün pixelFormat.cAccumBlueBits = 0; //BpP für Blau pixelFormat.cAccumAlphaBits = 0; //BpP für Alpha-Anteil pixelFormat.cDepthBits = 16; //16 oder 32 pixelFormat.cStencilBits = 0; //BpP im Stencilbuffer pixelFormat.cAuxBuffers = 0; //nicht in der generischen Version pixelFormat.iLayerType = (byte)Gdi.PFD_MAIN_PLANE; //PFD_MAIN_PLANE pixelFormat.bReserved = 0; // = 0 pixelFormat.dwLayerMask = 0; //nicht in der generischen Version pixelFormat.dwVisibleMask = 0; //nicht in der generischen Version pixelFormat.dwDamageMask = 0; //nicht in der generischen Version //Create device context this.deviceContext = User.GetDC(this.Handle); if (this.deviceContext == IntPtr.Zero) { MessageBox.Show("InitContexts: Unable to create an OpenGL device context!", "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(-1); } //Choose the Pixel Format that is the closest to our pixelFormat selectedPixelFormat = Gdi.ChoosePixelFormat(this.deviceContext, ref pixelFormat); //Make sure the requested pixel format is available if (selectedPixelFormat == 0) { MessageBox.Show("InitContexts: Unable to find a suitable pixel format!", "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(-1); } //Sets the selected Pixel Format if (!Gdi.SetPixelFormat(this.deviceContext, selectedPixelFormat, ref pixelFormat)) { MessageBox.Show("InitContexts: Unable to set the requested pixel format!", "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(-1); } //Create rendering context this.renderContext = Wgl.wglCreateContext(this.deviceContext); if (this.renderContext == IntPtr.Zero) { MessageBox.Show("InitContexts: Unable to create an OpenGL rendering context!", "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(-1); } this.MakeCurrentContext(); }
public override void Create(string name, int width, int height, int colorDepth, bool isFullScreen, int left, int top, bool depthBuffer, params object[] miscParams) { // see if a OpenGLContext has been created yet if (hDC == IntPtr.Zero) { // grab the current display settings User.EnumDisplaySettings(null, User.ENUM_CURRENT_SETTINGS, out intialScreenSettings); if (isFullScreen) { Gdi.DEVMODE screenSettings = new Gdi.DEVMODE(); screenSettings.dmSize = (short)Marshal.SizeOf(screenSettings); screenSettings.dmPelsWidth = width; // Selected Screen Width screenSettings.dmPelsHeight = height; // Selected Screen Height screenSettings.dmBitsPerPel = colorDepth; // Selected Bits Per Pixel screenSettings.dmFields = Gdi.DM_BITSPERPEL | Gdi.DM_PELSWIDTH | Gdi.DM_PELSHEIGHT; // Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar. int result = User.ChangeDisplaySettings(ref screenSettings, User.CDS_FULLSCREEN); if (result != User.DISP_CHANGE_SUCCESSFUL) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "Unable to change user display settings."); } } // grab the HWND from the supplied target control hWnd = (IntPtr)((Control)this.Handle).Handle; Gdi.PIXELFORMATDESCRIPTOR pfd = new Gdi.PIXELFORMATDESCRIPTOR(); pfd.nSize = (short)Marshal.SizeOf(pfd); pfd.nVersion = 1; pfd.dwFlags = Gdi.PFD_DRAW_TO_WINDOW | Gdi.PFD_SUPPORT_OPENGL | Gdi.PFD_DOUBLEBUFFER; pfd.iPixelType = (byte)Gdi.PFD_TYPE_RGBA; pfd.cColorBits = (byte)colorDepth; pfd.cDepthBits = 32; // TODO: Find the best setting and use that pfd.cStencilBits = 8; pfd.iLayerType = (byte)Gdi.PFD_MAIN_PLANE; // get the device context hDC = User.GetDC(hWnd); if (hDC == IntPtr.Zero) { throw new Exception("Cannot create a GL device context."); } // attempt to find an appropriate pixel format int pixelFormat = Gdi.ChoosePixelFormat(hDC, ref pfd); if (pixelFormat == 0) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "Unable to find a suitable pixel format."); } if (!Gdi.SetPixelFormat(hDC, pixelFormat, ref pfd)) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "Unable to set the pixel format."); } // attempt to get the rendering context hRC = Wgl.wglCreateContext(hDC); if (hRC == IntPtr.Zero) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "Unable to create a GL rendering context."); } if (!Wgl.wglMakeCurrent(hDC, hRC)) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "Unable to activate the GL rendering context."); } // init the GL context Gl.glShadeModel(Gl.GL_SMOOTH); // Enable Smooth Shading Gl.glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background Gl.glClearDepth(1.0f); // Depth Buffer Setup Gl.glEnable(Gl.GL_DEPTH_TEST); // Enables Depth Testing Gl.glDepthFunc(Gl.GL_LEQUAL); // The Type Of Depth Testing To Do Gl.glHint(Gl.GL_PERSPECTIVE_CORRECTION_HINT, Gl.GL_NICEST); // Really Nice Perspective Calculations } // set the params of the window // TODO: deal with depth buffer this.Name = name; this.colorDepth = colorDepth; this.width = width; this.height = height; this.isFullScreen = isFullScreen; this.top = top; this.left = left; // make this window active this.isActive = true; }
private void _initializeWgl() { // wglGetProcAddress does not work without an active OpenGL context, // but we need wglChoosePixelFormatARB's address before we can // create our main window. Thank you very much, Microsoft! // // The solution is to create a dummy OpenGL window first, and then // test for WGL_ARB_pixel_format support. If it is not supported, // we make sure to never call the ARB pixel format functions. // // If is is supported, we call the pixel format functions at least once // to initialize them (pointers are stored by glprocs.h). We can also // take this opportunity to enumerate the valid FSAA modes. SWF.Form frm = new SWF.Form(); IntPtr hwnd = frm.Handle; // if a simple CreateWindow fails, then boy are we in trouble... if (hwnd == IntPtr.Zero) { throw new Exception("Window creation failed"); } // no chance of failure and no need to release thanks to CS_OWNDC IntPtr hdc = User.GetDC(hwnd); // assign a simple OpenGL pixel format that everyone supports Gdi.PIXELFORMATDESCRIPTOR pfd = new Gdi.PIXELFORMATDESCRIPTOR(); ; pfd.nSize = (short)Marshal.SizeOf(pfd); pfd.nVersion = 1; pfd.cColorBits = 16; pfd.cDepthBits = 15; pfd.dwFlags = Gdi.PFD_DRAW_TO_WINDOW | Gdi.PFD_SUPPORT_OPENGL | Gdi.PFD_DOUBLEBUFFER; pfd.iPixelType = Gdi.PFD_TYPE_RGBA; // if these fail, wglCreateContext will also quietly fail int format; format = Gdi.ChoosePixelFormat(hdc, ref pfd); if (format != 0) { Gdi.SetPixelFormat(hdc, format, ref pfd); } IntPtr hrc = Wgl.wglCreateContext(hdc); if (hrc != IntPtr.Zero) { // if wglMakeCurrent fails, wglGetProcAddress will return null Wgl.wglMakeCurrent(hdc, hrc); Wgl.ReloadFunctions(); // Tao 2.0 // check for pixel format and multisampling support //IntPtr wglGetExtensionsStringARB = Wgl.wglGetProcAddress( "wglGetExtensionsStringARB" ); //if ( wglGetExtensionsStringARB != IntPtr.Zero ) //{ // string exts = Wgl.wglGetExtensionsStringARB( wglGetExtensionsStringARB, hdc ); // _hasPixelFormatARB = exts.Contains( "WGL_ARB_pixel_format" ); // _hasMultisample = exts.Contains( "WGL_ARB_multisample" ); //} _hasPixelFormatARB = Wgl.IsExtensionSupported("WGL_ARB_pixel_format"); _hasMultisample = Wgl.IsExtensionSupported("WGL_ARB_multisample"); if (_hasPixelFormatARB && _hasMultisample) { // enumerate all formats w/ multisampling int[] iattr = { Wgl.WGL_DRAW_TO_WINDOW_ARB, 1, Wgl.WGL_SUPPORT_OPENGL_ARB, 1, Wgl.WGL_DOUBLE_BUFFER_ARB, 1, Wgl.WGL_SAMPLE_BUFFERS_ARB, 1, Wgl.WGL_ACCELERATION_ARB, Wgl.WGL_FULL_ACCELERATION_ARB, // We are no matter about the colour, depth and stencil buffers here //WGL_COLOR_BITS_ARB, 24, //WGL_ALPHA_BITS_ARB, 8, //WGL_DEPTH_BITS_ARB, 24, //WGL_STENCIL_BITS_ARB, 8, // Wgl.WGL_SAMPLES_ARB, 2, 0 }; int[] formats = new int[256]; int[] count = new int[256]; // Tao 2.0 //int count; // cheating here. wglChoosePixelFormatARB proc address needed later on // when a valid GL context does not exist and glew is not initialized yet. _wglChoosePixelFormatARB = Wgl.wglGetProcAddress("wglChoosePixelFormatARB"); if (Wgl.wglChoosePixelFormatARB(hdc, iattr, null, 256, formats, count)) // Tao 2.0 //if ( Wgl.wglChoosePixelFormatARB( _wglChoosePixelFormatARB, hdc, iattr, null, 256, formats, out count ) != 0 ) { // determine what multisampling levels are offered int query = Wgl.WGL_SAMPLES_ARB, samples; for (int i = 0; i < count[0]; ++i) // Tao 2.0 //for ( int i = 0; i < count[ 0 ]; ++i ) { IntPtr wglGetPixelFormatAttribivARB = Wgl.wglGetProcAddress("wglGetPixelFormatAttribivARB"); if (Wgl.wglGetPixelFormatAttribivARB(hdc, formats[i], 0, 1, ref query, out samples)) // Tao 2.0 //if ( Wgl.wglGetPixelFormatAttribivARB( wglGetPixelFormatAttribivARB, hdc, formats[ i ], 0, 1, ref query, out samples ) != 0 ) { if (!_fsaaLevels.Contains(samples)) { _fsaaLevels.Add(samples); } } } } } Wgl.wglMakeCurrent(IntPtr.Zero, IntPtr.Zero); Wgl.wglDeleteContext(hrc); } // clean up our dummy window and class frm.Dispose(); frm = null; }
private void CreateDevice(int width, int height, int bits) { int pixelFormat; // Holds The Results After Searching For A Match //this.Fullscreen = fullscreenflag; GC.Collect(); // Request A Collection // This Forces A Swap Kernel.SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1); if (this.m_bFullscreen) // Attempt Fullscreen Mode? { Gdi.DEVMODE dmScreenSettings = new Gdi.DEVMODE(); // Device Mode // Size Of The Devmode Structure dmScreenSettings.dmSize = (short)Marshal.SizeOf(dmScreenSettings); dmScreenSettings.dmPelsWidth = width; // Selected Screen Width dmScreenSettings.dmPelsHeight = height; // Selected Screen Height dmScreenSettings.dmBitsPerPel = bits; // Selected Bits Per Pixel dmScreenSettings.dmFields = Gdi.DM_BITSPERPEL | Gdi.DM_PELSWIDTH | Gdi.DM_PELSHEIGHT; // Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar. if (User.ChangeDisplaySettings(ref dmScreenSettings, User.CDS_FULLSCREEN) != User.DISP_CHANGE_SUCCESSFUL) { // The Mode Fails throw new Exception("Fullscreen not supported"); } } Gdi.PIXELFORMATDESCRIPTOR pfd = new Gdi.PIXELFORMATDESCRIPTOR(); // pfd Tells Windows How We Want Things To Be pfd.nSize = (short)Marshal.SizeOf(pfd); // Size Of This Pixel Format Descriptor pfd.nVersion = 1; // Version Number pfd.dwFlags = Gdi.PFD_DRAW_TO_WINDOW | // Format Must Support Window Gdi.PFD_SUPPORT_OPENGL | // Format Must Support OpenGL Gdi.PFD_DOUBLEBUFFER; // Format Must Support Double Buffering pfd.iPixelType = (byte)Gdi.PFD_TYPE_RGBA; // Request An RGBA Format pfd.cColorBits = (byte)bits; // Select Our Color Depth pfd.cRedBits = 0; // Color Bits Ignored pfd.cRedShift = 0; pfd.cGreenBits = 0; pfd.cGreenShift = 0; pfd.cBlueBits = 0; pfd.cBlueShift = 0; pfd.cAlphaBits = 0; // No Alpha Buffer pfd.cAlphaShift = 0; // Shift Bit Ignored pfd.cAccumBits = 0; // No Accumulation Buffer pfd.cAccumRedBits = 0; // Accumulation Bits Ignored pfd.cAccumGreenBits = 0; pfd.cAccumBlueBits = 0; pfd.cAccumAlphaBits = 0; pfd.cDepthBits = 16; // 16Bit Z-Buffer (Depth Buffer) pfd.cStencilBits = 0; // No Stencil Buffer pfd.cAuxBuffers = 0; // No Auxiliary Buffer pfd.iLayerType = (byte)Gdi.PFD_MAIN_PLANE; // Main Drawing Layer pfd.bReserved = 0; // Reserved pfd.dwLayerMask = 0; // Layer Masks Ignored pfd.dwVisibleMask = 0; pfd.dwDamageMask = 0; this._hDC = User.GetDC(this.RenderControl.Handle); // Attempt To Get A Device Context if (this._hDC == IntPtr.Zero) { this.KillGLWindow(); throw new Exception("Can't Create A GL Device Context."); } pixelFormat = Gdi.ChoosePixelFormat(this._hDC, ref pfd); // Attempt To Find An Appropriate Pixel Format if (pixelFormat == 0) { // Did Windows Find A Matching Pixel Format? this.KillGLWindow(); throw new Exception("Can't Find A Suitable PixelFormat."); } if (!Gdi.SetPixelFormat(this._hDC, pixelFormat, ref pfd)) // Are We Able To Set The Pixel Format? { this.KillGLWindow(); // Reset The Display throw new Exception("Can't Set The PixelFormat."); } this._hRC = Wgl.wglCreateContext(this._hDC); // Attempt To Get The Rendering Context if (this._hRC == IntPtr.Zero) { this.KillGLWindow(); throw new Exception("Can't Create A GL Rendering Context."); } if (!Wgl.wglMakeCurrent(this._hDC, this._hRC)) // Try To Activate The Rendering Context { this.KillGLWindow(); // Reset The Display throw new Exception("Can't Activate The GL Rendering Context."); } //form.Show(); //form.TopMost = true; //form.Focus(); this.ReSizeGLScene(this.RenderControl.Width, this.RenderControl.Height); // Set Up Our Perspective GL Screen if (!InitGL()) { // Initialize Our Newly Created GL Window this.KillGLWindow(); // Reset The Display throw new Exception("Initialization Failed."); } }
/// <summary> /// Uses Wgl to return the procedure address for an extension function. /// </summary> /// <param name="extension"></param> /// <returns></returns> public override IntPtr GetProcAddress(string extension) { return(Wgl.wglGetProcAddress(extension)); }
private void CreateOpenGLContext(IntPtr hwnd) { this.hwnd = hwnd; this.hDC = GetDC(hwnd); var pixelformatdescriptor = new PIXELFORMATDESCRIPTOR(); pixelformatdescriptor.Init(); #if !USE_MSAA int pixelFormat; pixelFormat = ChoosePixelFormat(this.hDC, ref pixelformatdescriptor); SetPixelFormat(this.hDC, pixelFormat, ref pixelformatdescriptor); this.hglrc = wglCreateContext(this.hDC); wglMakeCurrent(this.hDC, this.hglrc); #else IntPtr tempContext = IntPtr.Zero; IntPtr tempHwnd = IntPtr.Zero; //Create temporary window IntPtr hInstance = Process.GetCurrentProcess().SafeHandle.DangerousGetHandle(); WNDCLASS wndclass = new WNDCLASS() { style = 0x0002 /*CS_HREDRAW*/ | 0x0001 /*CS_VREDRAW*/ | 0x0020 /*CS_OWNDC*/, lpfnWndProc = (hWnd, msg, wParam, lParam) => DefWindowProc(hWnd, msg, wParam, lParam), hInstance = hInstance, lpszClassName = "tmpWindowForMSAA~" + this.GetHashCode() }; ushort atom = RegisterClassW(ref wndclass); if (atom == 0) { throw new WindowCreateException(string.Format("RegisterClass error: {0}", Marshal.GetLastWin32Error())); } tempHwnd = CreateWindowEx( 0, new IntPtr(atom), "tmpWindow~", (uint)(WindowStyles.WS_CLIPSIBLINGS | WindowStyles.WS_CLIPCHILDREN), 0, 0, 1, 1, hwnd, IntPtr.Zero, hInstance, IntPtr.Zero); if (tempHwnd == IntPtr.Zero) { throw new WindowCreateException(string.Format("CreateWindowEx for tempContext error: {0}", Marshal.GetLastWin32Error())); } IntPtr tempHdc = GetDC(tempHwnd); var tempPixelFormat = ChoosePixelFormat(tempHdc, ref pixelformatdescriptor); if (tempPixelFormat == 0) { throw new Exception(string.Format("ChoosePixelFormat failed: error {0}", Marshal.GetLastWin32Error())); } if (!SetPixelFormat(tempHdc, tempPixelFormat, ref pixelformatdescriptor)) { throw new Exception(string.Format("SetPixelFormat failed: error {0}", Marshal.GetLastWin32Error())); } tempContext = Wgl.CreateContext(tempHdc);//Crate temp context to load entry points if (tempContext == IntPtr.Zero) { throw new Exception(string.Format("wglCreateContext for tempHdc failed: error {0}", Marshal.GetLastWin32Error())); } if (!Wgl.MakeCurrent(tempHdc, tempContext)) { throw new Exception(string.Format("wglMakeCurrent for tempContext failed: error {0}", Marshal.GetLastWin32Error())); } //load wgl entry points for wglChoosePixelFormatARB new Wgl().LoadEntryPoints(tempHdc); int[] iPixAttribs = { (int)WGL.WGL_SUPPORT_OPENGL_ARB, (int)GL.GL_TRUE, (int)WGL.WGL_DRAW_TO_WINDOW_ARB, (int)GL.GL_TRUE, (int)WGL.WGL_DOUBLE_BUFFER_ARB, (int)GL.GL_TRUE, (int)WGL.WGL_PIXEL_TYPE_ARB, (int)WGL.WGL_TYPE_RGBA_ARB, (int)WGL.WGL_ACCELERATION_ARB, (int)WGL.WGL_FULL_ACCELERATION_ARB, (int)WGL.WGL_COLOR_BITS_ARB, 32, (int)WGL.WGL_DEPTH_BITS_ARB, 24, (int)WGL.WGL_STENCIL_BITS_ARB, 8, (int)WGL.WGL_SWAP_METHOD_ARB, (int)WGL.WGL_SWAP_EXCHANGE_ARB, (int)WGL.WGL_SAMPLE_BUFFERS_ARB, (int)GL.GL_TRUE,//Enable MSAA (int)WGL.WGL_SAMPLES_ARB, 16, 0 }; int pixelFormat; uint numFormats; var result = Wgl.ChoosePixelFormatARB(this.hDC, iPixAttribs, null, 1, out pixelFormat, out numFormats); if (result == false || numFormats == 0) { throw new Exception(string.Format("wglChoosePixelFormatARB failed: error {0}", Marshal.GetLastWin32Error())); } if (!DescribePixelFormat(this.hDC, pixelFormat, (uint)Marshal.SizeOf <PIXELFORMATDESCRIPTOR>(), ref pixelformatdescriptor)) { throw new Exception(string.Format("DescribePixelFormat failed: error {0}", Marshal.GetLastWin32Error())); } if (!SetPixelFormat(this.hDC, pixelFormat, ref pixelformatdescriptor)) { throw new Exception(string.Format("SetPixelFormat failed: error {0}", Marshal.GetLastWin32Error())); } if ((this.hglrc = wglCreateContext(this.hDC)) == IntPtr.Zero) { throw new Exception(string.Format("wglCreateContext failed: error {0}", Marshal.GetLastWin32Error())); } Wgl.MakeCurrent(IntPtr.Zero, IntPtr.Zero); Wgl.DeleteContext(tempContext); ReleaseDC(tempHwnd, tempHdc); DestroyWindow(tempHwnd); if (!wglMakeCurrent(this.hDC, this.hglrc)) { throw new Exception(string.Format("wglMakeCurrent failed: error {0}", Marshal.GetLastWin32Error())); } Utility.CheckGLError(); #endif GL.GetIntegerv(GL.GL_STENCIL_BITS, IntBuffer); var stencilBits = IntBuffer[0]; if (stencilBits != 8) { throw new Exception("Failed to set stencilBits to 9."); } PrintGraphicInfo(); }
/// <summary> /// Disables the GL /// </summary> public static void DisableOpenGL() { Wgl.wglMakeCurrent((IntPtr)0, (IntPtr)0); Wgl.wglDeleteContext((IntPtr)hRC); }
// --- Private Static Methods --- #region bool CreateGLWindow(string title, int width, int height, int bits, bool fullscreenflag) /// <summary> /// Creates our OpenGL Window. /// </summary> /// <param name="title"> /// The title to appear at the top of the window. /// </param> /// <param name="width"> /// The width of the GL window or fullscreen mode. /// </param> /// <param name="height"> /// The height of the GL window or fullscreen mode. /// </param> /// <param name="bits"> /// The number of bits to use for color (8/16/24/32). /// </param> /// <param name="fullscreenflag"> /// Use fullscreen mode (<c>true</c>) or windowed mode (<c>false</c>). /// </param> /// <returns> /// <c>true</c> on successful window creation, otherwise <c>false</c>. /// </returns> private static bool CreateGLWindow(string title, int width, int height, int bits, bool fullscreenflag) { int pixelFormat; // Holds The Results After Searching For A Match fullscreen = fullscreenflag; // Set The Global Fullscreen Flag form = null; // Null The Form GC.Collect(); // Request A Collection // This Forces A Swap Kernel.SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1); if (fullscreen) // Attempt Fullscreen Mode? { Gdi.DEVMODE dmScreenSettings = new Gdi.DEVMODE(); // Device Mode // Size Of The Devmode Structure dmScreenSettings.dmSize = (short)Marshal.SizeOf(dmScreenSettings); dmScreenSettings.dmPelsWidth = width; // Selected Screen Width dmScreenSettings.dmPelsHeight = height; // Selected Screen Height dmScreenSettings.dmBitsPerPel = bits; // Selected Bits Per Pixel dmScreenSettings.dmFields = Gdi.DM_BITSPERPEL | Gdi.DM_PELSWIDTH | Gdi.DM_PELSHEIGHT; // Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar. if (User.ChangeDisplaySettings(ref dmScreenSettings, User.CDS_FULLSCREEN) != User.DISP_CHANGE_SUCCESSFUL) { // If The Mode Fails, Offer Two Options. Quit Or Use Windowed Mode. if (MessageBox.Show("The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?", "NeHe GL", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes) { fullscreen = false; // Windowed Mode Selected. Fullscreen = false } else { // Pop up A Message Box Lessing User Know The Program Is Closing. MessageBox.Show("Program Will Now Close.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Stop); return(false); // Return false } } } form = new Lesson11(); // Create The Window if (fullscreen) // Are We Still In Fullscreen Mode? { form.FormBorderStyle = FormBorderStyle.None; // No Border Cursor.Hide(); // Hide Mouse Pointer } else // If Windowed { form.FormBorderStyle = FormBorderStyle.Sizable; // Sizable Cursor.Show(); // Show Mouse Pointer } form.Width = width; // Set Window Width form.Height = height; // Set Window Height form.Text = title; // Set Window Title Gdi.PIXELFORMATDESCRIPTOR pfd = new Gdi.PIXELFORMATDESCRIPTOR(); // pfd Tells Windows How We Want Things To Be pfd.nSize = (short)Marshal.SizeOf(pfd); // Size Of This Pixel Format Descriptor pfd.nVersion = 1; // Version Number pfd.dwFlags = Gdi.PFD_DRAW_TO_WINDOW | // Format Must Support Window Gdi.PFD_SUPPORT_OPENGL | // Format Must Support OpenGL Gdi.PFD_DOUBLEBUFFER; // Format Must Support Double Buffering pfd.iPixelType = (byte)Gdi.PFD_TYPE_RGBA; // Request An RGBA Format pfd.cColorBits = (byte)bits; // Select Our Color Depth pfd.cRedBits = 0; // Color Bits Ignored pfd.cRedShift = 0; pfd.cGreenBits = 0; pfd.cGreenShift = 0; pfd.cBlueBits = 0; pfd.cBlueShift = 0; pfd.cAlphaBits = 0; // No Alpha Buffer pfd.cAlphaShift = 0; // Shift Bit Ignored pfd.cAccumBits = 0; // No Accumulation Buffer pfd.cAccumRedBits = 0; // Accumulation Bits Ignored pfd.cAccumGreenBits = 0; pfd.cAccumBlueBits = 0; pfd.cAccumAlphaBits = 0; pfd.cDepthBits = 16; // 16Bit Z-Buffer (Depth Buffer) pfd.cStencilBits = 0; // No Stencil Buffer pfd.cAuxBuffers = 0; // No Auxiliary Buffer pfd.iLayerType = (byte)Gdi.PFD_MAIN_PLANE; // Main Drawing Layer pfd.bReserved = 0; // Reserved pfd.dwLayerMask = 0; // Layer Masks Ignored pfd.dwVisibleMask = 0; pfd.dwDamageMask = 0; hDC = User.GetDC(form.Handle); // Attempt To Get A Device Context if (hDC == IntPtr.Zero) // Did We Get A Device Context? { KillGLWindow(); // Reset The Display MessageBox.Show("Can't Create A GL Device Context.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } pixelFormat = Gdi.ChoosePixelFormat(hDC, ref pfd); // Attempt To Find An Appropriate Pixel Format if (pixelFormat == 0) // Did Windows Find A Matching Pixel Format? { KillGLWindow(); // Reset The Display MessageBox.Show("Can't Find A Suitable PixelFormat.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } if (!Gdi.SetPixelFormat(hDC, pixelFormat, ref pfd)) // Are We Able To Set The Pixel Format? { KillGLWindow(); // Reset The Display MessageBox.Show("Can't Set The PixelFormat.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } hRC = Wgl.wglCreateContext(hDC); // Attempt To Get The Rendering Context if (hRC == IntPtr.Zero) // Are We Able To Get A Rendering Context? { KillGLWindow(); // Reset The Display MessageBox.Show("Can't Create A GL Rendering Context.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } if (!Wgl.wglMakeCurrent(hDC, hRC)) // Try To Activate The Rendering Context { KillGLWindow(); // Reset The Display MessageBox.Show("Can't Activate The GL Rendering Context.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } form.Show(); // Show The Window form.TopMost = true; // Topmost Window form.Focus(); // Focus The Window if (fullscreen) // This Shouldn't Be Necessary, But Is { Cursor.Hide(); } ReSizeGLScene(width, height); // Set Up Our Perspective GL Screen if (!InitGL()) // Initialize Our Newly Created GL Window { KillGLWindow(); // Reset The Display MessageBox.Show("Initialization Failed.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } return(true); // Success }
public override RenderWindow CreateWindow(bool autoCreateWindow, GLRenderSystem renderSystem, string windowTitle) { RenderWindow autoWindow = null; if (autoCreateWindow) { int width = 640; int height = 480; int bpp = 32; bool fullscreen = false; ConfigOption optVM = ConfigOptions["Video Mode"]; string vm = optVM.Value; int pos = vm.IndexOf('x'); if (pos == -1) { throw new Exception("Invalid Video Mode provided"); } width = int.Parse(vm.Substring(0, vm.IndexOf("x"))); height = int.Parse(vm.Substring(vm.IndexOf("x") + 1)); fullscreen = (ConfigOptions["Full Screen"].Value == "Yes"); NamedParameterList miscParams = new NamedParameterList(); ConfigOption opt; opt = ConfigOptions["Color Depth"]; if (opt != null) { miscParams.Add("colorDepth", opt.Value); } opt = ConfigOptions["VSync"]; if (opt != null) { miscParams.Add("vsync", opt.Value); if (Wgl.IsExtensionSupported("wglSwapIntervalEXT")) { Wgl.wglSwapIntervalEXT(StringConverter.ParseBool(opt.Value) ? 1 : 0); } } opt = ConfigOptions["FSAA"]; if (opt != null) { miscParams.Add("fsaa", opt.Value); } // create a default form to use for a rendering target //DefaultForm form = CreateDefaultForm( windowTitle, 0, 0, width, height, fullscreen ); // create the window with the default form as the target autoWindow = renderSystem.CreateRenderWindow(windowTitle, width, height, fullscreen, miscParams); // set the default form's renderwindow so it can access it internally //form.RenderWindow = autoWindow; // show the window //form.Show(); } return(autoWindow); }