/// <summary> /// /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { if (disposing) { PresentParams = null; } if (Direct3D != null) { Direct3D.Dispose(); Direct3D = null; } if (Sprite != null) { Sprite.Dispose(); Sprite = null; } if (Device != null) { Device.Dispose(); Device = null; } if (d3dFont != null) { d3dFont.Dispose(); d3dFont = null; } }
protected override void DrawText(Object dev, String text, String text2 = null, int alpha = 0) { Device device = (Device)dev; if (_font == null) { _font = new SlimDX.Direct3D9.Font(device, new System.Drawing.Font("Lucida Console", 10.0f)); } if (screenHeight == 0 | screenWidth == 0) { using (Surface backBuffer = device.GetBackBuffer(0, 0)) { screenWidth = backBuffer.Description.Width; screenHeight = backBuffer.Description.Height; } } _font.DrawString(null, text, new Rectangle(0, 0, screenWidth, screenHeight), DrawTextFormat.Top | DrawTextFormat.Right, System.Drawing.Color.Red); if (alpha > 0) { Color c = Color.FromArgb(alpha, System.Drawing.Color.Red); _font.DrawString(null, text2, new Rectangle(0, 15, screenWidth, screenHeight - 15), DrawTextFormat.Top | DrawTextFormat.Right, c); } }
public override Result Render() { Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); if (Device.BeginScene().IsSuccess&& MainWindow != null) { if (_hmRenderer != null) { _hmRenderer.Render(); } var rs = new[] { new Rectangle(10, 10, 0, 0), new Rectangle(10, 30, 0, 0), new Rectangle(10, 50, 0, 0), new Rectangle(10, 70, 0, 0) }; Font.DrawString(null, String.Format("Arrows: Move camera"), rs[0], DrawTextFormat.Left | DrawTextFormat.Top | DrawTextFormat.NoClip, Color.White); Font.DrawString(null, String.Format("WASD: Move selection"), rs[1], DrawTextFormat.Left | DrawTextFormat.Top | DrawTextFormat.NoClip, Color.White); Font.DrawString(null, String.Format("+/-: Raise/Lower terrain"), rs[2], DrawTextFormat.Left | DrawTextFormat.Top | DrawTextFormat.NoClip, Color.White); Font.DrawString(null, String.Format("Space: Smooth terrain"), rs[3], DrawTextFormat.Left | DrawTextFormat.Top | DrawTextFormat.NoClip, Color.White); Device.EndScene(); Device.Present(); } return(ResultCode.Success); }
protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing == true) { if (this.titleFont != null) { this.titleFont.Dispose(); this.titleFont = null; } if (this.labelFont != null) { this.labelFont.Dispose(); this.labelFont = null; } if (this.device != null && this.device.Disposed == false) { if (this.device.Direct3D != null) { this.device.Direct3D.Dispose(); } this.device.Dispose(); this.device = null; } } }
public void OnDeviceReset(object sender, EventArgs e) { _control = sender as DirectxControl; if (_control == null) { throw new ArgumentNullException(nameof(sender)); } _sprite?.Dispose(); _sprite = new Dx9.Sprite(_control.Device); _shipSprite?.Dispose(); _shipSprite = new Dx9.Sprite(_control.Device); if (_texture == null) { _texture = Dx9.Texture.FromFile(_control.Device, "Ressources\\maxresdefault.jpg", _control.Device.Viewport.Width, _control.Device.Viewport.Height, 0, Dx9.Usage.None, Dx9.Format.Unknown, Dx9.Pool.Default, Dx9.Filter.Default, Dx9.Filter.Default, 0, out _imageInformation); } if (_shipTexture == null) { _shipTexture = Dx9.Texture.FromFile(_control.Device, "Ressources\\Voyager.png", 200, 200, 0, Dx9.Usage.None, Dx9.Format.Unknown, Dx9.Pool.Default, Dx9.Filter.Default, Dx9.Filter.Default, 0); } if (_circleTexture == null) { _circleTexture = Dx9.Texture.FromFile(_control.Device, "Ressources\\200px-65537-gon.svg.png", 20, 20, 0, Dx9.Usage.None, Dx9.Format.Unknown, Dx9.Pool.Default, Dx9.Filter.Default, Dx9.Filter.Default, 0); } if (_font == null) { SD.Font f = new SD.Font("Arial", 20f, SD.FontStyle.Regular); _font = new Dx9.Font(_control.Device, f); } }
public override Result Init(int width, int height, bool windowed) { CreateWindow(width, height); Device = CreateDevice(width, height, windowed); if (Device == null) { return(ResultCode.Failure); } Font = new Font(Device, 18, 0, FontWeight.Bold, 1, false, CharacterSet.Default, Precision.Default, FontQuality.Default, PitchAndFamily.Default | PitchAndFamily.DontCare, "Arial"); _heightmap = new HeightMap(Device, new Point(100, 100), 15.0f); if (_heightmap.CreateRandomHeightMap(MathF.Rand(2000), _size / 10.0f, _amplitude / 10.0f, 9).IsFailure) { Debug.Print("Failed to create random heightmap"); Quit(); } _hmRenderer = new HeightMapRenderer(_heightmap, Device); if (_hmRenderer.CreateParticles().IsFailure) { Debug.Print("Failed to create particles"); Quit(); } IsRunning = true; return(ResultCode.Success); }
public void Dispose() { isInitialized = false; if ((renderControl != null) && !renderControl.IsDisposed) { UnregisterControlEvents(); renderControl = null; } if (swapChain != null) { swapChain.Dispose(); swapChain = null; } if (TextFont != null) { TextFont.Dispose(); TextFont = null; } if (CursorMesh != null) { CursorMesh.Dispose(); CursorMesh = null; } if (Device != null) { Device.Direct3D.Dispose(); Device.Dispose(); Device = null; } }
public FpsDisplay(Device device) { fontSprite = new Sprite(device); font = new SlimDX.Direct3D9.Font(device, 20, 0, FontWeight.Normal, 0, false, CharacterSet.Default, Precision.Default, FontQuality.ClearTypeNatural, PitchAndFamily.DontCare, "tahoma"); }
public Vec2 MeasureString(string text, int height, DrawTextFormat format) { SlimDX.Direct3D9.Font font = this.GetFont(height); Rectangle rectangle = font.MeasureString(this.textSprite, text, format); return(new Vec2(rectangle.Width, rectangle.Height)); }
public override Result Init(int width, int height, bool windowed) { CreateWindow(width, height); Device = CreateDevice(width, height, windowed); if (Device == null) return ResultCode.Failure; Font = new Font(Device, 18, 0, FontWeight.Bold, 1, false, CharacterSet.Default, Precision.Default, FontQuality.Default, PitchAndFamily.Default | PitchAndFamily.DontCare, "Arial"); _heightmap = new HeightMap(Device, new Point(100, 100), 15.0f); if (_heightmap.LoadFromFile("images/abe.jpg").IsFailure) { Debug.Print("failed to load from file"); Quit(); } _hmRenderer = new HeightMapRenderer(_heightmap, Device); if (_hmRenderer.CreateParticles().IsFailure) { Debug.Print("Failed to create particles"); Quit(); } IsRunning = true; return ResultCode.Success; }
private SlimDX.Direct3D9.Font CreateFont(Device dev, int slice) { var name = FFontInput[slice].Name; var size = FSizeInput[slice]; var italic = FItalicInput[slice]; var weight = FBoldInput[slice] ? FontWeight.Bold : FontWeight.Light; var quality = FQuality[slice]; var id = GetFontKey(dev, name, size, italic, weight, quality); SlimDX.Direct3D9.Font font; if (!FFonts.TryGetValue(id, out font)) { font = new SlimDX.Direct3D9.Font( dev, size, 0, weight, 0, italic, CharacterSet.Default, Precision.Default, //id.Precision, quality, PitchAndFamily.Default, name); font.PreloadCharacters(FPreloadMin[slice], FPreloadMax[slice]); FFonts.Add(id, font); } if (FFontCaching[slice]) { font.Tag = dev; } else { font.Tag = null; // Will be removed by next Evaluate } return(font); }
public override void AllocateResources() { DisplayFont = new SlimDX.Direct3D9.Font(Panel.MainPlot.Device, new System.Drawing.Font("Lucida Console", 16)); DisplayFont.MeasureString(null, "X", DrawTextFormat.Center, ref FontSizeRect); PositionUpdated = true; }
/// <summary> /// Allocates DirectX resources and attaches to render events. /// </summary> private void EnableStats() { Log("Try get Device"); _device = SkinContext.Device; if (_device == null) { return; } _swapChain = _device.GetSwapChain(0); _swapChainEx = new SwapChainEx(_swapChain); _line = new Line(_device) { Width = 2.5f, Antialias = true }; _fontSprite = new Sprite(_device); _font = new Font(_device, TEXT_SIZE, 0, FontWeight.Normal, 0, false, CharacterSet.Default, Precision.Default, FontQuality.ClearTypeNatural, PitchAndFamily.DontCare, "tahoma"); // Get device info _adapterDisplayModeEx = SkinContext.Direct3D.GetAdapterDisplayModeEx(0); Log("Screen height {0} at refresh rate {1} Hz", _adapterDisplayModeEx.Height, _adapterDisplayModeEx.RefreshRate); Log("Attach render events"); SkinContext.DeviceSceneBegin += BeginScene; SkinContext.DeviceSceneEnd += EndScene; _statsEnabled = true; }
public override Result Init(int width, int height, bool windowed) { CreateWindow(width, height); Device = CreateDevice(width, height, windowed); if (Device == null) { return(ResultCode.Failure); } Font = new Font(Device, 18, 0, FontWeight.Bold, 1, false, CharacterSet.Default, Precision.Default, FontQuality.Default, PitchAndFamily.Default | PitchAndFamily.DontCare, "Arial"); _heightmap = new HeightMap(Device, new Point(100, 100), 15.0f); if (_heightmap.LoadFromFile("images/abe.jpg").IsFailure) { Debug.Print("failed to load from file"); Quit(); } _hmRenderer = new HeightMapRenderer(_heightmap, Device); if (_hmRenderer.CreateParticles().IsFailure) { Debug.Print("Failed to create particles"); Quit(); } IsRunning = true; return(ResultCode.Success); }
public override Result Init(int width, int height, bool windowed) { CreateWindow(width, height); Device = CreateDevice(width, height, windowed); if (Device == null) return ResultCode.Failure; Font = new Font(Device, 18, 0, FontWeight.Bold, 1, false, CharacterSet.Default, Precision.Default, FontQuality.Default, PitchAndFamily.Default | PitchAndFamily.DontCare, "Arial"); _heightmap = new HeightMap(Device, new Point(50, 50), 15.0f); _hmRenderer = new HeightMapRenderer(_heightmap, Device) { ShowSelection = true }; _heightmap.Renderer = _hmRenderer; _editor = new HeightMapEditorSelection(_heightmap, _hmRenderer); _hmRenderer.Editor = _editor; if (_hmRenderer.CreateParticles().IsFailure) { Debug.Print("Failed to create particles"); Quit(); } IsRunning = true; return ResultCode.Success; }
void DrawRectangle(float x, float y, float w, int h, Line MenuLine, SlimDX.Direct3D9.Font MenuFont, Color4 MenuLineColor) { try { SlimDX.Vector2[] vLine1 = new SlimDX.Vector2[2]; SlimDX.Vector2[] vLine2 = new SlimDX.Vector2[2]; SlimDX.Vector2[] vLine3 = new SlimDX.Vector2[2]; SlimDX.Vector2[] vLine4 = new SlimDX.Vector2[2]; vLine1[0] = new Vector2(); vLine1[1] = new Vector2(); vLine2[0] = new Vector2(); vLine2[1] = new Vector2(); vLine3[0] = new Vector2(); vLine3[1] = new Vector2(); vLine4[0] = new Vector2(); vLine4[1] = new Vector2(); vLine1[0].X = x; vLine1[0].Y = y; vLine1[1].X = x; vLine1[1].Y = y + h; vLine2[0].X = x + w; vLine2[0].Y = y; vLine2[1].X = x + w; vLine2[1].Y = y + h; vLine3[0].X = x; vLine3[0].Y = y; vLine3[1].X = x + w; vLine3[1].Y = y; vLine4[0].X = x; vLine4[0].Y = y + h; vLine4[1].X = x + w; vLine4[1].Y = y + h; if (MenuLine != null) { MenuLine.Width = 2; MenuLine.Antialias = false; MenuLine.GLLines = false; MenuLine.Begin(); MenuLine.Draw(vLine1, MenuLineColor); MenuLine.Draw(vLine2, MenuLineColor); MenuLine.Draw(vLine3, MenuLineColor); MenuLine.Draw(vLine4, MenuLineColor); MenuLine.End(); } } catch (Exception ExtInfo) { Interface.ReportException(ExtInfo); return; } }
private void Form_Load(object sender, EventArgs e) { Form form = (Form)sender; System.Diagnostics.Debug.Assert(Direct3D == null); Direct3D = new Direct3D(); int nAdapter = Direct3D.Adapters[0].Adapter; Capabilities devCaps = Direct3D.GetDeviceCaps(nAdapter, DeviceType.Hardware); // the flags for our Direct3D device. Use software rendering by // default CreateFlags devFlags = CreateFlags.SoftwareVertexProcessing; // use hardware vertex processing if supported if ((devCaps.DeviceCaps & DeviceCaps.HWTransformAndLight) == DeviceCaps.HWTransformAndLight) { devFlags = CreateFlags.HardwareVertexProcessing; } // use pure device (whatever that is) if supported if ((devCaps.DeviceCaps & DeviceCaps.PureDevice) == DeviceCaps.PureDevice) { devFlags |= CreateFlags.PureDevice; } DisplayMode displayMode = Direct3D.GetAdapterDisplayMode(nAdapter); System.Diagnostics.Debug.Assert(PresentParams == null); PresentParams = new PresentParameters(); PresentParams.BackBufferWidth = form.ClientSize.Width; PresentParams.BackBufferHeight = form.ClientSize.Height; PresentParams.BackBufferFormat = displayMode.Format; PresentParams.BackBufferCount = 1; PresentParams.Windowed = true; PresentParams.SwapEffect = SwapEffect.Discard; PresentParams.AutoDepthStencilFormat = Format.D16; PresentParams.EnableAutoDepthStencil = true; PresentParams.DeviceWindowHandle = form.Handle; System.Diagnostics.Debug.Assert(Device == null); // create the Direct3D device Device = new SDXDevice(new Device(Direct3D, nAdapter, DeviceType.Hardware, form.Handle, devFlags, PresentParams), Form.ClientSize.Width / 640.0f, Form.ClientSize.Height / 480.0f); ResetDevice(); using (System.Drawing.Font baseFont = new System.Drawing.Font("Arial Black", 18, FontStyle.Bold)) { System.Diagnostics.Debug.Assert(d3dFont == null); d3dFont = new Font(Device, baseFont); } Application.Idle += OnApplicationIdle; }
public Font(int height, int width, string font) { _font = new SlimDX.Direct3D9.Font(Rendering.Device, height, width, FontWeight.Normal, 1, false, CharacterSet.Default, Precision.Default, FontQuality.Antialiased, PitchAndFamily.Default, font); Rendering.RegisterResource(this); }
public void Dispose() { font.Dispose(); sprite.Dispose(); font = null; GC.SuppressFinalize(this); }
public Font(string familyName) { mBaseFont = new SlimDX.Direct3D9.Font(Game.GameManager.GraphicsThread.GraphicsManager.Device, 30, 0, FontWeight.SemiBold, 1, false, CharacterSet.Ansi, Precision.TrueTypeOnly, FontQuality.Antialiased, PitchAndFamily.Default, familyName); Game.GameManager.GraphicsThread.GraphicsManager.VideoResourceMgr.AddVideoResource(new Video.VideoResource(mBaseFont.OnLostDevice, mBaseFont.OnResetDevice)); }
public override void ReleaseResources() { if (DisplayFont != null) { DisplayFont.Dispose(); } DisplayFont = null; }
public override void AllocateResources() { if (MainPlot != null) { DisplayFontNormal = new SlimDX.Direct3D9.Font(MainPlot.Device, new System.Drawing.Font("Lucida Console", 7)); } base.AllocateResources(); }
public MyRenderer() { _texture = null; _font = null; _shipVector3 = new Vector3(0, 0, 0); _mapVector3 = new Vector3(0, 0, 100); _mousePosition = new Vector3(0, 0, 0); _rotation = 0f; }
private void SetManagedDevice(IntPtr unmanagedDevice) { // Start by freeing everything FreeResources(); // Create a managed Device from the unmanaged pointer // The constructor don't call IUnknown.AddRef but the "destructor" seem to call IUnknown.Release // Direct3D seem to be happier with that according to the DirectX log Marshal.AddRef(unmanagedDevice); this.unmanagedDevice = unmanagedDevice; device = Device.FromPointer(unmanagedDevice); //text sprite = new Sprite(device); _gdiMouseFixtionFont = new System.Drawing.Font("Tahoma", 30); _d3dMouseFixtionFont = new Direct3D.Font(device, _gdiMouseFixtionFont); _gdiGazeFixtionFont = new System.Drawing.Font("Tahoma", 30); _d3dGazeFixtionFont = new Direct3D.Font(device, _gdiGazeFixtionFont); //mouse _d3dMouseTrackLine = new Direct3D.Line(device); _d3dMouseTrackLine.Width = _mouseTrackLineWidth; _d3dMouseCursorCircleLine = new Direct3D.Line(device); _d3dMouseCursorCircleLine.Width = _mouseCursorCircleLineWidth; _d3dMouseFixationLine = new Direct3D.Line(device); _d3dMouseFixationLine.Width = _mouseFixationLineWidth; _d3dMouseScanpathLine = new Direct3D.Line(device); _d3dMouseScanpathLine.Width = _mouseScanpathLineWidth; //gaze _d3dGazeTrackLine = new Direct3D.Line(device); _d3dGazeTrackLine.Width = _gazeTrackLineWidth; _d3dGazeCursorCircleLine = new Direct3D.Line(device); _d3dGazeCursorCircleLine.Width = _gazeCursorCircleLineWidth; _d3dGazeFixationLine = new Direct3D.Line(device); _d3dGazeFixationLine.Width = _gazeFixationLineWidth; _d3dGazeScanpathLine = new Direct3D.Line(device); _d3dGazeScanpathLine.Width = _gazeScanpathLineWidth; // Load a png file to the teature _mouseCursorTex = Texture.FromFile(device, @"..\..\..\Resource\Picture\cursor1.png"); SurfaceDescription spiderDesc = _mouseCursorTex.GetLevelDescription(0); _mouseCursorSize = new Size(spiderDesc.Width, spiderDesc.Height); _gazeCursorTex = Texture.FromFile(device, @"..\..\..\Resource\Picture\eyecursor.png"); spiderDesc = _gazeCursorTex.GetLevelDescription(0); _gazeCursorSize = new Size(spiderDesc.Width, spiderDesc.Height); }
public Vec2 AddTextWithHeight(Vec2 pos, string text, Color color, int height, DrawTextFormat format) { SlimDX.Direct3D9.Font font = this.GetFont(height); Rectangle rectangle = font.MeasureString(this.textSprite, text, format); rectangle.X += pos.X; rectangle.Y += pos.Y; font.DrawString(this.textSprite, text, rectangle, format, color); return(new Vec2(rectangle.Width, rectangle.Height)); }
public override void ReleaseResources() { if (DisplayFontNormal != null) { DisplayFontNormal.Dispose(); } DisplayFontNormal = null; base.ReleaseResources(); }
public Font(string font, int size) { //_font = new SlimDX.Direct3D9.Font(Rendering.Device, height, width, FontWeight.Normal, 1, false, // CharacterSet.Default, Precision.Default, FontQuality.Antialiased, // PitchAndFamily.Default, font); _font = new SlimDX.Direct3D9.Font(Rendering.Device, new System.Drawing.Font(font, size)); Rendering.RegisterResource(this); }
public static void x() { using (SlimDX.Direct3D9.Font font = new SlimDX.Direct3D9.Font(device, new System.Drawing.Font("Times New Roman", 16.0f))) { if (_lastFrame != null) { font.DrawString(null, String.Format("{0:N1} fps", (1000.0 / (DateTime.Now - _lastFrame.Value).TotalMilliseconds)), 100, 100, System.Drawing.Color.Red); } _lastFrame = DateTime.Now; } }
public Render(D3D.Device device, int shiftX = 0, int shiftY = 0) { this.device = device; this.shiftX = shiftX; this.shiftY = shiftY; line = new D3D.Line(device); fonts = new D3D.Font[3]; fonts[0] = new D3D.Font(device, new Font("Dotum", 8, FontStyle.Regular)); fonts[1] = new D3D.Font(device, new Font("Calibri", 8, FontStyle.Regular)); fonts[2] = new D3D.Font(device, new Font("Tahoma", 9, FontStyle.Regular)); }
private SlimDX.Direct3D9.Font GetFont(int size) { if (this.fonts.ContainsKey(size)) { return(this.fonts[size]); } System.Drawing.Font font = new System.Drawing.Font("Verdana", (float)size); SlimDX.Direct3D9.Font font2 = new SlimDX.Direct3D9.Font(this.Dx, font); this.fonts.Add(size, font2); return(font2); }
public Renderer(Control control) { PresentParameters presentParams = new PresentParameters(); presentParams.Windowed = true; presentParams.BackBufferCount = 0; presentParams.BackBufferWidth = Screen.PrimaryScreen.WorkingArea.Width; presentParams.BackBufferHeight = Screen.PrimaryScreen.WorkingArea.Height; Device = new Device(new Direct3D(), 0, DeviceType.Hardware, control.Handle, CreateFlags.SoftwareVertexProcessing, presentParams); if ((Device.Capabilities.VertexProcessingCaps & VertexProcessingCaps.Tweening) == 0) { Report.ReportLog("Vertex tweening is not supported!"); } camera = new Camera(control); RenderControl = control; Device.SetRenderState(RenderState.Lighting, true); Device.SetRenderState(RenderState.DiffuseMaterialSource, ColorSource.Material); Device.SetRenderState(RenderState.EmissiveMaterialSource, ColorSource.Material); Device.SetRenderState(RenderState.SpecularMaterialSource, ColorSource.Material); Device.SetRenderState(RenderState.SpecularEnable, true); Device.SetRenderState(RenderState.AlphaBlendEnable, true); Device.SetRenderState(RenderState.BlendOperationAlpha, BlendOperation.Add); Device.SetRenderState(RenderState.SourceBlend, Blend.SourceAlpha); Device.SetRenderState(RenderState.DestinationBlend, Blend.InverseSourceAlpha); Light light = new Light(); light.Type = LightType.Directional; light.Ambient = new Color4(int.Parse((string)Gui.Config["LightAmbientARGB"], System.Globalization.NumberStyles.AllowHexSpecifier)); light.Diffuse = new Color4(int.Parse((string)Gui.Config["LightDiffuseARGB"], System.Globalization.NumberStyles.AllowHexSpecifier)); light.Specular = new Color4(int.Parse((string)Gui.Config["LightSpecularARGB"], System.Globalization.NumberStyles.AllowHexSpecifier)); Device.SetLight(0, light); Device.EnableLight(0, true); TextFont = new SlimDX.Direct3D9.Font(Device, new System.Drawing.Font("Arial", 8)); TextColor = new Color4(Color.White); CursorMesh = Mesh.CreateSphere(Device, 1, 10, 10); CursorMaterial = new Material(); CursorMaterial.Ambient = new Color4(1, 1f, 1f, 1f); CursorMaterial.Diffuse = new Color4(1, 0.6f, 1, 0.3f); showNormals = (bool)Gui.Config["ShowNormals"]; showBones = (bool)Gui.Config["ShowBones"]; wireframe = (bool)Gui.Config["Wireframe"]; culling = (bool)Gui.Config["Culling"]; Background = Color.FromArgb(255, 10, 10, 60); isInitialized = true; Render(); }
public static void Initialize(IntPtr devicePointer) { if (_usedDevicePointer != devicePointer) { //Debug.WriteLine("Rendering: Device initialized on " + devicePointer); Device = Device.FromPointer(devicePointer); _usedDevicePointer = devicePointer; DrawingFont = new SlimDX.Direct3D9.Font(Device, new System.Drawing.Font(FontFamily.GenericSansSerif, 14)); } Camera.Initialize(); }
private void CreateFont() { if (font != null) { font.Dispose(); } dirty = false; font = new Font(device, FontSize, 0, FontWeight, 0, false, CharacterSet.Default, Precision.TrueType, FontQuality.ClearTypeNatural, PitchAndFamily.Default | PitchAndFamily.DontCare, FontName); }
/// <summary> /// Loads another font into memory. /// </summary> /// <param name="name">The new font's name.</param> /// <param name="size">The new font's size.</param> public void ChangeFont(String name, int size) { if (_font != null) { _font.Dispose(); } _name = name; _size = size; System.Drawing.Font backingFont = new System.Drawing.Font(name, size); _font = new Font(_device, backingFont); }
public override Result Init(int width, int height, bool windowed) { CreateWindow(width, height); Device = CreateDevice(width, height, windowed); if (Device == null) return ResultCode.Failure; Font = new Font(Device, 48, 0, FontWeight.Bold, 1, false, CharacterSet.Default, Precision.Default, FontQuality.Default, PitchAndFamily.Default | PitchAndFamily.DontCare, "Arial"); IsRunning = true; return ResultCode.Success; }
public override Result Init(int width, int height, bool windowed) { CreateWindow(width, height); Device = CreateDevice(width, height, windowed); if (Device == null) return ResultCode.Failure; Font = new Font(Device, 18, 0, FontWeight.Bold, 1, false, CharacterSet.Default, Precision.Default, FontQuality.Default, PitchAndFamily.Default | PitchAndFamily.DontCare, "Arial"); _heightmap = new HeightMap(Device, new Point(100, 100), 15.0f); if (_heightmap.CreateRandomHeightMap(MathF.Rand(2000), _size / 10.0f, _amplitude / 10.0f, 9).IsFailure) { Debug.Print("Failed to create random heightmap"); Quit(); } _hmRenderer = new HeightMapRenderer(_heightmap, Device); if (_hmRenderer.CreateParticles().IsFailure) { Debug.Print("Failed to create particles"); Quit(); } IsRunning = true; return ResultCode.Success; }
private void Init_Resources() { resources_created = true; System.Drawing.Font theFont = new System.Drawing.Font("Arial", 10f, FontStyle.Regular, GraphicsUnit.Pixel); dxFont = new SlimDX.Direct3D9.Font(dxDevice, theFont); dxTextSprite = new Sprite(dxDevice); dxLine = new Line(dxDevice); LastTextureLoad = System.DateTime.Now.AddMilliseconds(500); LoadTextures = true; }
public void Release() { _font.Dispose(); _font = null; }
/// <summary> /// Sets the render states and draws the selected objects to scene. /// </summary> /// <param name="direct3DDevice">The direct 3D device pointer.</param> /// <returns><see cref="int"/></returns> public int EndSceneHook(IntPtr direct3DDevice) { // Do the first scan. if (!_opened) { _memory.OpenSF4Process(); _memory.RunScan(); _interface.WriteConsole("Street Fighter 4 Process hooked."); _opened = true; } if (_device == null) { _device = Device.FromPointer(direct3DDevice); _interface.WriteConsole(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\uiBackground.png"); _background = Texture.FromFile( _device, Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Resources\Images\uiBackground.png"); _interface.WriteConsole("Device created."); // Attempting to scale the font. _fontSize = _device.Viewport.Height / 48; _interface.WriteConsole(string.Format("Font size set to {0}", _fontSize)); _font = new Font(_device, new System.Drawing.Font("Consolas", _fontSize)); } // The game calls endscene twice a frame. We only need to draw once. // We should just return as normal the other time. if (_endsceneSkip) { _endsceneSkip = false; return _device.EndScene().Code; } _endsceneSkip = true; //// _device.SetRenderState(RenderState.Lighting, false); //// _device.SetRenderState(RenderState.SpecularEnable, false); _device.SetRenderState(RenderState.CullMode, Cull.None); _device.SetRenderState(RenderState.AlphaBlendEnable, true); _device.SetRenderState(RenderState.VertexBlend, VertexBlend.Disable); _device.SetRenderState(RenderState.SourceBlend, Blend.SourceAlpha); _device.SetRenderState(RenderState.DestinationBlend, Blend.InverseSourceAlpha); _device.SetRenderState(RenderState.BlendOperationAlpha, BlendOperation.Minimum); _device.SetRenderState(RenderState.FillMode, FillMode.Solid); _device.SetRenderState(RenderState.ColorWriteEnable, 0xF); _device.SetRenderState(RenderState.MultisampleAntialias, false); // Setting up the camera Vector3 eye = new Vector3 { X = _memory.GetCamX(), Y = _memory.GetCamY(), Z = _memory.GetCamZ() }; Vector3 target = new Vector3 { X = _memory.GetCamXp(), Y = _memory.GetCamYp(), Z = _memory.GetCamZp() }; float zoom = _memory.GetCamZoom(); _device.SetRenderState(RenderState.Lighting, false); // We don't need light for this... _device.SetTransform(TransformState.View, Matrix.LookAtLH(eye, target, new Vector3(0, 1, 0))); // Fix this shit later! _device.SetTransform( TransformState.Projection, Matrix.PerspectiveLH(0.1f * 16 / 9 * zoom + 0.008f, 0.1f * zoom + 0.008f, 0.1F, 100.0F)); _playerOneBoxes = _memory.ReadMemoryByteArrayWithBase(0x00688E6C, new int[] { 0x8, 0x2190 }, 25248); _playerTwoBoxes = _memory.ReadMemoryByteArrayWithBase(0x00688E6C, new int[] { 0xC, 0x2190 }, 25248); // Draw everything... if (_interface.DrawBasic1) { DrawHurtBoxes(_playerOneBoxes, _device); } if (_interface.DrawBasic2) { DrawHurtBoxes(_playerTwoBoxes, _device); } if (_interface.DrawPhysics1) { DrawPhysicsBoxes(_playerOneBoxes, _device); } if (_interface.DrawPhysics2) { DrawPhysicsBoxes(_playerTwoBoxes, _device); } if (_interface.DrawGrab1) { DrawThrowVulnerableBoxes(_playerOneBoxes, _device); } if (_interface.DrawGrab2) { DrawThrowVulnerableBoxes(_playerTwoBoxes, _device); } if (_interface.DrawHit1) { DrawHitbox(1, _device); } if (_interface.DrawHit2) { DrawHitbox(2, _device); } if (_interface.DrawGrab1) { DrawGrabBox(1, _device); } if (_interface.DrawGrab2) { DrawGrabBox(2, _device); } if (_interface.DrawProjectile1) { DrawProjectileBox(1, _device); } if (_interface.DrawProjectile2) { DrawProjectileBox(2, _device); } if (_interface.DrawProx1) { DrawProxBox(1, _device); } if (_interface.DrawProx2) { DrawProxBox(2, _device); } if (_interface.DrawInfo) { DrawInfo(_device); } _interface.FrameNumber = _memory.GetFrameCount(); // This does not use the sprite we use for all the other text... _font.DrawString(null, "Frame Trapped Lab Active", 20, 20, _textColor); return _device.EndScene().Code; }
public Renderer(Control control) { PresentParameters presentParams = new PresentParameters(); presentParams.Windowed = true; presentParams.BackBufferCount = 0; presentParams.BackBufferWidth = Screen.PrimaryScreen.WorkingArea.Width; presentParams.BackBufferHeight = Screen.PrimaryScreen.WorkingArea.Height; Device = new Device(new Direct3D(), 0, DeviceType.Hardware, control.Handle, CreateFlags.SoftwareVertexProcessing, presentParams); if ((Device.Capabilities.VertexProcessingCaps & VertexProcessingCaps.Tweening) == 0) { Report.ReportLog("Vertex tweening is not supported!"); } Device.SetRenderState(RenderState.Lighting, true); Device.SetRenderState(RenderState.DiffuseMaterialSource, ColorSource.Material); Device.SetRenderState(RenderState.EmissiveMaterialSource, ColorSource.Material); Device.SetRenderState(RenderState.SpecularMaterialSource, ColorSource.Material); Device.SetRenderState(RenderState.SpecularEnable, true); Device.SetRenderState(RenderState.AlphaBlendEnable, true); Device.SetRenderState(RenderState.BlendOperationAlpha, BlendOperation.Add); Device.SetRenderState(RenderState.SourceBlend, Blend.SourceAlpha); Device.SetRenderState(RenderState.DestinationBlend, Blend.InverseSourceAlpha); Device.SetSamplerState(0, SamplerState.MaxAnisotropy, 4); Device.SetSamplerState(0, SamplerState.MagFilter, TextureFilter.Anisotropic); Device.SetSamplerState(0, SamplerState.MinFilter, TextureFilter.Anisotropic); Device.SetSamplerState(0, SamplerState.MipFilter, TextureFilter.Linear); Light light = new Light(); light.Type = LightType.Directional; light.Ambient = new Color4(int.Parse((string)Gui.Config["LightAmbientARGB"], System.Globalization.NumberStyles.AllowHexSpecifier)); light.Diffuse = new Color4(int.Parse((string)Gui.Config["LightDiffuseARGB"], System.Globalization.NumberStyles.AllowHexSpecifier)); light.Specular = new Color4(int.Parse((string)Gui.Config["LightSpecularARGB"], System.Globalization.NumberStyles.AllowHexSpecifier)); Device.SetLight(0, light); Device.EnableLight(0, true); TextFont = new SlimDX.Direct3D9.Font(Device, new System.Drawing.Font("Arial", 8)); TextColor = new Color4(Color.White); CursorMesh = Mesh.CreateSphere(Device, 1, 10, 10); CursorMaterial = new Material(); CursorMaterial.Ambient = new Color4(1, 1f, 1f, 1f); CursorMaterial.Diffuse = new Color4(1, 0.6f, 1, 0.3f); showNormals = (bool)Gui.Config["ShowNormals"]; showBones = (bool)Gui.Config["ShowBones"]; string[] mode = Enum.GetNames(typeof(ShowBoneWeights)); for (int i = 0; i < mode.Length; i++) { if (mode[i] == (string)Gui.Config["ShowBoneWeights"]) { showBoneWeights = (ShowBoneWeights)i; break; } } wireframe = (bool)Gui.Config["Wireframe"]; culling = (bool)Gui.Config["Culling"]; Background = Color.FromArgb(int.Parse((string)Gui.Config["RendererBackgroundARGB"], System.Globalization.NumberStyles.AllowHexSpecifier)); isInitialized = true; camera = new Camera(control); RenderControl = control; }
private void InitDevice() { // Use D3DEx for Vista/Win7+ _is3D9Ex = false; if (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major >= 6) { _is3D9Ex = true; } DeviceType devType = DeviceType.Hardware; int adapterOrdinal = 0; Direct3D d3d = null; Direct3DEx d3dex = null; if (_is3D9Ex) { try { // Create Ex, fallback if it fails d3dex = new Direct3DEx(); } catch { d3d = new Direct3D(); _is3D9Ex = false; } } else d3d = new Direct3D(); // Look for PerfHUD AdapterCollection adapters = (_is3D9Ex ? d3dex : d3d).Adapters; foreach (AdapterInformation adap in adapters) { if (adap.Details.Description.Contains("PerfH")) { adapterOrdinal = adap.Adapter; devType = DeviceType.Reference; } } foreach (var item in adapters[adapterOrdinal].GetDisplayModes(Format.X8R8G8B8)) { string val = item.Width + "x" + item.Height; bool found = false; for (int i = 0; i < ValidResolutions.Count; i++) { if (ValidResolutions[i].Equals(val)) { found = true; break; } } if(!found) ValidResolutions.Add(val); } // Get resolution Size res = GetResolution(); RenderSize = res; form.ClientSize = res; // Set present parameters _pp = new PresentParameters(); _pp.Windowed = r_fs.Integer==0?true:false; _pp.SwapEffect = SwapEffect.Discard; _pp.EnableAutoDepthStencil = true; _pp.AutoDepthStencilFormat = Format.D24S8; _pp.PresentationInterval = (r_vsync.Integer==1? PresentInterval.One: PresentInterval.Immediate); _pp.Multisample = MultiSampling; _pp.BackBufferWidth = RenderSize.Width; _pp.BackBufferHeight = RenderSize.Height; _pp.BackBufferFormat = Format.X8R8G8B8; _pp.DeviceWindowHandle = form.Handle; // Handle Capabilities Capabilities caps = adapters[adapterOrdinal].GetCaps(devType); CreateFlags createFlags = CreateFlags.SoftwareVertexProcessing; // Got hardare vertex? if ((caps.DeviceCaps & DeviceCaps.HWTransformAndLight) == DeviceCaps.HWTransformAndLight) { createFlags = CreateFlags.HardwareVertexProcessing; // Support pure device? if ((caps.DeviceCaps & DeviceCaps.PureDevice) == DeviceCaps.PureDevice) createFlags |= CreateFlags.PureDevice; } createFlags |= CreateFlags.FpuPreserve; // Create d3d device + behemoth fallback try { if (_is3D9Ex) { if (r_fs.Bool) { DisplayModeEx dsp = new DisplayModeEx(); dsp.Width = _pp.BackBufferWidth; dsp.Height = _pp.BackBufferHeight; dsp.Format = _pp.BackBufferFormat; dsp.RefreshRate = 60; _pp.FullScreenRefreshRateInHertz = 60; //DisplayModeEx dispMode = d3dex.GetAdapterDisplayModeEx(adapterOrdinal); //RenderSize = new Size(dispMode.Width, dispMode.Height); //form.ClientSize = new Size(dispMode.Width, dispMode.Height); //_pp.BackBufferFormat = dispMode.Format; //_pp.BackBufferWidth = dispMode.Width; //_pp.BackBufferHeight = dispMode.Height; //_pp.FullScreenRefreshRateInHertz = dispMode.RefreshRate; device = new DeviceEx(d3dex, adapterOrdinal, devType, form.Handle, createFlags, _pp, dsp); } else device = new DeviceEx(d3dex, adapterOrdinal, devType, form.Handle, createFlags, _pp); } else device = new Device(d3d, adapterOrdinal, devType, form.Handle, createFlags, _pp); } catch (Direct3D9Exception ex) { if (ex.ResultCode == ResultCode.NotAvailable) { // Try again with different settings RenderSize = new Size(800, 600); form.ClientSize = new Size(800, 600); _pp.BackBufferWidth = 800; _pp.BackBufferHeight = 600; _pp.BackBufferCount = 1; _pp.SwapEffect = SwapEffect.Discard; createFlags &= ~(CreateFlags.PureDevice | CreateFlags.HardwareVertexProcessing); createFlags |= CreateFlags.SoftwareVertexProcessing; try { if (_is3D9Ex) { if (r_fs.Bool) { DisplayModeEx dispMode = d3dex.GetAdapterDisplayModeEx(adapterOrdinal); RenderSize = new Size(dispMode.Width, dispMode.Height); form.ClientSize = new Size(dispMode.Width, dispMode.Height); _pp.BackBufferFormat = dispMode.Format; _pp.BackBufferWidth = dispMode.Width; _pp.BackBufferHeight = dispMode.Height; _pp.FullScreenRefreshRateInHertz = dispMode.RefreshRate; device = new DeviceEx(d3dex, adapterOrdinal, devType, form.Handle, createFlags, _pp, dispMode); } else device = new DeviceEx(d3dex, adapterOrdinal, devType, form.Handle, createFlags, _pp); } else device = new Device(d3d, adapterOrdinal, devType, form.Handle, createFlags, _pp); } catch (Exception ex2) { if (_is3D9Ex) { // 3. fallback.. disable ex _is3D9Ex = false; Size ress = GetResolution(); RenderSize = ress; form.ClientSize = ress; _pp.BackBufferWidth = ress.Width; _pp.BackBufferHeight = ress.Height; _pp.BackBufferCount = 1; _pp.SwapEffect = SwapEffect.Discard; d3dex.Dispose(); device = new Device(new Direct3D(), adapterOrdinal, devType, form.Handle, createFlags, _pp); } else throw ex2; } } else throw ex; } // Load main shader if (System.IO.File.Exists(System.Windows.Forms.Application.StartupPath+"/client/render/simple.fx")) { string shaderOutput = null; SlimDX.Configuration.ThrowOnError = false; effect = Effect.FromFile(device, System.Windows.Forms.Application.StartupPath + "/client/render/simple.fx", null, null, null, ShaderFlags.None, null, out shaderOutput); if (shaderOutput != null && shaderOutput != "" && effect == null) { // Shader problem :..( System.Windows.Forms.MessageBox.Show(shaderOutput, "Shader Compilation error :(", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); Shutdown(); return; } SlimDX.Configuration.ThrowOnError = true; } else { System.Console.WriteLine("Could not find shader.."); } // Add fonts if (Fonts.Count == 0) { System.Drawing.Text.PrivateFontCollection col = new System.Drawing.Text.PrivateFontCollection(); col.AddFontFile(System.Windows.Forms.Application.StartupPath + @"\data\gui\Candara.ttf"); // UI Title System.Drawing.Font localFont = new System.Drawing.Font(col.Families[0], 10.5f, System.Drawing.FontStyle.Regular); SlimDX.Direct3D9.Font font = new SlimDX.Direct3D9.Font(Renderer.Instance.device, localFont); Fonts.Add("title", font); // FPS, etc. font = new SlimDX.Direct3D9.Font(device, new System.Drawing.Font("Lucidia Console", 10f, System.Drawing.FontStyle.Regular)); Fonts.Add("diag", font); // Labels and UI elements localFont = new System.Drawing.Font(col.Families[0], 10f, System.Drawing.FontStyle.Regular); font = new SlimDX.Direct3D9.Font(Renderer.Instance.device, localFont); Fonts.Add("label", font); localFont = new System.Drawing.Font(col.Families[0], 15f, System.Drawing.FontStyle.Regular); font = new SlimDX.Direct3D9.Font(Renderer.Instance.device, localFont); Fonts.Add("biglabel", font); localFont = new System.Drawing.Font(col.Families[0], 23f, System.Drawing.FontStyle.Regular); font = new SlimDX.Direct3D9.Font(Renderer.Instance.device, localFont); Fonts.Add("biggerlabel", font); // Textbox col = new System.Drawing.Text.PrivateFontCollection(); col.AddFontFile(System.Windows.Forms.Application.StartupPath + @"\data\gui\dina10px.ttf"); localFont = new System.Drawing.Font(col.Families[0], 12f, FontStyle.Regular); font = new SlimDX.Direct3D9.Font(Renderer.Instance.device, localFont); Fonts.Add("textbox", font); } // Init backbuffers, etc. OnResetDevice(); bloom = new Bloom(this); tonemap = new ToneMap(this); // Init windowing system WindowManager.Instance.Init(device); }
private void Main_Load(object sender, EventArgs e) { HotKey = new Hotkey(); HotKey.enable(this.Handle, Hotkey.Modifiers.None, Keys.Insert); // Delete //Insert HotKey.enable(this.Handle, Hotkey.Modifiers.Alt, Keys.F1); HotKey.enable(this.Handle, Hotkey.Modifiers.None, Keys.N); HotKey.enable(this.Handle, Hotkey.Modifiers.Alt, Keys.F3); HotKey.enable(this.Handle, Hotkey.Modifiers.Alt, Keys.F5); //HotKey.enable(base.Handle, Hotkey.Modifiers.None, Keys.CapsLock); //HotKey.enable(base.Handle, Hotkey.Modifiers.None, Keys.Q); Native.SetWindowLong(this.Handle, -20, (IntPtr)((Native.GetWindowLong(this.Handle, -20) ^ 0x80000) ^ 0x20)); Native.SetLayeredWindowAttributes(this.Handle, 0, 0xff, 2); PresentParameters parameters = new SlimDX.Direct3D9.PresentParameters(); parameters.Windowed = true; parameters.SwapEffect = SwapEffect.Discard; parameters.BackBufferFormat = Format.A8R8G8B8; parameters.BackBufferHeight = this.Height; parameters.BackBufferWidth = this.Width; parameters.PresentationInterval = PresentInterval.One; DXDevice = new SlimDX.Direct3D9.Device(new Direct3D(), 0, DeviceType.Hardware, this.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters[] { parameters }); if (System.IO.File.Exists("map_large.png")) DXTextrureMapLarge = SlimDX.Direct3D9.Texture.FromFile(DXDevice, "map_large.png"); if (System.IO.File.Exists("map.png")) DXTextrureMap = SlimDX.Direct3D9.Texture.FromFile(DXDevice, "map.png"); if (System.IO.File.Exists("LagerMap.jpg")) DXTextureGameMap = SlimDX.Direct3D9.Texture.FromFile(DXDevice, "LagerMap.jpg"); CircleVertices = new VertexBuffer(DXDevice, (circleComplexity + 2) * TexVertex.SizeBytes, Usage.WriteOnly, VertexFormat.None, Pool.Managed); DXSprite = new SlimDX.Direct3D9.Sprite(DXDevice); DXLine = new SlimDX.Direct3D9.Line(DXDevice); DXFont = new SlimDX.Direct3D9.Font(DXDevice, new System.Drawing.Font("NewRoman", 9f)); //NewRoman DXFontB = new SlimDX.Direct3D9.Font(DXDevice, new System.Drawing.Font("Tahoma", 12f)); //NewRoman if (this.GameMemory.Attach("H1Z1 PlayClient (Live)") == false) { Application.Exit(); return; } Thread dxThread = new Thread(new ThreadStart(DoProcess)); dxThread.IsBackground = true; dxThread.Start(); //Thread aimThread = new Thread(new ThreadStart(DoAiming)); //aimThread.IsBackground = true; //aimThread.Start(); }
private SlimDX.Direct3D9.Font GetFont(int size) { if (this.fonts.ContainsKey(size)) { return this.fonts[size]; } System.Drawing.Font font = new System.Drawing.Font("Verdana", (float)size); SlimDX.Direct3D9.Font font2 = new SlimDX.Direct3D9.Font(this.Dx, font); this.fonts.Add(size, font2); return font2; }
public TrueTypeFont(Device device, int size) { this.font = new D3D.Font(device.RawDevice, size, 0, D3D.FontWeight.Normal, 0, false, D3D.CharacterSet.Default, D3D.Precision.Outline, D3D.FontQuality.Default, D3D.PitchAndFamily.Default, ""); }
public void Initialize() { LoadSettings(); if (cut_lines) { if (NesEmu.TVFormat == TVSystem.NTSC) { linesToSkip = 8; scanlines = 224; } else { linesToSkip = 1; scanlines = 238; } } else { linesToSkip = 0; scanlines = 240; } currentBuffer = new int[256 * 240]; originalRect = new Rectangle(0, 0, 256, scanlines); currentMode = direct3D.Adapters[0].CurrentDisplayMode; Console.WriteLine("Direct3D: Initializing Direct 3d video device ..."); if (!NesEmu.EmulationON) fullScreen = false; try { if (!fullScreen) { presentParams = new PresentParameters(); presentParams.BackBufferWidth = surface_control.Width; presentParams.BackBufferCount = 1; presentParams.BackBufferHeight = surface_control.Height; presentParams.BackBufferFormat = Format.A8R8G8B8; presentParams.Windowed = true; presentParams.SwapEffect = SwapEffect.Discard; presentParams.Multisample = MultisampleType.None; presentParams.PresentationInterval = PresentInterval.Default; displayFormat = currentMode.Format; displayDevice = new Device(direct3D, 0, DeviceType.Hardware, surface_control.Handle, hardware_vertex_processing ? CreateFlags.HardwareVertexProcessing : CreateFlags.SoftwareVertexProcessing, presentParams); bufferSize = (256 * scanlines * 4); font = new SlimDX.Direct3D9.Font(displayDevice, new System.Drawing.Font("Tahoma", (6 * surface_control.Height) / scanlines, FontStyle.Bold)); font_BIG = new SlimDX.Direct3D9.Font(displayDevice, new System.Drawing.Font("Tahoma", (8 * surface_control.Height) / scanlines, FontStyle.Bold)); CreateDisplayObjects(displayDevice); initialized = true; disposed = false; if (keep_aspect_ratio) destinationRect = GetRatioStretchRectangle(surface_control.Width, surface_control.Height); else destinationRect = new Rectangle(0, 0, surface_control.Width, surface_control.Height); notification_x = destinationRect.X + 2; notification_y = surface_control.Height - ((surface_control.Height * 25) / scanlines); surface_control.Select(); if (!cursor_visible) { Cursor.Show(); cursor_visible = true; } canRender = true; } else { DisplayMode mode = this.FindSupportedMode(); presentParams = new PresentParameters(); presentParams.BackBufferFormat = mode.Format; presentParams.BackBufferCount = 1; presentParams.BackBufferWidth = mode.Width; presentParams.BackBufferHeight = mode.Height; presentParams.FullScreenRefreshRateInHertz = mode.RefreshRate; presentParams.Windowed = false; presentParams.SwapEffect = SwapEffect.Discard; presentParams.Multisample = MultisampleType.None; presentParams.PresentationInterval = PresentInterval.Default; displayFormat = mode.Format; displayDevice = new Device(direct3D, 0, DeviceType.Hardware, surface_control.Parent.Handle, hardware_vertex_processing ? CreateFlags.HardwareVertexProcessing : CreateFlags.SoftwareVertexProcessing, presentParams); displayDevice.ShowCursor = false; bufferSize = (256 * scanlines) * 4; font = new SlimDX.Direct3D9.Font(displayDevice, new System.Drawing.Font("Tahoma", (8 * mode.Height) / scanlines, FontStyle.Bold)); CreateDisplayObjects(displayDevice); initialized = true; disposed = false; if (keep_aspect_ratio) destinationRect = GetRatioStretchRectangle(mode.Width, mode.Height); else destinationRect = new Rectangle(0, 0, mode.Width, mode.Height); notification_x = destinationRect.X + 2; notification_y = mode.Height - ((mode.Height * 25) / scanlines); if (cursor_visible) { Cursor.Hide(); cursor_visible = false; } canRender = true; //Program.FormMain.InitializeInputRenderer(); } SetupZapperBounds(); Console.WriteLine("Direct3D: Direct 3d video device initialized."); } catch (Exception e) { initialized = false; Console.WriteLine("Direct3D: Failed to initialize the Direct 3d video device:"); Console.WriteLine(e.Message); } }
private void ReinitializeRenderer() { if (swapChain != null) { swapChain.Dispose(); swapChain = null; } if (TextFont != null) { TextFont.Dispose(); TextFont = null; } if (CursorMesh != null) { CursorMesh.Dispose(); CursorMesh = null; } PresentParameters presentParams = new PresentParameters(); presentParams.Windowed = true; presentParams.BackBufferCount = 0; presentParams.BackBufferWidth = Screen.PrimaryScreen.WorkingArea.Width; presentParams.BackBufferHeight = Screen.PrimaryScreen.WorkingArea.Height; try { Device.Reset(new PresentParameters[] { presentParams }); deviceLost = false; } catch { deviceLost = true; return; } Device.SetRenderState(RenderState.Lighting, true); Device.SetRenderState(RenderState.DiffuseMaterialSource, ColorSource.Material); Device.SetRenderState(RenderState.EmissiveMaterialSource, ColorSource.Material); Device.SetRenderState(RenderState.SpecularMaterialSource, ColorSource.Material); Device.SetRenderState(RenderState.SpecularEnable, true); Device.SetRenderState(RenderState.AlphaBlendEnable, true); Device.SetRenderState(RenderState.BlendOperationAlpha, BlendOperation.Add); Device.SetRenderState(RenderState.SourceBlend, Blend.SourceAlpha); Device.SetRenderState(RenderState.DestinationBlend, Blend.InverseSourceAlpha); Light light = new Light(); light.Type = LightType.Directional; light.Ambient = new Color4(int.Parse((string)Gui.Config["LightAmbientARGB"], System.Globalization.NumberStyles.AllowHexSpecifier)); light.Diffuse = new Color4(int.Parse((string)Gui.Config["LightDiffuseARGB"], System.Globalization.NumberStyles.AllowHexSpecifier)); light.Specular = new Color4(int.Parse((string)Gui.Config["LightSpecularARGB"], System.Globalization.NumberStyles.AllowHexSpecifier)); Device.SetLight(0, light); Device.EnableLight(0, true); TextFont = new SlimDX.Direct3D9.Font(Device, new System.Drawing.Font("Arial", 8)); TextColor = new Color4(Color.White); CursorMesh = Mesh.CreateSphere(Device, 1, 10, 10); CursorMaterial = new Material(); CursorMaterial.Ambient = new Color4(1, 1f, 1f, 1f); CursorMaterial.Diffuse = new Color4(1, 0.6f, 1, 0.3f); Culling = true; Background = Color.FromArgb(int.Parse((string)Gui.Config["RendererBackgroundARGB"], System.Globalization.NumberStyles.AllowHexSpecifier)); RenderControl = renderControl; }
private void UnloadResources() { resources_created = false; if (dxFont != null) { dxFont.Dispose(); dxFont = null; } if (dxTextSprite != null) { dxTextSprite.Dispose(); dxTextSprite = null; } if (dxLine != null) { dxLine.Dispose(); dxLine = null; } foreach (MapData map in maps) { try { if (map.dxTexture != null) { map.dxTexture.Dispose(); map.dxTexture = null; } } catch { //meh } } }
public Renderer(Control _control, bool _fullscreen, String _renderMethod) { fullscreen = _fullscreen; m_Control = _control; renderMethod = _renderMethod; if (m_Device == null) { Direct3DEx _d3d = new Direct3DEx(); PresentParameters _parameters = new PresentParameters(); if (fullscreen) { _parameters.BackBufferWidth = 1920;// m_Control.Width; _parameters.BackBufferHeight = 1080;// m_Control.Height; } else { _parameters.BackBufferWidth = 1280;// m_Control.Width; _parameters.BackBufferHeight = 800;// m_Control.Height; } if (fullscreen) { _parameters.BackBufferFormat = Format.X8R8G8B8; _parameters.BackBufferCount = 1; _parameters.Multisample = MultisampleType.None; _parameters.SwapEffect = SwapEffect.Flip; //_parameters.PresentationInterval = PresentInterval.Default; _parameters.PresentationInterval = PresentInterval.Immediate; _parameters.Windowed = false; _parameters.DeviceWindowHandle = m_Control.Parent.Handle; _parameters.SwapEffect = SwapEffect.Flip; _parameters.FullScreenRefreshRateInHertz = 0; _parameters.PresentFlags = PresentFlags.None | PresentFlags.DiscardDepthStencil; _parameters.AutoDepthStencilFormat = Format.D24X8; _parameters.EnableAutoDepthStencil = true; m_Device = new Device(_d3d, 0, DeviceType.Hardware, m_Control.Parent.Handle, CreateFlags.Multithreaded | CreateFlags.HardwareVertexProcessing, _parameters); } else { DisplayMode _mode = _d3d.GetAdapterDisplayMode(0); _parameters.BackBufferFormat = _mode.Format; _parameters.BackBufferCount = 1; _parameters.Multisample = MultisampleType.None; _parameters.SwapEffect = SwapEffect.Flip; _parameters.PresentationInterval = PresentInterval.Default; _parameters.Windowed = true; _parameters.DeviceWindowHandle = m_Control.Handle; _parameters.PresentationInterval = PresentInterval.Immediate; _parameters.PresentFlags = PresentFlags.DeviceClip | PresentFlags.Video; m_Device = new DeviceEx(_d3d, 0, DeviceType.Hardware, m_Control.Handle, CreateFlags.Multithreaded | CreateFlags.HardwareVertexProcessing, _parameters); } } m_RenderTarget = m_Device.GetRenderTarget(0); leftTex = new Texture(m_Device, 1280, 720, 1, Usage.RenderTarget, Format.A8R8G8B8, Pool.Default); //leftTex = Texture.FromFile(m_Device, ".\\Images\\checkerboard.jpg", D3DX.DefaultNonPowerOf2, D3DX.DefaultNonPowerOf2, 1, Usage.Dynamic, Format.A8R8G8B8, Pool.Default, Filter.None, Filter.None, 0); //leftTex = Texture.FromFile(m_Device, ".\\Images\\LeftEye.jpg", D3DX.DefaultNonPowerOf2, D3DX.DefaultNonPowerOf2, 1, Usage.RenderTarget, Format.Unknown, Pool.Default, Filter.None, Filter.None, 0); SurfaceDescription desc = leftTex.GetLevelDescription(0); //leftTex = Texture.FromFile(m_Device, ".\\Images\\CheckerboardLeft.jpg", Usage.RenderTarget, Pool.Default); rightTex = new Texture(m_Device, 1280, 720, 1, Usage.RenderTarget, Format.A8R8G8B8, Pool.Default); //rightTex = Texture.FromFile(m_Device, ".\\Images\\RightEye.jpg", D3DX.DefaultNonPowerOf2, D3DX.DefaultNonPowerOf2, 1, Usage.RenderTarget, Format.Unknown, Pool.Default, Filter.None, Filter.None, 0); //rightTex = Texture.FromFile(m_Device, ".\\Images\\CheckerboardRight.jpg", Usage.RenderTarget, Pool.Default); m_font = new SlimDX.Direct3D9.Font(m_Device, new System.Drawing.Font(FontFamily.GenericSansSerif, 24.0f)); switch (renderMethod) { case "None" : m_distortionEffect = Effect.FromFile(m_Device, "PlainPS.fx", ShaderFlags.None); break; case "Oculus": m_distortionEffect = Effect.FromFile(m_Device, "OculusRiftPS.fx", ShaderFlags.None); break; case "3DTV": m_distortionEffect = Effect.FromFile(m_Device, "PlainPS.fx", ShaderFlags.None); break; default: throw new Exception("No render method found."); break; } //leftImage = Surface.CreateOffscreenPlain(m_Device, 640, 720, Format.A8R8G8B8, Pool.Default); //Surface.FromFile(leftImage, ".\\Images\\checkerboardRedGreen.jpg", Filter.None, 0); //rightImage = Surface.CreateOffscreenPlain(m_Device, 640, 720, Format.A8R8G8B8, Pool.Default); //Surface.FromFile(rightImage, ".\\Images\\checkerboardRedGreen.jpg", Filter.None, 0); //tex = new Texture(m_Device, 1280, 720, 1, Usage.Dynamic, Format.A8R8G8B8, Pool.Default); //tex = new Texture(m_Device, 1280, 720, 1, Usage.RenderTarget, Format.R8G8B8, Pool.Default); }
public static bool DirectXInit() { if (!MainForm.booting) { try { if (!MainForm.booting) { rendering = false; switch (display_mode) { case DisplayMode.PANADAPTER: case DisplayMode.PANAFALL: case DisplayMode.PANASCOPE: panadapter_target = (Control)MainForm.picPanadapter; panadapter_W = panadapter_target.Width; panadapter_H = panadapter_target.Height; waterfall_target = (Control)MainForm.picWaterfall; waterfall_H = waterfall_target.Height; waterfall_W = waterfall_target.Width; waterfallX_data = new float[waterfall_W]; panadapterX_scope_data = new float[waterfall_W * 2]; panadapterX_scope_data_mark = new float[waterfall_W * 2]; panadapterX_scope_data_space = new float[waterfall_W * 2]; Audio.ScopeDisplayWidth = waterfall_W; break; case DisplayMode.PANAFALL_INV: case DisplayMode.PANASCOPE_INV: panadapter_target = (Control)MainForm.picWaterfall; panadapter_W = panadapter_target.Width; panadapter_H = panadapter_target.Height; waterfall_target = (Control)MainForm.picPanadapter; waterfall_H = waterfall_target.Height; waterfall_W = waterfall_target.Width; waterfallX_data = new float[waterfall_W]; panadapterX_scope_data = new float[waterfall_W * 2]; Audio.ScopeDisplayWidth = waterfall_W; break; case DisplayMode.WATERFALL: waterfall_target = (Control)MainForm.picWaterfall; break; default: panadapter_H = panadapter_target.Height; panadapter_W = panadapter_target.Width; panadapterX_scope_data = new float[panadapter_W]; panadapter_target = (Control)MainForm.picPanadapter; break; } panadapterX_data = new float[panadapter_target.Width]; refresh_panadapter_grid = true; average_buffer = new float[BUFFER_SIZE]; // initialize averaging buffer array average_buffer[0] = CLEAR_FLAG; // set the clear flag average_waterfall_buffer = new float[BUFFER_SIZE]; // initialize averaging buffer array average_waterfall_buffer[0] = CLEAR_FLAG; // set the clear flag peak_buffer = new float[BUFFER_SIZE]; peak_buffer[0] = CLEAR_FLAG; new_display_data = new float[BUFFER_SIZE]; new_waterfall_data = new float[BUFFER_SIZE]; current_display_data = new float[BUFFER_SIZE]; current_waterfall_data = new float[BUFFER_SIZE]; waterfall_display_data = new float[BUFFER_SIZE]; for (int i = 0; i < BUFFER_SIZE; i++) { new_display_data[i] = 0.0f; new_waterfall_data[i] = 0.0f; current_display_data[i] = 0.0f; current_waterfall_data[i] = 0.0f; waterfall_display_data[i] = 0.0f; } PresentParameters presentParms = new PresentParameters(); presentParms.Windowed = true; presentParms.SwapEffect = SwapEffect.Discard; presentParms.BackBufferFormat = SlimDX.Direct3D9.Format.Unknown; presentParms.BackBufferHeight = panadapter_target.Height; presentParms.BackBufferWidth = panadapter_target.Width; presentParms.BackBufferCount = 1; presentParms.BackBufferFormat = Format.X8R8G8B8; PresentParameters waterfall_presentParms = new PresentParameters(); waterfall_presentParms.Windowed = true; waterfall_presentParms.SwapEffect = SwapEffect.Discard; waterfall_presentParms.BackBufferFormat = SlimDX.Direct3D9.Format.Unknown; waterfall_presentParms.BackBufferHeight = waterfall_target.Height; waterfall_presentParms.BackBufferWidth = waterfall_target.Width; waterfall_presentParms.BackBufferCount = 1; waterfall_presentParms.BackBufferFormat = Format.X8R8G8B8; switch (directx_render_type) { case RenderType.HARDWARE: try { device = new Device(new Direct3D(), 0, DeviceType.Hardware, panadapter_target.Handle, CreateFlags.HardwareVertexProcessing | CreateFlags.FpuPreserve | CreateFlags.Multithreaded, presentParms); waterfall_dx_device = new Device(new Direct3D(), 0, DeviceType.Hardware, waterfall_target.Handle, CreateFlags.HardwareVertexProcessing | CreateFlags.FpuPreserve | CreateFlags.Multithreaded, waterfall_presentParms); } catch (Direct3D9Exception ex) { MessageBox.Show("DirectX hardware init error!" + ex.ToString()); } break; case RenderType.SOFTWARE: { try { device = new Device(new Direct3D(), 0, DeviceType.Hardware, panadapter_target.Handle, CreateFlags.SoftwareVertexProcessing | CreateFlags.FpuPreserve, presentParms); waterfall_dx_device = new Device(new Direct3D(), 0, DeviceType.Hardware, waterfall_target.Handle, CreateFlags.SoftwareVertexProcessing | CreateFlags.FpuPreserve, waterfall_presentParms); } catch (Direct3D9Exception ex) { MessageBox.Show("DirectX software init error!\n" + ex.ToString()); return false; } } break; } var vertexElems = new[] { new VertexElement(0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.PositionTransformed, 0), new VertexElement(0, 16, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), VertexElement.VertexDeclarationEnd }; var vertexElems1 = new[] { new VertexElement(0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.PositionTransformed, 0), new VertexElement(0, 16, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), VertexElement.VertexDeclarationEnd }; var vertexDecl = new VertexDeclaration(device, vertexElems); device.VertexDeclaration = vertexDecl; var vertexDecl1 = new VertexDeclaration(waterfall_dx_device, vertexElems1); waterfall_dx_device.VertexDeclaration = vertexDecl1; waterfall_bmp = new System.Drawing.Bitmap(waterfall_target.Width, waterfall_target.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); BitmapData bitmapData = waterfall_bmp.LockBits( new Rectangle(0, 0, waterfall_bmp.Width, waterfall_bmp.Height), ImageLockMode.ReadWrite, waterfall_bmp.PixelFormat); waterfall_bmp_size = bitmapData.Stride * waterfall_bmp.Height; waterfall_bmp_stride = bitmapData.Stride; waterfall_memory = new byte[waterfall_bmp_size]; waterfall_bmp.UnlockBits(bitmapData); waterfall_rect = new Rectangle(0, 0, waterfall_target.Width, waterfall_target.Height); panadapter_font = new SlimDX.Direct3D9.Font(device, pan_font); if (File.Exists(background_image)) { PanadapterTexture = Texture.FromFile(device, background_image, panadapter_target.Width, panadapter_target.Height, 1, Usage.None, Format.Unknown, Pool.Managed, SlimDX.Direct3D9.Filter.Default, SlimDX.Direct3D9.Filter.Default, 0); Panadapter_texture_size.Width = panadapter_target.Width; Panadapter_texture_size.Height = panadapter_target.Height; Panadapter_Sprite = new Sprite(device); WaterfallTexture = Texture.FromFile(waterfall_dx_device, background_image, waterfall_target.Width, waterfall_target.Height, 1, Usage.None, Format.X8R8G8B8, Pool.Managed, SlimDX.Direct3D9.Filter.Default, SlimDX.Direct3D9.Filter.Default, 0); Waterfall_texture_size.Width = waterfall_target.Width; Waterfall_texture_size.Height = waterfall_target.Height; Waterfall_Sprite = new Sprite(waterfall_dx_device); } else { Panadapter_Sprite = null; WaterfallTexture = new Texture(waterfall_dx_device, waterfall_target.Width, waterfall_target.Height, 0, Usage.None, Format.X8R8G8B8, Pool.Managed); Waterfall_texture_size.Width = waterfall_target.Width; Waterfall_texture_size.Height = waterfall_target.Height; Waterfall_Sprite = new Sprite(waterfall_dx_device); } if (Panadapter_Event == null) Panadapter_Event = new AutoResetEvent(true); if (Waterfall_Event == null) Waterfall_Event = new AutoResetEvent(true); ScopeLine_vb = new VertexBuffer(waterfall_dx_device, waterfall_W * 2 * 20, Usage.WriteOnly, VertexFormat.None, Pool.Managed); ScopeLine_verts = new Vertex[waterfall_W * 2]; ScopeLine_vb_monitor = new VertexBuffer(MainForm.waterfall_dx_device, MainForm.picMonitor.Width * 2 * 20, Usage.WriteOnly, VertexFormat.None, Pool.Managed); PanLine_vb = new VertexBuffer(device, panadapterX_data.Length * 20, Usage.WriteOnly, VertexFormat.None, Pool.Managed); PanLine_vb_fill = new VertexBuffer(device, panadapter_W * 2 * 20, Usage.WriteOnly, VertexFormat.None, Pool.Managed); PanLine_verts = new Vertex[panadapter_W]; PanLine_verts_fill = new Vertex[panadapter_W * 2]; return true; } return false; } catch (Exception ex) { Debug.Write("DirectX init general fault!\n" + ex.ToString()); return false; } } return false; }
private void CreateDevice() { this.device = new Device(new Direct3D(), 0, DeviceType.Hardware, this.devicePanel.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters() { SwapEffect = SwapEffect.Discard, Windowed = true, BackBufferWidth = this.devicePanel.ClientSize.Width, BackBufferHeight = this.devicePanel.ClientSize.Height }); this.device.VertexFormat = VectorColored.Format; this.titleFont = new DXFont(this.device, new WinFont("Courier New", 14, FontStyle.Bold)); this.labelFont = new DXFont(this.device, new WinFont("Courier New", 10, FontStyle.Bold)); }
/// <summary> /// Hook for IDirect3DDevice9.EndScene /// </summary> /// <param name="devicePtr">Pointer to the IDirect3DDevice9 instance. Note: object member functions always pass "this" as the first parameter.</param> /// <returns>The HRESULT of the original EndScene</returns> /// <remarks>Remember that this is called many times a second by the Direct3D application - be mindful of memory and performance!</remarks> int EndSceneHook(IntPtr devicePtr) { using (Device device = Device.FromPointer(devicePtr)) { // If you need to capture at a particular frame rate, add logic here decide whether or not to skip the frame try { #region Screenshot Request // Is there a screenshot request? If so lets grab the backbuffer lock (_lockRenderTarget) { if (Request != null) { _lastRequestTime = DateTime.Now; DateTime start = DateTime.Now; try { // First ensure we have a Surface to the render target data into if (_renderTarget == null) { // Create offscreen surface to use as copy of render target data using (SwapChain sc = device.GetSwapChain(0)) { _renderTarget = Surface.CreateOffscreenPlain(device, sc.PresentParameters.BackBufferWidth, sc.PresentParameters.BackBufferHeight, sc.PresentParameters.BackBufferFormat, Pool.SystemMemory); } } #region Prepare lines for overlay if (this.Request.RegionToCapture.Width == 0) { _lineVectors = new SlimDX.Vector2[] { new SlimDX.Vector2(0, 0), new SlimDX.Vector2(_renderTarget.Description.Width - 1, _renderTarget.Description.Height - 1), new SlimDX.Vector2(0, _renderTarget.Description.Height - 1), new SlimDX.Vector2(_renderTarget.Description.Width - 1, 0), new SlimDX.Vector2(0, 0), new SlimDX.Vector2(0, _renderTarget.Description.Height - 1), new SlimDX.Vector2(_renderTarget.Description.Width - 1, _renderTarget.Description.Height - 1), new SlimDX.Vector2(_renderTarget.Description.Width - 1, 0), }; } else { _lineVectors = new SlimDX.Vector2[] { new SlimDX.Vector2(this.Request.RegionToCapture.X, this.Request.RegionToCapture.Y), new SlimDX.Vector2(this.Request.RegionToCapture.Right, this.Request.RegionToCapture.Bottom), new SlimDX.Vector2(this.Request.RegionToCapture.X, this.Request.RegionToCapture.Bottom), new SlimDX.Vector2(this.Request.RegionToCapture.Right, this.Request.RegionToCapture.Y), new SlimDX.Vector2(this.Request.RegionToCapture.X, this.Request.RegionToCapture.Y), new SlimDX.Vector2(this.Request.RegionToCapture.X, this.Request.RegionToCapture.Bottom), new SlimDX.Vector2(this.Request.RegionToCapture.Right, this.Request.RegionToCapture.Bottom), new SlimDX.Vector2(this.Request.RegionToCapture.Right, this.Request.RegionToCapture.Y), }; } #endregion using (Surface backBuffer = device.GetBackBuffer(0, 0)) { // Create a super fast copy of the back buffer on our Surface device.GetRenderTargetData(backBuffer, _renderTarget); // We have the back buffer data and can now work on copying it to a bitmap ProcessRequest(); } } finally { // We have completed the request - mark it as null so we do not continue to try to capture the same request // Note: If you are after high frame rates, consider implementing buffers here to capture more frequently // and send back to the host application as needed. The IPC overhead significantly slows down // the whole process if sending frame by frame. Request = null; } DateTime end = DateTime.Now; this.DebugMessage("EndSceneHook: Capture time: " + (end - start).ToString()); _lastScreenshotTime = (end - start); } } #endregion #region Example: Draw Overlay (after screenshot so we don't capture overlay as well) if (this.ShowOverlay) { #region Draw fading lines based on last screencapture request if (_lastRequestTime != null && _lineVectors != null) { TimeSpan timeSinceRequest = DateTime.Now - _lastRequestTime.Value; if (timeSinceRequest.TotalMilliseconds < 1000.0) { using (Line line = new Line(device)) { _lineAlpha = (float)((1000.0 - timeSinceRequest.TotalMilliseconds) / 1000.0); // This is our fade out line.Antialias = true; line.Width = 1.0f; line.Begin(); line.Draw(_lineVectors, new SlimDX.Color4(_lineAlpha, 0.5f, 0.5f, 1.0f)); line.End(); } } else { _lineVectors = null; } } #endregion #region Draw frame rate using (SlimDX.Direct3D9.Font font = new SlimDX.Direct3D9.Font(device, new System.Drawing.Font("Times New Roman", 16.0f))) { if (_lastFrame != null) { font.DrawString(null, String.Format("{0:N1} fps", (1000.0 / (DateTime.Now - _lastFrame.Value).TotalMilliseconds)), 100, 100, System.Drawing.Color.Red); } _lastFrame = DateTime.Now; } #endregion } #endregion } catch(Exception e) { // If there is an error we do not want to crash the hooked application, so swallow the exception this.DebugMessage("EndSceneHook: Exeception: " + e.GetType().FullName + ": " + e.Message); } // EasyHook has already repatched the original EndScene - so calling EndScene against the SlimDX device will call the original // EndScene and bypass this hook. EasyHook will automatically reinstall the hook after this hook function exits. return device.EndScene().Code; } }
protected override void DrawText(Object dev, String text, String text2=null, int alpha=0) { Device device = (Device)dev; if (_font == null) { _font = new SlimDX.Direct3D9.Font(device, new System.Drawing.Font("Lucida Console", 10.0f)); } if (screenHeight == 0 | screenWidth == 0) { using (Surface backBuffer = device.GetBackBuffer(0, 0)) { screenWidth = backBuffer.Description.Width; screenHeight = backBuffer.Description.Height; } } _font.DrawString(null, text, new Rectangle(0, 0, screenWidth, screenHeight), DrawTextFormat.Top | DrawTextFormat.Right, System.Drawing.Color.Red); if (alpha>0) { Color c = Color.FromArgb(alpha, System.Drawing.Color.Red); _font.DrawString(null, text2, new Rectangle(0, 15, screenWidth, screenHeight-15), DrawTextFormat.Top | DrawTextFormat.Right, c); } }
public static bool DirectXInit() { if (!booting && !DX_reinit) { try { try { DX_reinit = true; switch (current_display_mode) { case DisplayMode.PANADAPTER: case DisplayMode.PANAFALL: case DisplayMode.PANAFALL_INV: case DisplayMode.PANASCOPE: panadapter_target = (Control)console.picDisplay; panadapter_W = panadapter_target.Width; panadapter_H = panadapter_target.Height; WaterfallTarget = (Control)console.picWaterfall; waterfallX_data = new float[waterfall_W]; panadapterX_scope_data = new float[waterfall_W * 2]; break; case DisplayMode.WATERFALL: WaterfallTarget = (Control)console.picWaterfall; panadapterX_scope_data = new float[waterfall_W * 2]; break; default: panadapter_H = panadapter_target.Height; panadapter_W = panadapter_target.Width; panadapterX_scope_data = new float[panadapter_W * 2]; panadapter_target = (Control)console.picDisplay; break; } panadapterX_data = new float[panadapter_W]; refresh_panadapter_grid = true; histogram_data = new int[panadapter_W]; histogram_verts = new HistogramData[panadapter_W * 4]; scope_min = new float[waterfall_target.Width]; scope_max = new float[waterfall_target.Width]; histogram_history = new int[panadapter_W]; for (int i = 0; i < panadapter_W; i++) { histogram_data[i] = Int32.MaxValue; histogram_history[i] = 0; histogram_verts[i].X = i; histogram_verts[i].Y = panadapter_H; histogram_verts[i].color = Color.Green; } average_buffer = new float[BUFFER_SIZE]; // initialize averaging buffer array average_buffer[0] = CLEAR_FLAG; // set the clear flag average_waterfall_buffer = new float[BUFFER_SIZE]; // initialize averaging buffer array average_waterfall_buffer[0] = CLEAR_FLAG; // set the clear flag peak_buffer = new float[BUFFER_SIZE]; peak_buffer[0] = CLEAR_FLAG; new_display_data = new float[BUFFER_SIZE]; new_scope_data = new float[BUFFER_SIZE]; new_waterfall_data = new float[BUFFER_SIZE]; current_display_data = new float[BUFFER_SIZE]; current_scope_data = new float[BUFFER_SIZE]; current_waterfall_data = new float[BUFFER_SIZE]; waterfall_display_data = new float[BUFFER_SIZE]; for (int i = 0; i < BUFFER_SIZE; i++) { new_display_data[i] = -200.0f; new_scope_data[i] = -200.0f; new_waterfall_data[i] = -200.0f; current_display_data[i] = -200.0f; current_scope_data[i] = -200.0f; current_waterfall_data[i] = -200.0f; waterfall_display_data[i] = -200.0f; } presentParms = new PresentParameters(); presentParms.Windowed = true; presentParms.SwapEffect = SwapEffect.Discard; presentParms.Multisample = MultisampleType.None; presentParms.EnableAutoDepthStencil = true; presentParms.AutoDepthStencilFormat = Format.D24X8; presentParms.PresentFlags = PresentFlags.DiscardDepthStencil; presentParms.PresentationInterval = PresentInterval.Default; presentParms.BackBufferFormat = Format.X8R8G8B8; presentParms.BackBufferHeight = panadapter_target.Height; presentParms.BackBufferWidth = panadapter_target.Width; presentParms.Windowed = true; presentParms.BackBufferCount = 1; switch (directx_render_type) { case RenderType.HARDWARE: try { device = new Device(new Direct3D(), 0, DeviceType.Hardware, panadapter_target.Handle, CreateFlags.HardwareVertexProcessing | CreateFlags.FpuPreserve | CreateFlags.Multithreaded, presentParms); waterfall_dx_device = new Device(new Direct3D(), 0, DeviceType.Hardware, waterfall_target.Handle, CreateFlags.HardwareVertexProcessing | CreateFlags.FpuPreserve | CreateFlags.Multithreaded, presentParms); } catch (Direct3D9Exception ex) { if (debug && !console.ConsoleClosing) console.Invoke(new DebugCallbackFunction(console.DebugCallback), "DirectX hardware init error!" + ex.ToString()); } break; case RenderType.SOFTWARE: try { device = new Device(new Direct3D(), 0, DeviceType.Hardware, panadapter_target.Handle, CreateFlags.SoftwareVertexProcessing | CreateFlags.FpuPreserve | CreateFlags.Multithreaded, presentParms); waterfall_dx_device = new Device(new Direct3D(), 0, DeviceType.Hardware, waterfall_target.Handle, CreateFlags.SoftwareVertexProcessing | CreateFlags.FpuPreserve | CreateFlags.Multithreaded, presentParms); } catch (Direct3D9Exception exe) { if (debug && !console.ConsoleClosing) console.Invoke(new DebugCallbackFunction(console.DebugCallback), "DirectX software init error!" + exe.ToString()); return false; } break; } var vertexElems = new[] { new VertexElement(0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.PositionTransformed, 0), new VertexElement(0, 16, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), VertexElement.VertexDeclarationEnd }; var vertexDecl = new VertexDeclaration(device, vertexElems); device.VertexDeclaration = vertexDecl; var vertexDecl1 = new VertexDeclaration(waterfall_dx_device, vertexElems); waterfall_dx_device.VertexDeclaration = vertexDecl1; waterfall_bmp = new System.Drawing.Bitmap(waterfall_target.Width, waterfall_target.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); BitmapData bitmapData = waterfall_bmp.LockBits( new Rectangle(0, 0, waterfall_bmp.Width, waterfall_bmp.Height), ImageLockMode.ReadWrite, waterfall_bmp.PixelFormat); waterfall_bmp_size = bitmapData.Stride * waterfall_bmp.Height; waterfall_bmp_stride = bitmapData.Stride; waterfall_memory = new byte[waterfall_bmp_size]; waterfall_bmp.UnlockBits(bitmapData); waterfall_rect = new Rectangle(0, 0, waterfall_target.Width, waterfall_target.Height); //backbuf = waterfall_dx_device.GetBackBuffer(0, 0); panadapter_font = new SlimDX.Direct3D9.Font(device, pan_font); if (background_image != null && File.Exists(background_image)) { PanadapterTexture = Texture.FromFile(device, background_image, panadapter_target.Width, panadapter_target.Height, 1, Usage.None, Format.Unknown, Pool.Managed, SlimDX.Direct3D9.Filter.Default, SlimDX.Direct3D9.Filter.Default, 0); Panadapter_texture_size.Width = panadapter_target.Width; Panadapter_texture_size.Height = panadapter_target.Height; Panadapter_Sprite = new Sprite(device); WaterfallTexture = Texture.FromFile(waterfall_dx_device, background_image, waterfall_target.Width, waterfall_target.Height, 1, Usage.None, Format.Unknown, Pool.Managed, SlimDX.Direct3D9.Filter.Default, SlimDX.Direct3D9.Filter.Default, 0); Waterfall_texture_size.Width = waterfall_target.Width; Waterfall_texture_size.Height = waterfall_target.Height; WaterfallBackgroundTexture = Texture.FromFile(waterfall_dx_device, background_image, waterfall_target.Width, waterfall_target.Height, 1, Usage.None, Format.Unknown, Pool.Managed, SlimDX.Direct3D9.Filter.Default, SlimDX.Direct3D9.Filter.Default, 0); Waterfall_Sprite = new Sprite(waterfall_dx_device); } else { Panadapter_Sprite = null; WaterfallTexture = new Texture(waterfall_dx_device, waterfall_target.Width, waterfall_target.Height, 0, Usage.None, Format.X8R8G8B8, Pool.Managed); WaterfallBackgroundTexture = new Texture(waterfall_dx_device, waterfall_target.Width, waterfall_target.Height, 0, Usage.None, Format.X8R8G8B8, Pool.Managed); Waterfall_texture_size.Width = waterfall_target.Width; Waterfall_texture_size.Height = waterfall_target.Height; Waterfall_Sprite = new Sprite(waterfall_dx_device); } if (directx_render_type == RenderType.HARDWARE) { Waterfall_vb = new VertexBuffer(waterfall_dx_device, panadapterX_data.Length * 2 * 20, Usage.WriteOnly, VertexFormat.None, Pool.Managed); Waterfall_verts = new Vertex[waterfall_W * 2]; Panadapter_vb = new VertexBuffer(device, panadapterX_data.Length * 2 * 20, Usage.WriteOnly, VertexFormat.None, Pool.Managed); PanLine_vb_fill = new VertexBuffer(device, panadapter_W * 2 * 20, Usage.WriteOnly, VertexFormat.None, Pool.Managed); Panadapter_verts = new Vertex[panadapter_W * 2]; Panadapter_verts_fill = new Vertex[panadapter_W * 2]; HistogramLine_verts = new Vertex[panadapter_W * 6]; Histogram_vb = new VertexBuffer(device, panadapter_W * 4 * 20, Usage.WriteOnly, VertexFormat.None, Pool.Managed); } else if (directx_render_type == RenderType.SOFTWARE) { Waterfall_vb = new VertexBuffer(waterfall_dx_device, panadapterX_data.Length * 20, Usage.WriteOnly, VertexFormat.None, Pool.Default); Waterfall_verts = new Vertex[waterfall_W]; Panadapter_vb = new VertexBuffer(device, panadapterX_data.Length * 20, Usage.WriteOnly, VertexFormat.None, Pool.Default); PanLine_vb_fill = new VertexBuffer(device, panadapter_W * 2 * 20, Usage.WriteOnly, VertexFormat.None, Pool.Default); Panadapter_verts = new Vertex[panadapter_W]; Panadapter_verts_fill = new Vertex[panadapter_W * 2]; HistogramLine_verts = new Vertex[panadapter_W * 6]; Histogram_vb = new VertexBuffer(device, panadapter_W * 4 * 20, Usage.WriteOnly, VertexFormat.None, Pool.Default); } panadapter_verts = new Vector2[panadapter_W]; panadapter_line = new Line(device); panadapter_line.Antialias = smooth_line; panadapter_line.Width = display_line_width; panadapter_line.GLLines = true; panadapter_fill_verts = new Vector2[panadapter_W * 2]; panadapter_fill_line = new Line(device); panadapter_fill_line.Antialias = smooth_line; panadapter_fill_line.Width = 1; panadapter_fill_line.GLLines = true; high_swr_font = new SlimDX.Direct3D9.Font(device, new System.Drawing.Font("Arial", 14.0f, FontStyle.Bold)); DX_reinit = false; return true; } catch (Direct3D9Exception ex) { //MessageBox.Show("DirectX init general fault!\n" + ex.ToString()); DX_reinit = false; if (debug && !console.ConsoleClosing) console.Invoke(new DebugCallbackFunction(console.DebugCallback), "DirectX init general fault!\n" + ex.ToString()); return false; } } catch (Exception ex) { Debug.Write(ex.ToString()); DX_reinit = false; return false; } } return true; }
/// <summary> /// Just ensures that the surface we created is cleaned up. /// </summary> public override void Cleanup() { DebugMessage("Cleanup"); try { lock (_lockRenderTarget) { if (_renderTarget != null) { _renderTarget.Dispose(); _renderTarget = null; } if (_renderTarget0 != null) { _renderTarget0.Dispose(); _renderTarget0 = null; } Request = null; if (bitmap != null) { bitmap.Dispose(); bitmap = null; } if (_font != null) { _font.OnLostDevice(); _font.Dispose(); _font = null; } if (_sprite != null) { _sprite.Dispose(); _sprite = null; } screenWidth = screenHeight = 0; } } catch { } }