public MaterialPlusClippingPlusColorProviderKey(IMaterial material, PlaneD3D[] clipPlanes, Gdi.Plot.IColorProvider colorProvider) : base(material, clipPlanes) { if (null == colorProvider) throw new ArgumentNullException(nameof(colorProvider)); this.ColorProvider = colorProvider; }
public float[] GetColorArrayForColorProvider(Gdi.Plot.IColorProvider colorProvider) { int numberOfColors = 1024; var result = new float[4 * numberOfColors]; for (int i = 0, offs = 0; i < numberOfColors; ++i, offs += 4) { double tu = i / (double)numberOfColors; double u = (tu - UOfColorBelow) / UOfColorRegular; var c = colorProvider.GetAxoColor(u); result[offs + 0] = c.ScR; result[offs + 1] = c.ScG; result[offs + 2] = c.ScB; result[offs + 3] = c.ScA; } return result; }
internal PlotTradeObject(GdiEngine engine, object source, ChartSetting chartSetting) : base(engine, chartSetting) { __cGDI = engine.GDI; __cTrades = source as TradeContainer; }
private void SetFont(Gdi g) { g.Font = FontCache.CreateFont("Calibri", 13, FontStyle.Regular, true); g.TextAlign = Win32.TextAlign.TA_LEFT; g.TextColor = Color.Black; }
/// <summary> /// Swaps the back and front buffer. /// </summary> internal void SwapBuffers() { Gdi.SwapBuffersFast(this.deviceContext); }
void createGLWindow(string title) { int height = 400; int width = 600; int bpp = 16; int pixelFormat; form = null; GC.Collect(); Gdi.DEVMODE dmScreenSettings = new Gdi.DEVMODE(); dmScreenSettings.dmSize = (short)Marshal.SizeOf(dmScreenSettings); dmScreenSettings.dmPelsWidth = width; dmScreenSettings.dmPelsHeight = height; dmScreenSettings.dmBitsPerPel = bpp; dmScreenSettings.dmFields = Gdi.DM_BITSPERPEL | Gdi.DM_PELSWIDTH | Gdi.DM_PELSHEIGHT; form = new EngineOld();; //form.FormBorderStyle = FormBorderStyle.None; form.Width = width; // Set Window Width form.Height = height; // Set Window Height form.Text = 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)bpp; // 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; DC = User.GetDC(form.Handle); // Attempt To Get A Device Context if (DC == 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); //**errorHandler } // Attempt To Find An Appropriate Pixel Format pixelFormat = Gdi.ChoosePixelFormat(DC, ref pfd); 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); } if (!Gdi.SetPixelFormat(DC, 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); } RC = Wgl.wglCreateContext(DC); // Attempt To Get The Rendering Context if (RC == 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); } if (!Wgl.wglMakeCurrent(DC, RC)) { // Try To Activate The Rendering Context killGLWindow(); // Reset The Display MessageBox.Show("Can't Activate The GL Rendering Context.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } form.Show(); // Show The Window //form.TopMost = true; // Topmost Window form.Focus(); // Focus The Window InitLayout(); }
private void CalcContentRectangle() { int buttonHeight = UISettings.CalcPix(24); int buttonWidth = UISettings.CalcPix(75); int w = Width / 10; int textHeight = 0; if (!string.IsNullOrEmpty(_message)) { using (Gdi g = new Gdi(this)) { SetFont(g); Size textSize = g.GetDrawTextSize(_message, w * 9 - _margin * 2, Win32.DT.WORDBREAK); textHeight = textSize.Height; } } int h = _margin + textHeight + _margin + (buttonHeight * 3 + _margin / 2 * 2) + _margin; if (_shortview) { h -= (buttonHeight + _margin / 2); } if (h > Height / 10 * 6) { h = Height / 10 * 6; } int contentWidth = w * 9; int contentHeight = h; int vPos = (Height - contentHeight) / 2; int hPos = w / 2; _contentRectangle = new Rectangle(hPos, vPos, contentWidth, contentHeight); _textRectangle = new Rectangle(_contentRectangle.X + _margin, _contentRectangle.Y + _margin, _contentRectangle.Width - _margin * 2, _contentRectangle.Height - _margin - _margin - (buttonHeight * 3 + _margin / 2 * 2) - _margin); if (_shortview) { _textRectangle.Height += (buttonHeight + _margin / 2); } int buttonXPos = _contentRectangle.Left + (_contentRectangle.Width - buttonWidth) / 2; int buttonYPos = _contentRectangle.Y + _margin + _textRectangle.Height + _margin; _textRectangle.Height -= _margin; buttonUpdate.Location = new Point(buttonXPos, buttonYPos); buttonUpdate.Size = new Size(buttonWidth, buttonHeight); if (!_shortview) { buttonYPos += buttonHeight + _margin / 2; buttonSkip.Location = new Point(buttonXPos, buttonYPos); buttonSkip.Size = new Size(buttonWidth, buttonHeight); buttonSkip.Visible = true; } else { buttonSkip.Location = new Point(buttonXPos, buttonYPos); buttonSkip.Size = new Size(1, 1); buttonSkip.Visible = false; } buttonYPos += buttonHeight + _margin / 2; buttonCancel.Location = new Point(buttonXPos, buttonYPos); buttonCancel.Size = new Size(buttonWidth, buttonHeight); if (_shortview) { buttonCancel.Text = Resources.UpdateInfoDialogControl_Buttons_Exit; } else { buttonCancel.Text = Resources.UpdateInfoDialogControl_Buttons_Cancel; } //Границы и фон _imgLT.Location = new Point(_contentRectangle.X, _contentRectangle.Y); _imgTT.Location = new Point(_imgLT.Right + 1, _contentRectangle.Y); _imgTT.Width = _contentRectangle.Width - _imgLT.Width - _imgRT.Width; _imgRT.Location = new Point(_imgTT.Right + 1, _contentRectangle.Y); _imgLL.Location = new Point(_contentRectangle.X, _imgLT.Bottom + 1); _imgLL.Height = _contentRectangle.Height - _imgLT.Height - _imgLB.Height; _imgRR.Location = new Point(_imgRT.Location.X + _imgRT.Size.Width - _imgRR.Size.Width, _imgRT.Bottom + 1); _imgRR.Height = _contentRectangle.Height - _imgRT.Height - _imgRB.Height; _imgLB.Location = new Point(_contentRectangle.X, _imgLL.Bottom + 1); _imgBB.Location = new Point(_imgLB.Right + 1, _imgLB.Top + 1); _imgBB.Width = _contentRectangle.Width - _imgLB.Width - _imgRB.Width; _imgRB.Location = new Point(_imgBB.Right + 1, _imgLB.Top); _backgroundRectangle = new Rectangle(_imgLL.Right + 1, _imgLL.Top, _imgRR.Left - _imgLL.Right - 1, _imgLL.Height + 1); }
protected override void InternalCopyGraphItems(HostLayer from, Gdi.GraphCopyOptions options) { bool bGraphItems = options.HasFlag(Gdi.GraphCopyOptions.CopyLayerGraphItems); bool bChildLayers = options.HasFlag(Gdi.GraphCopyOptions.CopyChildLayers); bool bLegends = options.HasFlag(Gdi.GraphCopyOptions.CopyLayerLegends); var criterium = new Func<IGraphicBase, bool>(x => { if (x is Gdi.HostLayer) return bChildLayers; if (x is LegendText) return bLegends; return bGraphItems; }); InternalCopyGraphItems(from, options, criterium); }
/// <summary> /// /// </summary> public void SwapBuffers() { Gdi.SwapBuffersFast(deviceContext); }
/// <summary> /// Creates the OpenGL contexts. /// </summary> public void InitializeContexts() { int pixelFormat; // Holds the selected pixel format windowHandle = this.Handle; // Get window handle if (windowHandle == IntPtr.Zero) // No window handle means something is wrong { MessageBox.Show("Window creation error. No window handle.", "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(-1); } Gdi.PIXELFORMATDESCRIPTOR pfd = new Gdi.PIXELFORMATDESCRIPTOR(); // The pixel format descriptor pfd.nSize = (short)Marshal.SizeOf(pfd); // Size of the pixel format descriptor pfd.nVersion = 1; // Version number (always 1) pfd.dwFlags = Gdi.PFD_DRAW_TO_WINDOW | // Format must support windowed mode Gdi.PFD_SUPPORT_OPENGL | // Format must support OpenGL Gdi.PFD_DOUBLEBUFFER; // Must support double buffering pfd.iPixelType = (byte)Gdi.PFD_TYPE_RGBA; // Request an RGBA format pfd.cColorBits = (byte)colorBits; // Select our color depth pfd.cRedBits = 0; // Individual 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; // Alpha shift bit ignored pfd.cAccumBits = accumBits; // Accumulation buffer pfd.cAccumRedBits = 0; // Individual accumulation bits ignored pfd.cAccumGreenBits = 0; pfd.cAccumBlueBits = 0; pfd.cAccumAlphaBits = 0; pfd.cDepthBits = depthBits; // Z-buffer (depth buffer) pfd.cStencilBits = stencilBits; // 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; deviceContext = User.GetDC(windowHandle); // Attempt to get the device context if (deviceContext == IntPtr.Zero) // Did we not get a device context? { MessageBox.Show("Can not create a GL device context.", "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(-1); } pixelFormat = Gdi.ChoosePixelFormat(deviceContext, ref pfd); // Attempt to find an appropriate pixel format if (pixelFormat == 0) // Did windows not find a matching pixel format? { MessageBox.Show("Can not find a suitable PixelFormat.", "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(-1); } if (!Gdi.SetPixelFormat(deviceContext, pixelFormat, ref pfd)) // Are we not able to set the pixel format? { MessageBox.Show("Can not set the chosen PixelFormat. Chosen PixelFormat was " + pixelFormat + ".", "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(-1); } renderingContext = Wgl.wglCreateContext(deviceContext); // Attempt to get the rendering context if (renderingContext == IntPtr.Zero) // Are we not able to get a rendering context? { MessageBox.Show("Can not create a GL rendering context.", "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(-1); } MakeCurrent(); // Attempt to activate the rendering context // Force A Reset On The Working Set Size Kernel.SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1); }
public static void Run() { // Ask The User Which Screen Mode They Prefer if (MessageBox.Show("Would You Like To Run In Fullscreen Mode?", "Start FullScreen?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { fullscreen = false; // Windowed Mode } // Create Our OpenGL Window if (!CreateGLWindow("NeHe's Particle Tutorial", 640, 480, 16, fullscreen)) { return; // Quit If Window Was Not Created } if (fullscreen) // Are We In Fullscreen Mode { slowdown = 1; // If So, Speed Up The Particles (3dfx Issue) } while (!done) // Loop That Runs While done = false { Application.DoEvents(); // Process Events // Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene() if ((active && (form != null) && !DrawGLScene()) || keys[(int)Keys.Escape]) // Active? Was There A Quit Received? { done = true; // ESC Or DrawGLScene Signalled A Quit } else // Not Time To Quit, Update Screen { Gdi.SwapBuffers(hDC); // Swap Buffers (Double Buffering) if (keys[(int)Keys.Add] && (slowdown > 1)) { slowdown -= 0.01f; // Speed Up Particles } if (keys[(int)Keys.Subtract] && (slowdown < 4)) { slowdown += 0.01f; // Slow Down Particles } if (keys[(int)Keys.PageUp]) { zoom += 0.1f; // Zoom In } if (keys[(int)Keys.PageDown]) { zoom -= 0.1f; // Zoom Out } if (keys[(int)Keys.Enter] && !rp) // Return Key Pressed { rp = true; // Set Flag Telling Us It's Pressed rainbow = !rainbow; // Toggle Rainbow Mode On / Off } if (!keys[(int)Keys.Enter]) { rp = false; // If Return Is Released Clear Flag } // Space Or Rainbow Mode if ((keys[(int)Keys.Space] && !sp) || (rainbow && (delay > 25))) { if (keys[(int)Keys.Space]) { rainbow = false; // If Spacebar Is Pressed Disable Rainbow Mode } sp = true; // Set Flag Telling Us Space Is Pressed delay = 0; // Reset The Rainbow Color Cycling Delay col++; // Change The Particle Color if (col > 11) { col = 0; // If Color Is To High Reset It } } if (!keys[(int)Keys.Space]) { sp = false; // If Spacebar Is Released Clear Flag } // If Up Arrow And Y Speed Is Less Than 200 Increase Upward Speed if (keys[(int)Keys.Up] && (yspeed < 200)) { yspeed += 1; } // If Down Arrow And Y Speed Is Greater Than -200 Increase Downward Speed if (keys[(int)Keys.Down] && (yspeed > -200)) { yspeed -= 1; } // If Right Arrow And X Speed Is Less Than 200 Increase Speed To The Right if (keys[(int)Keys.Right] && (xspeed < 200)) { xspeed += 1; } // If Left Arrow And X Speed Is Greater Than -200 Increase Speed To The Left if (keys[(int)Keys.Left] && (xspeed > -200)) { xspeed -= 1; } delay++; // Increase Rainbow Mode Color Cycling Delay Counter if (keys[(int)Keys.F1]) // Is F1 Being Pressed? { keys[(int)Keys.F1] = false; // If So Make Key false KillGLWindow(); // Kill Our Current Window fullscreen = !fullscreen; // Toggle Fullscreen / Windowed Mode // Recreate Our OpenGL Window if (!CreateGLWindow("NeHe's Particle Tutorial", 640, 480, 16, fullscreen)) { return; // Quit If Window Was Not Created } done = false; // We're Not Done Yet } } } // Shutdown KillGLWindow(); // Kill The Window return; // Exit The Program }
public void Action(ChartParameter parameter) { __cGDI.ClearRops(true); __cGDI.ClearRops(__cLineInfos, __cTextInfos, !parameter.Updated); InputDeviceStatus cStatus = parameter.Status; if (cStatus.Event == EInputDeviceEvent.MouseMove) { ZChart cChart = parameter.Chart; AxisX cAxisX = cChart.AxisX; ChartProperty cProperty = cChart.ChartProperty; MouseEventArgs e = cStatus.GetCurrentMouseArgs(); int iOldBKColor = __cGDI.SelectBackground(cProperty.BackgroundColor); IntPtr cOldFont = __cGDI.SelectFont(cProperty.AxisFont); IntPtr cPen = Gdi.CreatePen(new PowerLanguage.PenStyle(cProperty.ForeColor, 1)); int iBarNumber = cAxisX.ConvertBarNumberFromX(e.X); if (iBarNumber > cAxisX.DataCount) { return; } else { Rectangle cAxisXRect = cAxisX.AxisRectangle; AxisXUnit cUnit = cAxisX.ConvertBarNumberToWidth(iBarNumber); cAxisXRect.X = cUnit.CenterPoint; cAxisXRect.Width = cAxisX.FontMetrics.Width * 12; DateTime cDateTime = cAxisX.ConvertBarNumberToTime(iBarNumber); __cLineInfos.Add(__cGDI.DrawRopLine(cPen, cUnit.CenterPoint, 0, cUnit.CenterPoint, cAxisXRect.Y)); __cTextInfos.Add(__cGDI.DrawRopString(cDateTime.ToString("MM/dd HH:mm"), cProperty.BackgroundColor, cProperty.ForeColor, 2, 5, cAxisXRect)); } List <Layer> cLayers = cChart.Layers; int iCount = cLayers.Count; for (int i = 0; i < iCount; i++) { Layer cLayer = cLayers[i]; if (__cLineInfos.Count == 1 && cLayer.IsLayerScope(e.X, e.Y)) { AxisY cAxisY = cLayer.AxisY; Rectangle cAxisYRect = cAxisY.AxisRectangle; cAxisYRect.Y = e.Y; cAxisYRect.Height = cAxisY.FontMetrics.Height; __cLineInfos.Add(__cGDI.DrawRopLine(cPen, 0, e.Y, cAxisYRect.X, e.Y)); __cTextInfos.Add(__cGDI.DrawRopString(Math.Round(cAxisY.ConvertValueFromY(e.Y), cAxisY.Decimals).ToString(), cProperty.BackgroundColor, cProperty.ForeColor, 5, 0, cAxisYRect)); } cLayer.LegendIndex = iBarNumber; __cEngine.DrawLegend(cLayer, cProperty); } __cGDI.RemoveObject(__cGDI.SelectFont(cOldFont)); __cGDI.SelectBackground(iOldBKColor); } //如果使用者使用十字線功能, 如果有在選擇繪圖功能會在 CustomPainter 屬性儲存繪圖功能的類別名稱 //如果有繪圖類別名稱就取出使用 string sName = parameter.CustomPainter; if (__cCustomPainter == null && sName != null) { __cCustomPainter = parameter.Behavior.GetCustomAction(sName); if (__cCustomPainter == null || !(__cCustomPainter is IDrawable)) { parameter.CustomPainter = null; } } if (__cCustomPainter != null) { __cCustomPainter.Action(parameter); //如果繪圖類別名稱 == null 表示繪圖已經完畢 if (parameter.CustomPainter == null) { __cCustomPainter = null; } } }
protected ScummEngine(GameSettings settings, IGraphicsManager gfxManager, IInputManager inputManager, IMixer mixer) { Settings = settings; var game = (GameInfo)settings.Game; _resManager = ResourceManager.Load(game); _game = game; InvalidBox = _game.Version < 5 ? (byte)255 : (byte)0; _gameMD5 = ToMd5Bytes(game.MD5); _gfxManager = gfxManager; _inputManager = inputManager; _inputState = inputManager.GetState(); _strings = new byte[_resManager.NumArray][]; _inventory = new ushort[_resManager.NumInventory]; _invData = new ObjectData[_resManager.NumInventory]; CurrentScript = 0xFF; Mixer = mixer; ScreenWidth = Game.Width; ScreenHeight = Game.Height; AudioCDManager = new DefaultAudioCDManager(this, mixer); Sound = new Sound(this, mixer); SetupMusic(); _variables = new int[_resManager.NumVariables]; _bitVars = new BitArray(_resManager.NumBitVariables); _slots = new ScriptSlot[NumScriptSlot]; for (int i = 0; i < NumScriptSlot; i++) { _slots[i] = new ScriptSlot(); } for (int i = 0; i < 200; i++) { _objs[i] = new ObjectData(); } for (int i = 0; i < 6; i++) { _string[i] = new TextSlot(); if (game.Version != 3) { _string[i].Default.Position = new Point(2, 5); } } _colorCycle = new ColorCycle[16]; for (int i = 0; i < _colorCycle.Length; i++) { _colorCycle[i] = new ColorCycle(); } _nest = new NestedScript[MaxScriptNesting + 1]; for (int i = 0; i < _nest.Length; i++) { _nest[i] = new NestedScript(); } _scaleSlots = new ScaleSlot[20]; for (int i = 0; i < _scaleSlots.Length; i++) { _scaleSlots[i] = new ScaleSlot(); } Gdi = Gdi.Create(this, game); switch (game.Version) { case 0: _costumeLoader = new CostumeLoader0(this); _costumeRenderer = new CostumeRenderer0(this); break; case 7: case 8: _costumeLoader = new AkosCostumeLoader(this); _costumeRenderer = new AkosRenderer(this); break; default: _costumeLoader = new ClassicCostumeLoader(this); _costumeRenderer = new ClassicCostumeRenderer(this); break; } CreateCharset(); ResetCursors(); // Create the text surface var pixelFormat = _game.Features.HasFlag(GameFeatures.Is16BitColor) ? PixelFormat.Rgb16 : PixelFormat.Indexed8; _textSurface = new Surface(ScreenWidth * _textSurfaceMultiplier, ScreenHeight * _textSurfaceMultiplier, PixelFormat.Indexed8, false); ClearTextSurface(); if (Game.Platform == Platform.FMTowns) { _townsScreen = new TownsScreen(_gfxManager, ScreenWidth * _textSurfaceMultiplier, ScreenHeight * _textSurfaceMultiplier, PixelFormat.Rgb16); _townsScreen.SetupLayer(0, ScreenWidth, ScreenHeight, 32767); _townsScreen.SetupLayer(1, ScreenWidth * _textSurfaceMultiplier, ScreenHeight * _textSurfaceMultiplier, 16, _textPalette); } if (Game.Version == 0) { InitScreens(8, 144); } else if ((Game.GameId == GameId.Maniac) && (_game.Version <= 1) && _game.Platform != Platform.NES) { InitScreens(16, 152); } else if (Game.Version >= 7) { InitScreens(0, ScreenHeight); } else { InitScreens(16, 144); } // Allocate gfx compositing buffer (not needed for V7/V8 games). if (Game.Version < 7) { _composite = new Surface(ScreenWidth, ScreenHeight, pixelFormat, false); } InitActors(); OwnerRoom = Game.Version >= 7 ? 0x0FF : 0x0F; if (Game.Version < 7) { Camera.LeftTrigger = 10; Camera.RightTrigger = 30; } InitPalettes(); InitializeVerbs(); // WORKAROUND for bug in boot script of Loom (CD) // The boot script sets the characters of string 21, // before creating the string.resource. if (_game.GameId == GameId.Loom) { _strings[21] = new byte[13]; } }
public override IPositionNormalUIndexedTriangleBuffer GetPositionNormalUIndexedTriangleBuffer(IMaterial material, PlaneD3D[] clipPlanes, Gdi.Plot.IColorProvider colorProvider) { // Transform the clip planes to our coordinate system var clipPlanesTransformed = clipPlanes.Select(plane => _transformation.Transform(plane)).ToArray(); PositionNormalUIndexedTriangleBuffer result; var key = new MaterialPlusClippingPlusColorProviderKey(material, clipPlanesTransformed, colorProvider); if (!_positionNormalUIndexedTriangleBuffers.TryGetValue(key, out result)) { result = new PositionNormalUIndexedTriangleBuffer(this); _positionNormalUIndexedTriangleBuffers.Add(key, result); } return result; }
protected override void DrawItemOn(Gdi g, NativeItemData nativeItem, Rectangle rItem, int nItem) { NativeItemData item = nativeItem; bool isSelected = ShowSelectedItem ? nItem == _SelectedIndex : false; if (rItem.Height > Settings.ListItemPixSize) { rItem = new Rectangle(rItem.Left, rItem.Top + rItem.Height - Settings.ListItemPixSize, rItem.Width, Settings.ListItemPixSize); } //Фон DrawItemBackgroundOn(g, item, rItem, nItem, isSelected); //Аватарка int leftIndent = rItem.Left + item.InfoLeftIndents[0]; int topIndent = rItem.Top + item.InfoTopIndents[0]; #region выводим изображение int index = -1; for (int i = 0; i < NativeItems.Count; i++) { var ni = NativeItems[i]; if (ni.Uid == item.Uid) { index = i; break; } } if (index > -1) { if (IsItemVisible(index)) { if (!string.IsNullOrEmpty(item.PrimaryImageURL)) { if (!item.PrimaryImageURL.Equals("clear")) { IImage newIImage = null; if (File.Exists(item.PrimaryImageURL)) { ImageHelper.LoadImageFromFile(item.PrimaryImageURL, out newIImage); item.PrimaryImage = newIImage; } else { item.PrimaryImage = MasterForm.SkinManager.GetImage("ImageNull"); } } else { item.PrimaryImage = MasterForm.SkinManager.GetImage("ImageNull"); } item.PrimaryImageURL = string.Empty; } int imageMarginLeft = 0; int imageMarginTop = 0; ImageInfo newImageInfo; item.PrimaryImage.GetImageInfo(out newImageInfo); imageMarginLeft = 0; imageMarginTop = 0; g.DrawImageAlphaChannel(item.PrimaryImage, leftIndent + imageMarginLeft, topIndent + imageMarginTop); } } #endregion //полоска var rSep = new Rectangle(rItem.Left, rItem.Top, rItem.Width, 1); g.FillRect(rSep, Settings.ListItemSeparator); //Имя leftIndent = rItem.Left + item.InfoLeftIndents[1]; topIndent = rItem.Top + item.InfoTopIndents[1]; if (!string.IsNullOrEmpty(item.PrimaryText) && !string.IsNullOrEmpty(item.SecondaryText)) { g.TextAlign = Win32.TextAlign.TA_LEFT; if (isSelected) { g.TextColor = Color.White; } else { g.TextColor = Settings.ListItemTextColor; } g.Font = Settings.PrimaryTextFontGdi; Size size = g.GetTextExtent(item.PrimaryText); g.ExtTextOut(leftIndent, topIndent, item.PrimaryText); leftIndent += size.Width; g.Font = Settings.SecondaryTextFontGdi; g.ExtTextOut(leftIndent, topIndent, item.SecondaryText); } //Online leftIndent = rItem.Left + item.InfoLeftIndents[2]; topIndent = rItem.Top + item.InfoTopIndents[2]; if (!string.IsNullOrEmpty(item.TertiaryText)) { g.Font = Settings.ThirdTextFontGdi; g.TextAlign = Win32.TextAlign.TA_LEFT; if (isSelected) { g.TextColor = Color.White; } else { g.TextColor = Color.FromArgb(150, 150, 150); } g.ExtTextOut(leftIndent, topIndent, item.TertiaryText); } }
public Bitmap TextRenderHQ(int _size, string _font, string _color, int _offset, string _str, bool _shadow) { privateFonts = new PrivateFontCollection(); privateFonts.AddFontFile(_font); font = new Font(privateFonts.Families[0], _size); String s = _str; String[] rgbs = _color.Split(new Char[] { ' ', ',', ';', ':' }); Color[] colors = new Color[rgbs.Length]; for (Int32 i = 0; i < rgbs.Length; i++) { colors[i] = HexColorToColor(rgbs[i]); } Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format24bppRgb); Graphics g = Graphics.FromImage(bmp); IntPtr hdc = g.GetHdc(); IntPtr oldfont = Gdi.SelectObject(hdc, font.ToHfont()); TEXTMETRIC tm = new TEXTMETRIC(); Gdi.GetTextMetrics(hdc, ref tm); Int32 totalwidth = 0; Int32[] width = new Int32[1]; Int32[] widths = new Int32[s.Length]; Graphics gs = Graphics.FromImage(new Bitmap(1, 1)); for (Int32 i = 0; i < s.Length; i++) { Gdi.GetCharWidth(hdc, s[i], s[i], width); SizeF sizeW = gs.MeasureString(s[i].ToString(), new Font(_font, _size)); if (s[i] >= 0x4e00 && s[i] <= 0x9fbb) { widths[i] = (int)sizeW.Width - _offset; } else { widths[i] = width[0]; } } SizeF sizeF = gs.MeasureString(s, font); totalwidth = (int)sizeF.Width; Gdi.SelectObject(hdc, oldfont); g.ReleaseHdc(hdc); g.Dispose(); bmp.Dispose(); LayeredImage image = new LayeredImage(totalwidth + 4, tm.tmHeight + 4 + 4); Layer bg = image.Layers.Add(); bg.Clear(Color.Black); bg.DrawText(0, 0, s, font, new SolidBrush(Color.White)); Layer copybg = image.Layers.Copy(bg); copybg.Blur(4, 4); Layer white = image.Layers.Add(); white.Clear(Color.White); if (_shadow) { Layer shadow = image.Layers.Copy(copybg); shadow.Invert(); shadow.Opacity = 0.5; shadow.OffsetX += 4; shadow.OffsetY += 4; } Int32 offsetx = 0; Int32 colorindex = 0; Layer final = image.Layers.Add(); for (Int32 i = 0; i < s.Length; i++) { Color c = colors[colorindex]; colorindex++; if (colorindex >= colors.Length) { colorindex = 0; } SolidBrush brush = new SolidBrush(c); final.FillRectangle(offsetx, 0, widths[i], tm.tmHeight, brush); offsetx += widths[i]; } final.BumpMap(copybg, 135, 45, 3, false); final.Mask = (FastBitmap)bg.Bitmap.Clone(); FastBitmap result = image.Flatten(); result._bitmap.MakeTransparent(); return(result._bitmap); }
protected override LResult WindowProcedure(WindowHandle window, MessageType message, WParam wParam, LParam lParam) { switch (message) { case MessageType.InputLanguageChange: dwCharSet = (CharacterSet)(uint)wParam; goto case MessageType.Create; case MessageType.Create: using (DeviceContext dc = window.GetDeviceContext()) { using (FontHandle font = Gdi.CreateFont(characterSet: dwCharSet, pitch: FontPitch.FixedPitch)) { dc.SelectObject(font); dc.GetTextMetrics(out TextMetrics tm); cxChar = tm.AverageCharWidth; cyChar = tm.Height; dc.SelectObject(StockFont.System); } } goto CalculateSize; case MessageType.Size: cxClient = lParam.LowWord; cyClient = lParam.HighWord; CalculateSize: // calculate window size in characters cxBuffer = Math.Max(1, cxClient / cxChar); cyBuffer = Math.Max(1, cyClient / cyChar); // allocate memory for buffer and clear it pBuffer = new char[cxBuffer, cyBuffer]; // set caret to upper left corner xCaret = 0; yCaret = 0; if (window == Windows.GetFocus()) { Windows.SetCaretPosition(new Point(xCaret * cxChar, yCaret * cyChar)); } window.Invalidate(true); return(0); case MessageType.SetFocus: // create and show the caret window.CreateCaret(default, new Size(cxChar, cyChar)); Windows.SetCaretPosition(new Point(xCaret * cxChar, yCaret * cyChar)); window.ShowCaret(); return(0); case MessageType.KillFocus: // hide and destroy the caret window.HideCaret(); Windows.DestroyCaret(); return(0); case MessageType.KeyDown: switch ((VirtualKey)wParam) { case VirtualKey.Home: xCaret = 0; break; case VirtualKey.End: xCaret = cxBuffer - 1; break; case VirtualKey.Prior: yCaret = 0; break; case VirtualKey.Next: yCaret = cyBuffer - 1; break; case VirtualKey.Left: xCaret = Math.Max(xCaret - 1, 0); break; case VirtualKey.Right: xCaret = Math.Min(xCaret + 1, cxBuffer - 1); break; case VirtualKey.Up: yCaret = Math.Max(yCaret - 1, 0); break; case VirtualKey.Down: yCaret = Math.Min(yCaret + 1, cyBuffer - 1); break; case VirtualKey.Delete: for (int x = xCaret; x < cxBuffer - 1; x++) { pBuffer[x, yCaret] = pBuffer[x + 1, yCaret]; } pBuffer[cxBuffer - 1, yCaret] = ' '; window.HideCaret(); using (DeviceContext dc = window.GetDeviceContext()) { using (FontHandle font = Gdi.CreateFont(characterSet: dwCharSet, pitch: FontPitch.FixedPitch)) { dc.SelectObject(font); unsafe { fixed(char *c = &pBuffer[xCaret, yCaret]) dc.TextOut( new Point(xCaret * cxChar, yCaret * cyChar), new ReadOnlySpan <char>(c, cxBuffer - xCaret)); } dc.SelectObject(StockFont.System); } window.ShowCaret(); } break; } Windows.SetCaretPosition(new Point(xCaret * cxChar, yCaret * cyChar)); return(0); case MessageType.Char: for (int i = 0; i < lParam.LowWord; i++) { switch ((char)wParam) { case '\b': // backspace if (xCaret > 0) { xCaret--; window.SendMessage(MessageType.KeyDown, (uint)VirtualKey.Delete, 1); } break; case '\t': // tab do { window.SendMessage(MessageType.Char, ' ', 1); } while (xCaret % 8 != 0); break; case '\n': // line feed if (++yCaret == cyBuffer) { yCaret = 0; } break; case '\r': // carriage return xCaret = 0; if (++yCaret == cyBuffer) { yCaret = 0; } break; case '\x1B': // escape for (int y = 0; y < cyBuffer; y++) { for (int x = 0; x < cxBuffer; x++) { pBuffer[x, y] = ' '; } } xCaret = 0; yCaret = 0; window.Invalidate(false); break; default: // character codes pBuffer[xCaret, yCaret] = (char)wParam; window.HideCaret(); using (DeviceContext dc = window.GetDeviceContext()) { using (FontHandle font = Gdi.CreateFont(characterSet: dwCharSet, pitch: FontPitch.FixedPitch)) { dc.SelectObject(font); unsafe { fixed(char *c = &pBuffer[xCaret, yCaret]) dc.TextOut( new Point(xCaret * cxChar, yCaret * cyChar), new ReadOnlySpan <char>(c, 1)); } dc.SelectObject(StockFont.System); } window.ShowCaret(); } if (++xCaret == cxBuffer) { xCaret = 0; if (++yCaret == cyBuffer) { yCaret = 0; } } break; } } Windows.SetCaretPosition(new Point(xCaret * cxChar, yCaret * cyChar)); return(0); case MessageType.Paint: using (DeviceContext dc = window.BeginPaint()) { using (FontHandle font = Gdi.CreateFont(0, 0, 0, 0, FontWeight.DoNotCare, false, false, false, dwCharSet, OutputPrecision.Default, ClippingPrecision.Default, Quality.Default, FontPitch.FixedPitch, FontFamilyType.DoNotCare, null)) { dc.SelectObject(font); unsafe { for (int y = 0; y < cyBuffer; y++) fixed(char *c = &pBuffer[0, y]) dc.TextOut(new Point(0, y * cyChar), new ReadOnlySpan <char>(c, cxBuffer)); } dc.SelectObject(StockFont.System); } } return(0); } return(base.WindowProcedure(window, message, wParam, lParam)); }
/// <summary> /// This will create a point list out of the data, which can be used to plot the data. In order to create this list, /// the function must have knowledge how to calculate the points out of the data. This will be done /// by a function provided by the calling function. /// </summary> /// <param name="layer">The plot layer.</param> /// <returns>An array of plot points in layer coordinates.</returns> public Processed2DPlotData GetRangesAndPoints( Gdi.IPlotArea layer) { const double MaxRelativeValue = 1E2; Altaxo.Data.IReadableColumn xColumn = this.XColumn; Altaxo.Data.IReadableColumn yColumn = this.YColumn; if (null == xColumn || null == yColumn) return null; // this plotitem is only for x and y double columns Processed2DPlotData result = new Processed2DPlotData(); MyPlotData myPlotData = new MyPlotData(xColumn, yColumn); result.XPhysicalAccessor = new IndexedPhysicalValueAccessor(myPlotData.GetXPhysical); result.YPhysicalAccessor = new IndexedPhysicalValueAccessor(myPlotData.GetYPhysical); PlotRangeList rangeList = null; // allocate an array PointF to hold the line points // _tlsBufferedPlotData is a static buffer that is allocated per thread // and thus is only used temporary here in this routine if (null == _tlsBufferedPlotData) _tlsBufferedPlotData = new List<PointF>(); else _tlsBufferedPlotData.Clear(); // Fill the array with values // only the points where x and y are not NaNs are plotted! bool bInPlotSpace = true; int plotRangeStart = 0; int rangeOffset = 0; rangeList = new PlotRangeList(); result.RangeList = rangeList; Scale xAxis = layer.XAxis; Scale yAxis = layer.YAxis; Gdi.G2DCoordinateSystem coordsys = layer.CoordinateSystem; int maxRowIndex = GetMaximumRowIndexFromDataColumns(); int plotArrayIdx = 0; foreach (int dataRowIdx in _dataRowSelection.GetSelectedRowIndicesFromTo(0, maxRowIndex, _dataTable?.Document?.DataColumns, maxRowIndex)) { if (xColumn.IsElementEmpty(dataRowIdx) || yColumn.IsElementEmpty(dataRowIdx)) { if (!bInPlotSpace) { bInPlotSpace = true; rangeList.Add(new PlotRange(plotRangeStart, plotArrayIdx, rangeOffset)); } continue; } double x_rel, y_rel; double xcoord, ycoord; x_rel = xAxis.PhysicalVariantToNormal(xColumn[dataRowIdx]); y_rel = yAxis.PhysicalVariantToNormal(yColumn[dataRowIdx]); // chop relative values to an range of about -+ 10^6 if (x_rel > MaxRelativeValue) x_rel = MaxRelativeValue; if (x_rel < -MaxRelativeValue) x_rel = -MaxRelativeValue; if (y_rel > MaxRelativeValue) y_rel = MaxRelativeValue; if (y_rel < -MaxRelativeValue) y_rel = -MaxRelativeValue; // after the conversion to relative coordinates it is possible // that with the choosen axis the point is undefined // (for instance negative values on a logarithmic axis) // in this case the returned value is NaN if (coordsys.LogicalToLayerCoordinates(new Logical3D(x_rel, y_rel), out xcoord, out ycoord)) { if (bInPlotSpace) { bInPlotSpace = false; plotRangeStart = plotArrayIdx; rangeOffset = dataRowIdx - plotArrayIdx; } _tlsBufferedPlotData.Add(new PointF((float)xcoord, (float)ycoord)); plotArrayIdx++; } else { if (!bInPlotSpace) { bInPlotSpace = true; rangeList.Add(new PlotRange(plotRangeStart, plotArrayIdx, rangeOffset)); } } } // end foreach if (!bInPlotSpace) { bInPlotSpace = true; rangeList.Add(new PlotRange(plotRangeStart, plotArrayIdx, rangeOffset)); // add the last range } result.PlotPointsInAbsoluteLayerCoordinates = _tlsBufferedPlotData.ToArray(); return result; }
public void EnumerateDisplaySettings_Null() { var settings = Gdi.EnumerateDisplaySettings(null).ToArray(); settings.Should().NotBeEmpty(); }
/// <summary> /// Функция "распила" текста на строчки /// </summary> /// <param name="text">Исходный текст</param> /// <param name="width">Ширина области отображения текста</param> /// <param name="count">Количество выводимых строк (если значение не ограничено указать 0)</param> /// <param name="g">Графический контекст</param> /// <returns></returns> public static List <string> CutTextToLines(string inputText, int textWidth, int linesCount, Gdi g) { List <string> result = new List <string>(); if (linesCount == 0) { linesCount = int.MaxValue; } inputText = inputText.Replace("\r", string.Empty); string[] lines = inputText.Split('\n'); // первый распил по символам переноса строки int currentLine; int maxChars; string text; string outtext; int ipreviouscol; int icol; int[] extents; Size size; bool isSpace; // признак: пробел bool isOver; // признак: нужна новая строка currentLine = 0; try { foreach (string line in lines) { currentLine++; text = line; icol = line.Length; ipreviouscol = 0; do { text = line.Substring(ipreviouscol); size = g.GetTextExtent(text, textWidth, out extents, out maxChars); isSpace = false; isOver = false; if (text.Length > maxChars) { isOver = true; // ищем первый пробел по которому можем обрезать int iSpace = text.LastIndexOf(' ', maxChars, maxChars); if (iSpace > -1) // он есть { isSpace = true; icol = iSpace; } else // его нет { isSpace = false; icol = maxChars; } outtext = text.Substring(0, icol); // обрезаем кусок текста до пробела } else { isOver = false; outtext = text; // берем весь текст } // если в конце строки был пробел, то это необходимо учесть на следующей итерации if (isSpace) { ipreviouscol += (icol + 1); } else { ipreviouscol += icol; } // если набрали требуемое в linesCount количество строк, необходимо прервать фукцию обработки // если к этому моменту остался необработанный текст, необходимо добавить символы "..." if (linesCount > (result.Count + 1)) { result.Add(outtext); } else { if (isOver || (lines.Length != currentLine)) { outtext = outtext.Remove(outtext.Length - 3, 3); // удаляем последние 3 символа чтобы "..." гарантировано влезло outtext = outtext.Trim(); outtext += "..."; } result.Add(outtext); throw new Exception(); } }while (text.Length > maxChars); } } catch // чтобы выйти из всех циклов { // } return(result); }
/// <summary> /// Creates the device and rendering contexts using the supplied settings /// in accumBits, colorBits, depthBits, and stencilBits. Returns the selected /// pixel format number. /// </summary> protected virtual int CreateContexts(IntPtr pDeviceContext, int preferredPixelFormatNum) { deviceContext = pDeviceContext; if (deviceContext == IntPtr.Zero) { throw new Exception("CreateContexts: Unable to create an OpenGL device context"); } int selectedFormat = 0; Gdi.PIXELFORMATDESCRIPTOR pixelFormat = new Gdi.PIXELFORMATDESCRIPTOR(); pixelFormat.nSize = (short)Marshal.SizeOf(pixelFormat); pixelFormat.nVersion = 1; //Here we care most about finding a format that will allow the proper creation of the control first and foremost, because even if the format is so bad that output to the display cannot be understood by the user, then the user is able to change the graphical options from within the program. We care second most about finding a format which is quick to load and which will be most time efficient during graphics display. Again, if a wrong choice is made, the user can make a choice of format manually. try { //Simply try the preferred pixel format number. If it works, then that is all we care about. Remember, 0 is an invalid format number. if (_DescribePixelFormat(deviceContext, preferredPixelFormatNum, (uint)pixelFormat.nSize, ref pixelFormat) == 0 || !Gdi.SetPixelFormat(deviceContext, preferredPixelFormatNum, ref pixelFormat)) { throw new Exception(string.Format("Unable to set the requested pixel format ({0})", selectedFormat)); } selectedFormat = preferredPixelFormatNum; }catch { //Could not set the preferred pixel format for some reason. Possibly initial startup or the graphics card or driver changed since the program was last started. //Now try to auto-select the best pixel-format for speed efficientcy and graphical quality. try{ PixelFormatValue pfv = ChoosePixelFormatEx(deviceContext); if (!Gdi.SetPixelFormat(deviceContext, pfv.formatNumber, ref pfv.pfd)) { throw new Exception(""); } pixelFormat = pfv.pfd; selectedFormat = pfv.formatNumber; }catch { pixelFormat = new Gdi.PIXELFORMATDESCRIPTOR(); //Zero out the old pixel format. pixelFormat.nSize = (short)Marshal.SizeOf(pixelFormat); pixelFormat.nVersion = 1; //Unable to select a good pixel format. Now we are desperate. Try all formats starting from 1 until we get some format which at least works. That way the user can change the pixel format from the graphical options from inside the program after this point. selectedFormat = 0; do { selectedFormat++; if (selectedFormat > _DescribePixelFormat(deviceContext, selectedFormat, (uint)pixelFormat.nSize, ref pixelFormat)) { throw new Exception("There are no acceptable pixel formats for OpenGL graphics."); } }while(!Gdi.SetPixelFormat(deviceContext, selectedFormat, ref pixelFormat)); } } colorBits = pixelFormat.cColorBits; depthBits = pixelFormat.cDepthBits; autoSwapBuffers = FormatSupportsDoubleBuffering(pixelFormat); usehardware = FormatSupportsAcceleration(pixelFormat); //Create rendering context renderContext = Wgl.wglCreateContext(deviceContext); if (renderContext == IntPtr.Zero) { throw new Exception("CreateContexts: Unable to create an OpenGL rendering context"); } //Make this the current context MakeCurrentContext(); return(selectedFormat); }
protected override void OnPaint(PaintEventArgs e) { //base.OnPaint(e); //Bitmap bmp = new Bitmap(100, 100); Graphics g = e.Graphics; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed; Gdi gg = new Gdi(this.Handle); Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 100000; i++) { //g.FillRectangle(Brushes.Black, 0, 0, 100, 100); //g.DrawLine(Pens.Black, 0, 0, 100, 100); //gg.DrawLine(Pens.Black, 0, 0, 100, 100); //gg.DrawRectangle(Pens.Red, 100, 100, 200, 200); //g.DrawRectangle(Pens.Red, 100, 100, 200, 200); } gg.Dispose(); //e.Graphics.DrawImageUnscaled(bmp, 0, 0); sw.Stop(); System.Console.WriteLine(sw.ElapsedMilliseconds); }
public bool InitGLWindow(Control parent, int width, int height, int bits) { int pixelFormat; // Holds The Results After Searching For A Match this.parent = parent; GC.Collect(); // Request A Collection // This Forces A Swap Kernel.SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1); 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(parent.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); } 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); // Everything Went OK }
/// <summary> /// Creates and sets the pixel format and creates and connects the deviceContext and renderContext. /// </summary> internal 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); pixelFormat.nVersion = 1; pixelFormat.dwFlags = Gdi.PFD_DRAW_TO_WINDOW | Gdi.PFD_SUPPORT_OPENGL | Gdi.PFD_DOUBLEBUFFER; pixelFormat.iPixelType = (byte)Gdi.PFD_TYPE_RGBA; pixelFormat.cColorBits = 32; pixelFormat.cRedBits = 0; pixelFormat.cRedShift = 0; pixelFormat.cGreenBits = 0; pixelFormat.cGreenShift = 0; pixelFormat.cBlueBits = 0; pixelFormat.cBlueShift = 0; pixelFormat.cAlphaBits = 0; pixelFormat.cAlphaShift = 0; pixelFormat.cAccumBits = 0; pixelFormat.cAccumRedBits = 0; pixelFormat.cAccumGreenBits = 0; pixelFormat.cAccumBlueBits = 0; pixelFormat.cAccumAlphaBits = 0; pixelFormat.cDepthBits = 16; pixelFormat.cStencilBits = 0; pixelFormat.cAuxBuffers = 0; pixelFormat.iLayerType = (byte)Gdi.PFD_MAIN_PLANE; pixelFormat.bReserved = 0; pixelFormat.dwLayerMask = 0; pixelFormat.dwVisibleMask = 0; pixelFormat.dwDamageMask = 0; //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 abstract void DrawItemOn(Gdi g, Rectangle rItem);
public static void Run() { // Ask The User Which Screen Mode They Prefer if (MessageBox.Show("Would You Like To Run In Fullscreen Mode?", "Start FullScreen?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { fullscreen = false; // Windowed Mode } // Create Our OpenGL Window if (!CreateGLWindow("Lionel Brits & NeHe's 3D World Tutorial", 640, 480, 16, fullscreen)) { return; // Quit If Window Was Not Created } while (!done) // Loop That Runs While done = false { Application.DoEvents(); // Process Events // Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene() if ((active && (form != null) && !DrawGLScene()) || keys[(int)Keys.Escape]) // Active? Was There A Quit Received? { done = true; // ESC Or DrawGLScene Signalled A Quit } else // Not Time To Quit, Update Screen { Gdi.SwapBuffers(hDC); // Swap Buffers (Double Buffering) if (keys[(int)Keys.B] && !bp) { bp = true; blend = !blend; if (!blend) { Gl.glDisable(Gl.GL_BLEND); Gl.glEnable(Gl.GL_DEPTH_TEST); } else { Gl.glEnable(Gl.GL_BLEND); Gl.glDisable(Gl.GL_DEPTH_TEST); } } if (!keys[(int)Keys.B]) { bp = false; } if (keys[(int)Keys.F] && !fp) { fp = true; filter += 1; if (filter > 2) { filter = 0; } } if (!keys[(int)Keys.F]) { fp = false; } if (keys[(int)Keys.PageUp]) { z -= 0.02f; } if (keys[(int)Keys.PageDown]) { z += 0.02f; } if (keys[(int)Keys.Up]) { xpos -= (float)Math.Sin(heading * piover180) * 0.05f; zpos -= (float)Math.Cos(heading * piover180) * 0.05f; if (walkbiasangle >= 359) { walkbiasangle = 0; } else { walkbiasangle += 10; } walkbias = (float)Math.Sin(walkbiasangle * piover180) / 20; } if (keys[(int)Keys.Down]) { xpos += (float)Math.Sin(heading * piover180) * 0.05f; zpos += (float)Math.Cos(heading * piover180) * 0.05f; if (walkbiasangle <= 1) { walkbiasangle = 359; } else { walkbiasangle -= 10; } walkbias = (float)Math.Sin(walkbiasangle * piover180) / 20; } if (keys[(int)Keys.Right]) { heading -= 1; yrot = heading; } if (keys[(int)Keys.Left]) { heading += 1; yrot = heading; } if (keys[(int)Keys.PageUp]) { lookupdown -= 1; } if (keys[(int)Keys.PageDown]) { lookupdown += 1; } if (keys[(int)Keys.F1]) // Is F1 Being Pressed? { keys[(int)Keys.F1] = false; // If So Make Key false KillGLWindow(); // Kill Our Current Window fullscreen = !fullscreen; // Toggle Fullscreen / Windowed Mode // Recreate Our OpenGL Window if (!CreateGLWindow("Lionel Brits & NeHe's 3D World Tutorial", 640, 480, 16, fullscreen)) { return; // Quit If Window Was Not Created } done = false; // We're Not Done Yet } } } // Shutdown KillGLWindow(); // Kill The Window return; // Exit The Program }
/// <summary> /// Отрисовка /// </summary> protected override void OnRender(Gdi gMem, Rectangle clipRect) { using (Bitmap bmp = new Bitmap(clipRect.Width, clipRect.Height)) { using (Graphics bgr = Graphics.FromImage(bmp)) // Рисуем все в буфере для скорости { SizeF textSize = string.IsNullOrEmpty(Text) ? new SizeF(0, 0) : bgr.MeasureString(Text, Font); Color textColor = SwitchTextColor ? BackColor : ForeColor; // Отрисовка фона if (EmptyImage != null) { bgr.DrawImage(_emptyImageBitmap, new Rectangle(0, 0, clipRect.Width, clipRect.Height), new Rectangle(0, 0, _emptyImageBitmap.Width, _emptyImageBitmap.Height), GraphicsUnit.Pixel); } // Отрисовка прогресса if (FullImage != null) { bgr.DrawImage(_fullImageBitmap, new Rectangle(0, 0, clipRect.Width * Value / Maximum, clipRect.Height), new Rectangle(0, 0, _fullImageBitmap.Width * Value / Maximum, _fullImageBitmap.Height), GraphicsUnit.Pixel); } Pen borderPen = new Pen(SwitchTextColor ? Color.FromArgb(88, 97, 114 /*93, 103, 121*/) : Color.Black); if (NeedBorder) { // Обводка прямых краев bgr.DrawLine(borderPen, RoundCornersRadius, 0, Width - RoundCornersRadius, 0); bgr.DrawLine(borderPen, Width - 1, RoundCornersRadius - 2, Width - 1, Height - RoundCornersRadius + 2); bgr.DrawLine(borderPen, RoundCornersRadius - 3, Height - 1, Width + 3 - RoundCornersRadius, Height - 1); bgr.DrawLine(borderPen, 0, RoundCornersRadius, 0, Height - RoundCornersRadius); } //Отрисовка текста float textLeft = (clipRect.Width - textSize.Width) / 2; float textTop = (clipRect.Height - textSize.Height) / 2; if (!string.IsNullOrEmpty(Text)) { bgr.DrawString(Text, Font, new SolidBrush(textColor), new RectangleF(textLeft, textTop, textSize.Width, textSize.Height)); } // Скругление углов if (RoundCornersRadius > 0) { // Необходимо скругление - вычисление точек границы вырезаемой области int N = 100; List <Point> points = new List <Point>(N + 1); Point[] pointsArray = new Point[N]; points.Add(new Point(0, 0)); // Скругление верхнего левого угла кнопки for (int i = 0; i < N; i++) { int x = i * RoundCornersRadius / (N - 1); int y = (int)(RoundCornersRadius - Math.Round(Math.Sqrt(RoundCornersRadius * RoundCornersRadius - (x - RoundCornersRadius) * (x - RoundCornersRadius)))); points.Add(new Point(x, y)); } bgr.FillPolygon(new SolidBrush(Parent.BackColor), points.ToArray()); if (NeedBorder) { // Обводка верхнего левого угла кнопки points.CopyTo(1, pointsArray, 0, N); bgr.DrawLines(borderPen, pointsArray); } // Скругление верхнего правого угла кнопки for (int i = 0; i < N + 1; i++) { points[i] = new Point(clipRect.Width - points[i].X, points[i].Y); } bgr.FillPolygon(new SolidBrush(Parent.BackColor), points.ToArray()); if (NeedBorder) { // Обводка верхнего правого угла кнопки points.CopyTo(1, pointsArray, 0, N); bgr.DrawLines(borderPen, pointsArray); } // Скругление нижнего правого угла кнопки for (int i = 0; i < N + 1; i++) { points[i] = new Point(points[i].X, clipRect.Height - points[i].Y); } bgr.FillPolygon(new SolidBrush(Parent.BackColor), points.ToArray()); if (NeedBorder) { // Обводка нижнего правого угла кнопки points.CopyTo(1, pointsArray, 0, N); bgr.DrawLines(borderPen, pointsArray); } // Скругление нижнего левого угла кнопки for (int i = 0; i < N + 1; i++) { points[i] = new Point(clipRect.Width - points[i].X, points[i].Y); } bgr.FillPolygon(new SolidBrush(Parent.BackColor), points.ToArray()); if (NeedBorder) { // Обводка нижнего левого угла кнопки points.CopyTo(1, pointsArray, 0, N); bgr.DrawLines(borderPen, pointsArray); } } } gMem.DrawImage(bmp, clipRect.Left, clipRect.Top); } }
private void CalcContentRectangle() { int w = Width / 8; int textHeight = 0; if (!string.IsNullOrEmpty(_message)) { using (Gdi g = new Gdi(this)) { SetFont(g); Size textSize = g.GetDrawTextSize(_message, w * 6 - _margin * 2, Win32.DT.WORDBREAK); textHeight = textSize.Height; } } int h = textBoxStatus.Height + /*buttonOk.Height*/ 30 * 3 + _margin * 10; if (h > Height / 8 * 6) { h = Height / 8 * 6; } int contentWidth = w * 6; int contentHeight = h; int vPos = (Height - contentHeight) / 2; int hPos = w; _contentRectangle = new Rectangle(hPos, vPos, contentWidth, contentHeight); /* * _textRectangle = new Rectangle(_contentRectangle.X + _margin, _contentRectangle.Y + _margin, * _contentRectangle.Width - _margin * 2, * _contentRectangle.Height - _margin * 3 - buttonOk.Height); */ int workWidth = _contentRectangle.Width - _margin * 3; int left = hPos + _margin; textBoxStatus.Location = new Point(left + _contentRectangle.Left, _contentRectangle.Y + _margin * 3); textBoxStatus.Size = new Size(workWidth - _margin * 4, 30); buttonOk.Location = new Point(left + _contentRectangle.Left, textBoxStatus.Location.Y + textBoxStatus.Height + _margin); buttonOk.Size = new Size(workWidth - _margin * 4, 30); buttonReset.Location = new Point(left + _contentRectangle.Left, buttonOk.Location.Y + buttonOk.Height + _margin); buttonReset.Size = new Size(workWidth - _margin * 4, 30); buttonCancel.Location = new Point(left + _contentRectangle.Left, buttonReset.Location.Y + buttonReset.Height + _margin); buttonCancel.Size = new Size(workWidth - _margin * 4, 30); //Границы и фон _imgLT.Location = new Point(_contentRectangle.X, _contentRectangle.Y); _imgTT.Location = new Point(_imgLT.Right + 1, _contentRectangle.Y); _imgTT.Width = _contentRectangle.Width - _imgLT.Width - _imgRT.Width; _imgRT.Location = new Point(_imgTT.Right + 1, _contentRectangle.Y); _imgLL.Location = new Point(_contentRectangle.X, _imgLT.Bottom + 1); _imgLL.Height = _contentRectangle.Height - _imgLT.Height - _imgLB.Height; _imgRR.Location = new Point(_imgRT.Location.X + _imgRT.Size.Width - _imgRR.Size.Width, _imgRT.Bottom + 1); _imgRR.Height = _contentRectangle.Height - _imgRT.Height - _imgRB.Height; _imgLB.Location = new Point(_contentRectangle.X, _imgLL.Bottom + 1); _imgBB.Location = new Point(_imgLB.Right + 1, _imgLB.Top); _imgBB.Width = _contentRectangle.Width - _imgLB.Width - _imgRB.Width; _imgRB.Location = new Point(_imgBB.Right + 1, _imgLB.Top); _backgroundRectangle = new Rectangle(_imgLL.Right + 1, _imgLL.Top, _imgRR.Left - _imgLL.Right - 1, _imgLL.Height); }
protected override void OnRender(Gdi graphics, Rectangle clipRect) { //graphics.DrawText(_message, // new Win32.RECT(_textRectangle.X, // _textRectangle.Y, // _textRectangle.Width, // _textRectangle.Height), // Win32.DT.LEFT | Win32.DT.TOP | Win32.DT.WORDBREAK); clipRect.Intersect(this.Rectangle); if (clipRect.IsEmpty) { return; } //base.OnRender(graphics, clipRect); //SetupDefaultClip(g); float topAdjust = 0; switch (VerticalTextAlignment) { case VerticalAlignment.Top: topAdjust = 0; break; case VerticalAlignment.Bottom: //topAdjust = ClientHeight - _totalHeight; topAdjust = Height - _totalHeight; break; case VerticalAlignment.Center: //topAdjust = (ClientHeight - _totalHeight) / 2; topAdjust = (Height - _totalHeight) / 2; break; } if (BackColor != Color.Transparent) { graphics.FillRect( //new Rectangle(e.Origin.X, e.Origin.Y, ClientWidth, ClientHeigh), clipRect, BackColor); } foreach (LineBreak lineBreak in _lineBreaks) { float leftAdjust = 0; switch (HorizontalTextAlignment) { case HorizontalAlignment.Left: leftAdjust = 0; break; case HorizontalAlignment.Right: //leftAdjust = ClientWidth - lineBreak.Width; leftAdjust = Width - lineBreak.Width; break; case HorizontalAlignment.Center: //leftAdjust = (ClientWidth - lineBreak.Width) / 2.0f; leftAdjust = (Width - lineBreak.Width) / 2.0f; break; } Rectangle drawRect = new Rectangle(this.Left + Margin.Left + (int)leftAdjust, this.Top + Margin.Top + (int)topAdjust, (int)lineBreak.Width, (int)lineBreak.Height); if (clipRect.IntersectsWith(drawRect)) { graphics.Font = Font; graphics.TextColor = ForeColor; //graphics. //TODO: chhange all this code to only one single DrawText graphics.ExtTextOut(drawRect.Left, drawRect.Top, drawRect.Width, lineBreak.Text); // new Galssoft.WM.Components.SystemHelpers.Win32.RECT(drawRect), Galssoft.WM.Components.SystemHelpers.Win32.DT.LEFT); //Font, myForeBrush, e.Origin.X + leftAdjust, e.Origin.Y + topAdjust); } topAdjust += lineBreak.Height; if (topAdjust > Height) { break; } } }
// --- 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 Lesson01(); // 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 }
protected override void DrawItemOn(Gdi g, NativeItemData nativeItem, Rectangle rItem, int nItem) { int topIndent; int leftIndent; NativeItemData item = nativeItem; bool isSelected = ShowSelectedItem ? nItem == _SelectedIndex : false; //фон DrawItemBackgroundOn(g, item, rItem, nItem, isSelected); //полоска var rSep = new Rectangle(rItem.Left, rItem.Top, rItem.Width, 1); g.FillRect(rSep, Settings.ListItemSeparator); // дата topIndent = rItem.Top + item.InfoTopIndents[0]; leftIndent = rItem.Right - item.InfoLeftIndents[1]; if (IsItemNewGroup(nItem)) { topIndent += Settings.GroupPixHeight; } if (!string.IsNullOrEmpty(item.TertiaryText)) { g.Font = Settings.ThirdTextFontGdi; g.TextAlign = Win32.TextAlign.TA_RIGHT; g.TextColor = Color.FromArgb(51, 153, 255); if (isSelected) { g.TextColor = Color.White; } g.ExtTextOut(leftIndent, topIndent, item.TertiaryText); } // текст сообщения leftIndent = rItem.Left + item.InfoLeftIndents[0]; topIndent = rItem.Top + item.InfoTopIndents[0]; if (IsItemNewGroup(nItem)) { topIndent += Settings.GroupPixHeight; } if (item.SecondaryTextLines.Count > 0) { g.Font = Settings.SecondaryTextFontGdi; g.TextAlign = Win32.TextAlign.TA_LEFT; g.TextColor = Color.FromArgb(102, 102, 102); if (isSelected) { g.TextColor = Color.White; } foreach (string line in item.SecondaryTextLines) { g.ExtTextOut(leftIndent, topIndent, line); topIndent += UISettings.CalcPix(11); } } }
/// <summary> /// Tile background image to client size /// </summary> protected Bitmap PrepareBackground(Bitmap bmp) { return(Gdi.PrepareBackground(bmp, ClientSize.Width, ClientSize.Height)); }
private void DrawData(PaintEventArgs e, List <RollColumn> visibleColumns) { if (QueryItemText != null) { if (HorizontalOrientation) { int startRow = FirstVisibleRow; int range = Math.Min(LastVisibleRow, RowCount - 1) - startRow + 1; Gdi.PrepDrawString(NormalFont, _foreColor); for (int i = 0, f = 0; f < range; i++, f++) { f += lagFrames[i]; int LastVisible = LastVisibleColumnIndex; for (int j = FirstVisibleColumn; j <= LastVisible; j++) { Bitmap image = null; int x = 0; int y = 0; int bitmapOffsetX = 0; int bitmapOffsetY = 0; if (QueryItemIcon != null) { QueryItemIcon(f + startRow, visibleColumns[j], ref image, ref bitmapOffsetX, ref bitmapOffsetY); } if (image != null) { x = RowsToPixels(i) + CellWidthPadding + bitmapOffsetX; y = (j * CellHeight) + (CellHeightPadding * 2) + bitmapOffsetY; Gdi.DrawBitmap(image, new Point(x, y), true); } string text; int strOffsetX = 0; int strOffsetY = 0; QueryItemText(f + startRow, visibleColumns[j], out text, ref strOffsetX, ref strOffsetY); // Center Text x = RowsToPixels(i) + (CellWidth - text.Length * _charSize.Width) / 2; y = (j * CellHeight) + CellHeightPadding - VBar.Value; var point = new Point(x + strOffsetX, y + strOffsetY); var rePrep = false; if (j == 1) { if (SelectedItems.Contains(new Cell { Column = visibleColumns[j], RowIndex = i + startRow })) { Gdi.PrepDrawString(RotatedFont, SystemColors.HighlightText); rePrep = true; } else if (j == 1) { //1. not sure about this; 2. repreps may be excess, but if we render one column at a time, we do need to change back after rendering the header rePrep = true; Gdi.PrepDrawString(RotatedFont, _foreColor); } } if (!string.IsNullOrWhiteSpace(text)) { Gdi.DrawString(text, point); } if (rePrep) { Gdi.PrepDrawString(NormalFont, _foreColor); } } } } else { int startRow = FirstVisibleRow; int range = Math.Min(LastVisibleRow, RowCount - 1) - startRow + 1; Gdi.PrepDrawString(NormalFont, _foreColor); int xPadding = CellWidthPadding + 1 - HBar.Value; for (int i = 0, f = 0; f < range; i++, f++) // Vertical { f += lagFrames[i]; int LastVisible = LastVisibleColumnIndex; for (int j = FirstVisibleColumn; j <= LastVisible; j++) // Horizontal { RollColumn col = visibleColumns[j]; string text; int strOffsetX = 0; int strOffsetY = 0; Point point = new Point(col.Left.Value + xPadding, RowsToPixels(i) + CellHeightPadding); Bitmap image = null; int bitmapOffsetX = 0; int bitmapOffsetY = 0; if (QueryItemIcon != null) { QueryItemIcon(f + startRow, visibleColumns[j], ref image, ref bitmapOffsetX, ref bitmapOffsetY); } if (image != null) { Gdi.DrawBitmap(image, new Point(point.X + bitmapOffsetX, point.Y + bitmapOffsetY + CellHeightPadding), true); } QueryItemText(f + startRow, visibleColumns[j], out text, ref strOffsetX, ref strOffsetY); bool rePrep = false; if (SelectedItems.Contains(new Cell { Column = visibleColumns[j], RowIndex = f + startRow })) { Gdi.PrepDrawString(NormalFont, SystemColors.HighlightText); rePrep = true; } if (!string.IsNullOrWhiteSpace(text)) { Gdi.DrawString(text, new Point(point.X + strOffsetX, point.Y + strOffsetY)); } if (rePrep) { Gdi.PrepDrawString(NormalFont, _foreColor); } } } } } }
/// <summary> /// This will create a point list out of the data, which can be used to plot the data. In order to create this list, /// the function must have knowledge how to calculate the points out of the data. This will be done /// by a function provided by the calling function. /// </summary> /// <param name="layer">The plot layer.</param> /// <returns>An array of plot points in layer coordinates.</returns> public Processed2DPlotData GetRangesAndPoints( Gdi.IPlotArea layer) { const double MaxRelativeValue = 1E2; Altaxo.Data.IReadableColumn xColumn = this.XColumn; Altaxo.Data.IReadableColumn yColumn = this.YColumn; if(null==xColumn || null==yColumn) return null; // this plotitem is only for x and y double columns if(this.PlottablePoints<=0) return null; Processed2DPlotData result = new Processed2DPlotData(); MyPlotData myPlotData = new MyPlotData(xColumn, yColumn); result.XPhysicalAccessor = new IndexedPhysicalValueAccessor(myPlotData.GetXPhysical); result.YPhysicalAccessor = new IndexedPhysicalValueAccessor(myPlotData.GetYPhysical); PlotRangeList rangeList = null; PointF[] ptArray = null; // allocate an array PointF to hold the line points ptArray = new PointF[this.PlottablePoints]; result.PlotPointsInAbsoluteLayerCoordinates = ptArray; // Fill the array with values // only the points where x and y are not NaNs are plotted! int i,j; bool bInPlotSpace = true; int rangeStart=0; int rangeOffset=0; rangeList = new PlotRangeList(); result.RangeList = rangeList; Scale xAxis = layer.XAxis; Scale yAxis = layer.YAxis; Gdi.G2DCoordinateSystem coordsys = layer.CoordinateSystem; int len = this.PlotRangeEnd; for(i=this.PlotRangeStart,j=0;i<len;i++) { if(xColumn.IsElementEmpty(i) || yColumn.IsElementEmpty(i)) { if(!bInPlotSpace) { bInPlotSpace=true; rangeList.Add(new PlotRange(rangeStart,j,rangeOffset)); } continue; } double x_rel,y_rel; double xcoord, ycoord; x_rel = xAxis.PhysicalVariantToNormal(xColumn[i]); y_rel = yAxis.PhysicalVariantToNormal(yColumn[i]); // chop relative values to an range of about -+ 10^6 if(x_rel>MaxRelativeValue) x_rel = MaxRelativeValue; if(x_rel<-MaxRelativeValue) x_rel=-MaxRelativeValue; if(y_rel>MaxRelativeValue) y_rel = MaxRelativeValue; if(y_rel<-MaxRelativeValue) y_rel=-MaxRelativeValue; // after the conversion to relative coordinates it is possible // that with the choosen axis the point is undefined // (for instance negative values on a logarithmic axis) // in this case the returned value is NaN if(coordsys.LogicalToLayerCoordinates(new Logical3D(x_rel,y_rel), out xcoord, out ycoord)) { if(bInPlotSpace) { bInPlotSpace=false; rangeStart = j; rangeOffset = i-j; } ptArray[j].X = (float)xcoord; ptArray[j].Y = (float)ycoord; j++; } else { if(!bInPlotSpace) { bInPlotSpace=true; rangeList.Add(new PlotRange(rangeStart,j,rangeOffset)); } } } // end for if(!bInPlotSpace) { bInPlotSpace=true; rangeList.Add(new PlotRange(rangeStart,j,rangeOffset)); // add the last range } return result; }
private void DrawColumnBg(PaintEventArgs e, List <RollColumn> visibleColumns) { Gdi.SetBrush(SystemColors.ControlLight); Gdi.SetSolidPen(Color.Black); if (HorizontalOrientation) { Gdi.FillRectangle(0, 0, ColumnWidth + 1, DrawHeight + 1); Gdi.Line(0, 0, 0, visibleColumns.Count * CellHeight + 1); Gdi.Line(ColumnWidth, 0, ColumnWidth, visibleColumns.Count * CellHeight + 1); int start = -VBar.Value; foreach (var column in visibleColumns) { Gdi.Line(1, start, ColumnWidth, start); start += CellHeight; } if (visibleColumns.Any()) { Gdi.Line(1, start, ColumnWidth, start); } } else { int bottomEdge = RowsToPixels(0); // Gray column box and black line underneath Gdi.FillRectangle(0, 0, Width + 1, bottomEdge + 1); Gdi.Line(0, 0, TotalColWidth.Value + 1, 0); Gdi.Line(0, bottomEdge, TotalColWidth.Value + 1, bottomEdge); // Vertical black seperators for (int i = 0; i < visibleColumns.Count; i++) { int pos = visibleColumns[i].Left.Value - HBar.Value; Gdi.Line(pos, 0, pos, bottomEdge); } // Draw right most line if (visibleColumns.Any()) { int right = TotalColWidth.Value - HBar.Value; Gdi.Line(right, 0, right, bottomEdge); } } // Emphasis foreach (var column in visibleColumns.Where(c => c.Emphasis)) { Gdi.SetBrush(SystemColors.ActiveBorder); if (HorizontalOrientation) { Gdi.FillRectangle(1, visibleColumns.IndexOf(column) * CellHeight + 1, ColumnWidth - 1, ColumnHeight - 1); } else { Gdi.FillRectangle(column.Left.Value + 1 - HBar.Value, 1, column.Width.Value - 1, ColumnHeight - 1); } } // If the user is hovering over a column if (IsHoveringOnColumnCell) { if (HorizontalOrientation) { for (int i = 0; i < visibleColumns.Count; i++) { if (visibleColumns[i] != CurrentCell.Column) { continue; } if (CurrentCell.Column.Emphasis) { Gdi.SetBrush(Add(SystemColors.Highlight, 0x00222222)); } else { Gdi.SetBrush(SystemColors.Highlight); } Gdi.FillRectangle(1, i * CellHeight + 1, ColumnWidth - 1, ColumnHeight - 1); } } else { //TODO multiple selected columns for (int i = 0; i < visibleColumns.Count; i++) { if (visibleColumns[i] == CurrentCell.Column) { //Left of column is to the right of the viewable area or right of column is to the left of the viewable area if (visibleColumns[i].Left.Value - HBar.Value > Width || visibleColumns[i].Right.Value - HBar.Value < 0) { continue; } int left = visibleColumns[i].Left.Value - HBar.Value; int width = visibleColumns[i].Right.Value - HBar.Value - left; if (CurrentCell.Column.Emphasis) { Gdi.SetBrush(Add(SystemColors.Highlight, 0x00550000)); } else { Gdi.SetBrush(SystemColors.Highlight); } Gdi.FillRectangle(left + 1, 1, width - 1, ColumnHeight - 1); } } } } }
/// <summary> /// This will create a point list out of the data, which can be used to plot the data. In order to create this list, /// the function must have knowledge how to calculate the points out of the data. This will be done /// by a function provided by the calling function. /// </summary> /// <param name="layer">The plot layer.</param> /// <returns>An array of plot points in layer coordinates.</returns> public Processed2DPlotData GetRangesAndPoints( Gdi.IPlotArea layer) { const int functionPoints = 1000; const double MaxRelativeValue = 1E6; // allocate an array PointF to hold the line points PointF[] ptArray = new PointF[functionPoints]; Processed2DPlotData result = new Processed2DPlotData(); MyPlotData pdata = new MyPlotData(); result.PlotPointsInAbsoluteLayerCoordinates = ptArray; double[] xPhysArray = new double[functionPoints]; double[] yPhysArray = new double[functionPoints]; pdata._xPhysical = xPhysArray; pdata._yPhysical = yPhysArray; result.XPhysicalAccessor = new IndexedPhysicalValueAccessor(pdata.GetXPhysical); result.YPhysicalAccessor = new IndexedPhysicalValueAccessor(pdata.GetYPhysical); // double xorg = layer.XAxis.Org; // double xend = layer.XAxis.End; // Fill the array with values // only the points where x and y are not NaNs are plotted! int i, j; bool bInPlotSpace = true; int rangeStart = 0; PlotRangeList rangeList = new PlotRangeList(); result.RangeList = rangeList; Gdi.G2DCoordinateSystem coordsys = layer.CoordinateSystem; NumericalScale xaxis = layer.XAxis as NumericalScale; NumericalScale yaxis = layer.YAxis as NumericalScale; if (xaxis == null || yaxis == null) return null; for (i = 0, j = 0; i < functionPoints; i++) { double x_rel = ((double)i) / (functionPoints - 1); double x = xaxis.NormalToPhysical(x_rel); double y = Evaluate(x); if (Double.IsNaN(x) || Double.IsNaN(y)) { if (!bInPlotSpace) { bInPlotSpace = true; rangeList.Add(new PlotRange(rangeStart, j)); } continue; } // double x_rel = layer.XAxis.PhysicalToNormal(x); double y_rel = yaxis.PhysicalToNormal(y); // chop relative values to an range of about -+ 10^6 if (y_rel > MaxRelativeValue) y_rel = MaxRelativeValue; if (y_rel < -MaxRelativeValue) y_rel = -MaxRelativeValue; // after the conversion to relative coordinates it is possible // that with the choosen axis the point is undefined // (for instance negative values on a logarithmic axis) // in this case the returned value is NaN double xcoord, ycoord; if (coordsys.LogicalToLayerCoordinates(new Logical3D(x_rel, y_rel), out xcoord, out ycoord)) { if (bInPlotSpace) { bInPlotSpace = false; rangeStart = j; } xPhysArray[j] = x; yPhysArray[j] = y; ptArray[j].X = (float)xcoord; ptArray[j].Y = (float)ycoord; j++; } else { if (!bInPlotSpace) { bInPlotSpace = true; rangeList.Add(new PlotRange(rangeStart, j)); } } } // end for if (!bInPlotSpace) { bInPlotSpace = true; rangeList.Add(new PlotRange(rangeStart, j)); // add the last range } return result; }
protected abstract void DrawScreenOn(Gdi mem, Rectangle rect, int position);
internal PlotHlc(GdiEngine engine, object source, ChartSetting chartSetting) : base(engine, chartSetting) { __cGDI = engine.GDI; __cBars = source as Instrument; }
/// <summary> /// Internal copy from operation. It is presumed, that the events are already suspended. Additionally, /// it is not neccessary to call the OnChanged event, since this is called in the calling routine. /// </summary> /// <param name="obj">The object (layer) from which to copy.</param> /// <param name="options">Copy options.</param> protected override void InternalCopyFrom(HostLayer obj, Gdi.GraphCopyOptions options) { base.InternalCopyFrom(obj, options); // base copy, but keep in mind that InternalCopyGraphItems is overridden in this class var from = obj as XYZPlotLayer; if (null == from) return; if (0 != (options & Gdi.GraphCopyOptions.CopyLayerScales)) { this.CoordinateSystem = from.CoordinateSystem; // immutable this.Scales = (ScaleCollection)from._scales.Clone(); this._dataClipping = from._dataClipping; } if (0 != (options & Gdi.GraphCopyOptions.CopyLayerGrid)) { this.GridPlanes = from._gridPlanes.Clone(); } // Styles if (0 != (options & Gdi.GraphCopyOptions.CopyLayerAxes)) { this.AxisStyles = (AxisStyleCollection)from._axisStyles.Clone(); } // Plot items if (0 != (options & Gdi.GraphCopyOptions.CopyLayerPlotItems)) { this.PlotItems = null == from._plotItems ? null : new PlotItemCollection(this, from._plotItems, true); } else if (0 != (options & Gdi.GraphCopyOptions.CopyLayerPlotStyles)) { // TODO apply the styles from from._plotItems to the PlotItems here this.PlotItems.CopyFrom(from._plotItems, options); } }