/// <summary> /// Initializes the various Direct3D objects we'll be using. /// </summary> public bool Initialize(bool startThread) { try { StartThread = startThread; ReleaseD3D(); HwndSource hwnd = new HwndSource(0, 0, 0, 0, 0, "test", IntPtr.Zero); pp = new PresentParameters(); pp.SwapEffect = SwapEffect.Discard; pp.DeviceWindowHandle = hwnd.Handle; pp.Windowed = true; pp.BackBufferWidth = (int)ActualWidth; pp.BackBufferHeight = (int)ActualHeight; pp.BackBufferFormat = Format.X8R8G8B8; if (useDeviceEx) { deviceEx = new DeviceEx((Direct3DEx)Direct3D, 0, DeviceType.Hardware, hwnd.Handle, CreateFlags.HardwareVertexProcessing, pp); } else { device = new Device(Direct3D, 0, DeviceType.Hardware, hwnd.Handle, CreateFlags.HardwareVertexProcessing, pp); } // call the users one OnDeviceCreated(EventArgs.Empty); OnDeviceReset(EventArgs.Empty); // only if startThread is true if (StartThread) { CompositionTarget.Rendering += OnRendering; d3dimage.IsFrontBufferAvailableChanged += new DependencyPropertyChangedEventHandler(OnIsFrontBufferAvailableChanged); } d3dimage.Lock(); d3dimage.SetBackBuffer(D3DResourceType.IDirect3DSurface9, Device.GetBackBuffer(0, 0).ComPointer); d3dimage.Unlock(); CustomInitialize(); return(true); } catch (Exception exc) { MessageBox.Show(exc.Message); return(false); } }
/// <summary> /// Initializes a new instance of the <see cref="D3D11Image"/> class. Associates an D3D11 render target with the current instance. /// </summary> /// <param name="device">A valid D3D9 DeviceEx.</param> /// <param name="renderTarget">A valid D3D11 render target. It must be created with the "Shared" flag.</param> public D3D11Image(DeviceEx device, Texture2D renderTarget) { using (var resource = renderTarget.QueryInterface<DXGIResource>()) { var handle = resource.SharedHandle; this.texture = new Texture( device, renderTarget.Description.Width, renderTarget.Description.Height, 1, Usage.RenderTarget, Format.A8R8G8B8, Pool.Default, ref handle); } using (var surface = this.texture.GetSurfaceLevel(0)) { this.textureSurfaceHandle = surface.NativePointer; this.TrySetBackbufferPointer(this.textureSurfaceHandle); } this.IsFrontBufferAvailableChanged += this.HandleIsFrontBufferAvailableChanged; }
/// <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 SwapChain9Ex(_swapChain.NativePointer); _line = new Line(_device) { Width = 2.5f, Antialias = true }; _fontSprite = new Sprite(_device); _font = new Font(_device, TEXT_SIZE, 0, FontWeight.Normal, 0, false, FontCharacterSet.Default, FontPrecision.Default, FontQuality.ClearTypeNatural, FontPitchAndFamily.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; }
void Initialize() { ReleaseD3D(); HwndSource hwnd = new HwndSource(0, 0, 0, 0, 0, "test", IntPtr.Zero); pp = new PresentParameters(); pp.SwapEffect = SwapEffect.Discard; pp.DeviceWindowHandle = hwnd.Handle; pp.Windowed = true; pp.BackBufferWidth = (int)ActualWidth; pp.BackBufferHeight = (int)ActualHeight; pp.BackBufferFormat = Format.X8R8G8B8; //pp.Multisample = MultisampleType.EightSamples; device = new DeviceEx(Direct3D, 0, DeviceType.Hardware, hwnd.Handle, CreateFlags.HardwareVertexProcessing, pp); System.Windows.Media.CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering); d3dimage.IsFrontBufferAvailableChanged += new DependencyPropertyChangedEventHandler(d3dimage_IsFrontBufferAvailableChanged); d3dimage.Lock(); d3dimage.SetBackBuffer(D3DResourceType.IDirect3DSurface9, device.GetBackBuffer(0, 0).ComPointer); d3dimage.Unlock(); }
private void ReleaseDevice() { if (_device != null) { if (!_device.Disposed) { _device.Dispose(); _device = null; OnDeviceDestroyed(EventArgs.Empty); } } if (_deviceEx != null) { if (!_deviceEx.Disposed) { _deviceEx.Dispose(); _deviceEx = null; OnDeviceDestroyed(EventArgs.Empty); } } _d3dimage.Lock(); _d3dimage.SetBackBuffer(D3DResourceType.IDirect3DSurface9, IntPtr.Zero); _d3dimage.Unlock(); ReleaseBackBuffer(); }
public static Texture GetSharedD3D9(this DeviceEx device, SharpDX.Direct3D11.Texture2D renderTarget) { if (renderTarget == null) { return(null); } if ((renderTarget.Description.OptionFlags & SharpDX.Direct3D11.ResourceOptionFlags.Shared) == 0) { throw new ArgumentException("Texture must be created with ResourceOptionFlags.Shared"); } Format format = ToD3D9(renderTarget.Description.Format); if (format == Format.Unknown) { throw new ArgumentException("Texture format is not compatible with OpenSharedResource"); } using (var resource = renderTarget.QueryInterface <SharpDX.DXGI.Resource>()) { IntPtr handle = resource.SharedHandle; if (handle == IntPtr.Zero) { throw new ArgumentNullException("Handle"); } return(new Texture(device, renderTarget.Description.Width, renderTarget.Description.Height, 1, Usage.RenderTarget, format, Pool.Default, ref handle)); } }
public Graphics(RenderForm form, int width, int height) { reset = () => form.Invoke(new Action(() => { device.Reset(presentParameters); fontRenderer.Flush(); textureRenderer.Flush(); resized = false; })); form.UserResized += (sender, args) => Resize(form.ClientSize.Width, form.ClientSize.Height); presentParameters = new PresentParameters { Windowed = true, SwapEffect = SwapEffect.Discard, BackBufferFormat = Format.A8R8G8B8, BackBufferCount = 1, BackBufferWidth = width, BackBufferHeight = height, PresentationInterval = PresentInterval.One, MultiSampleType = MultisampleType.None, MultiSampleQuality = 0, PresentFlags = PresentFlags.LockableBackBuffer }; direct3D = new Direct3DEx(); device = new DeviceEx(direct3D, 0, DeviceType.Hardware, form.Handle, CREATE_FLAGS, presentParameters); fontRenderer = new FontRenderer(device); textureRenderer = new TextureRenderer(device); renderLocker.Reset(); }
/// <summary> /// Initializes a new instance of the <see cref="D3D9"/> class. /// </summary> public D3D9() { // Create Direct3DEx device on Windows Vista/7/8 with a display configured to use // the Windows Display Driver Model (WDDM). Use Direct3D on any other platform. _direct3D = new Direct3DEx(); PresentParameters presentparams = new PresentParameters { Windowed = true, SwapEffect = SwapEffect.Discard, PresentationInterval = PresentInterval.Default, // The device back buffer is not used. BackBufferFormat = Format.Unknown, BackBufferWidth = 1, BackBufferHeight = 1, // Use dummy window handle. DeviceWindowHandle = GetDesktopWindow() }; _device = new DeviceEx(_direct3D, 0, DeviceType.Hardware, IntPtr.Zero, CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve, presentparams); }
private void Initialize3D() { HwndSource hwnd = new HwndSource(0, 0, 0, 0, 0, "D3", IntPtr.Zero); _pp.SwapEffect = SwapEffect.Discard; _pp.DeviceWindowHandle = hwnd.Handle; _pp.Windowed = true; _pp.EnableAutoDepthStencil = true; _pp.BackBufferWidth = Math.Max(100, (int)ActualWidth); _pp.BackBufferHeight = Math.Max(100, (int)ActualHeight); _pp.BackBufferFormat = Format.A8R8G8B8; _pp.AutoDepthStencilFormat = Format.D32SingleLockable; _pp.BackBufferCount = 1; try { var direct3DEx = new Direct3DEx(); Direct3D = direct3DEx; Device = new DeviceEx(direct3DEx, 0, DeviceType.Hardware, hwnd.Handle, CreateFlags.HardwareVertexProcessing, _pp); } catch { // At this point we are pretty much screwed, require DeviceEx for the reset capability MessageBox.Show("Can't start DirectX, so that pretty much discounts doing anything else"); } System.Windows.Media.CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering); }
void Initialise() { if (this.FHandle == (IntPtr)0) { throw (new Exception("No shared texture handle set")); } this.FContext = new Direct3DEx(); this.FHiddenControl = new Control(); this.FHiddenControl.Visible = false; this.FHiddenControl.Width = this.FWidth; this.FHiddenControl.Height = this.FHeight; var flags = CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.PureDevice | CreateFlags.FpuPreserve; this.FDevice = new DeviceEx(FContext, 0, DeviceType.Hardware, this.FHiddenControl.Handle, flags, new PresentParameters() { BackBufferWidth = this.FWidth, BackBufferHeight = this.FHeight }); this.FTextureShared = new Texture(this.FDevice, this.FWidth, this.FHeight, 1, FUsage, FFormat, Pool.Default, ref this.FHandle); this.FTextureCopied = new Texture(this.FDevice, this.FWidth, this.FHeight, 1, Usage.RenderTarget, FFormat, Pool.Default); var description = FTextureCopied.GetLevelDescription(0); this.FSurfaceOffscreen = Surface.CreateOffscreenPlainEx(FDevice, FWidth, FHeight, description.Format, Pool.SystemMemory, Usage.None); this.FInitialised = true; }
protected override bool BeginRenderBrushOverride(PrimitiveBuffer primitiveContext, RenderContext renderContext) { ISlimDXVideoPlayer player; if (!GetPlayer(out player)) { return(false); } if (!RefreshEffectParameters(player)) { return(false); } lock (player.SurfaceLock) { Surface playerSurface = player.Surface; if (playerSurface == null) { return(false); } DeviceEx device = SkinContext.Device; SurfaceDescription desc = playerSurface.Description; SurfaceDescription?textureDesc = _texture == null ? new SurfaceDescription?() : _texture.GetLevelDescription(0); if (!textureDesc.HasValue || textureDesc.Value.Width != desc.Width || textureDesc.Value.Height != desc.Height) { TryDispose(ref _texture); _texture = new Texture(device, desc.Width, desc.Height, 1, Usage.RenderTarget, Format.A8R8G8B8, Pool.Default); } using (Surface target = _texture.GetSurfaceLevel(0)) device.StretchRectangle(playerSurface, target, TextureFilter.None); } return(_imageContext.StartRender(renderContext, _scaledVideoSize, _texture, _videoTextureClip, BorderColor.ToArgb(), _lastFrameData)); }
public void StartDirect3D(Window window) { Direct3DContext = new Direct3DEx(); var presentParameters = new PresentParameters { Windowed = true, SwapEffect = SwapEffect.Discard, DeviceWindowHandle = new WindowInteropHelper(window).Handle, PresentationInterval = SharpDX.Direct3D9.PresentInterval.Default }; Direct3DDevice = new DeviceEx(Direct3DContext, 0, DeviceType.Hardware, IntPtr.Zero, CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve, presentParameters); // Create the device using the main window handle, and a placeholder size (1,1). // The actual size doesn't matter because whenever we render using this GraphicsDevice, // we will make sure the back buffer is large enough for the window we're rendering into. // Also, the handle doesn't matter because we call GraphicsDevice.Present(...) with the // actual window handle to render into. GraphicsDevice = CreateGraphicsDevice(new WindowInteropHelper(window).Handle, 1, 1); DeviceCreated?.Invoke(this, EventArgs.Empty); }
/// <summary> /// Constructor for the hooking class. /// Creates the Direct3D9/Direct3D9Ex devices inside the function to get their /// native pointer for hooking purposes. /// </summary> public DX9Hook() { // Obtain the pointer to the IDirect3DDevice9 instance // by creating our own blank windows form and creating a IDirect3DDevice9 // targeting that form. The returned device should be the same one as used by the game. using (Direct3D direct3D = new Direct3D()) using (Form renderForm = new Form()) using (Device device = new Device(direct3D, 0, DeviceType.NullReference, IntPtr.Zero, CreateFlags.HardwareVertexProcessing, new PresentParameters() { BackBufferWidth = 1, BackBufferHeight = 1, DeviceWindowHandle = renderForm.Handle })) { DirectXFunctions = new VirtualFunctionTable(device.NativePointer, Enum.GetNames(typeof(Direct3DDevice9)).Length); } // Obtain the pointer to the IDirect3DDevice9Ex instance // by creating our own blank windows form and creating a IDirect3DDevice9Ex // targeting that form. The returned device should be the same one as used by the game. using (Direct3DEx direct3D = new Direct3DEx()) using (var renderForm = new Form()) using (DeviceEx device = new DeviceEx(direct3D, 0, DeviceType.NullReference, IntPtr.Zero, CreateFlags.HardwareVertexProcessing, new PresentParameters() { BackBufferWidth = 1, BackBufferHeight = 1, DeviceWindowHandle = renderForm.Handle })) { try { DirectXFunctions.TableEntries.AddRange(VirtualFunctionTable.GetObjectVTableAddresses(device.NativePointer, Enum.GetNames(typeof(Direct3DDevice9Ex)).Length)); SupportsDirect3D9Ex = true; } catch { SupportsDirect3D9Ex = false; } } }
// Used in the overlay unsafe int PresentExHook(IntPtr devicePtr, SharpDX.Rectangle *pSourceRect, SharpDX.Rectangle *pDestRect, IntPtr hDestWindowOverride, IntPtr pDirtyRegion, Present dwFlags) { _isUsingPresent = true; DeviceEx device = (DeviceEx)devicePtr; DoCaptureRenderTarget(device, "PresentEx"); // Region region = new Region(pDirtyRegion); if (pSourceRect == null || *pSourceRect == SharpDX.Rectangle.Empty) { device.PresentEx(dwFlags); } else { if (hDestWindowOverride != IntPtr.Zero) { device.PresentEx(dwFlags, *pSourceRect, *pDestRect, hDestWindowOverride); } else { device.PresentEx(dwFlags, *pSourceRect, *pDestRect); } } return(SharpDX.Result.Ok.Code); }
/// <summary> /// Initializes a new instance of the <see cref="D3D11Image"/> class. Associates an D3D11 render target with the current instance. /// </summary> /// <param name="device">A valid D3D9 DeviceEx.</param> /// <param name="renderTarget">A valid D3D11 render target. It must be created with the "Shared" flag.</param> public D3D11Image(DeviceEx device, Texture2D renderTarget) { using (var resource = renderTarget.QueryInterface <DXGIResource>()) { var handle = resource.SharedHandle; this.texture = new Texture( device, renderTarget.Description.Width, renderTarget.Description.Height, 1, Usage.RenderTarget, Format.A8R8G8B8, Pool.Default, ref handle); } using (var surface = this.texture.GetSurfaceLevel(0)) { this.textureSurfaceHandle = surface.NativePointer; this.TrySetBackbufferPointer(this.textureSurfaceHandle); } this.IsFrontBufferAvailableChanged += this.HandleIsFrontBufferAvailableChanged; }
public KinectD3DImage() { if (App.Current.MainWindow != null) { IntPtr window = new WindowInteropHelper(App.Current.MainWindow).Handle; var presentparams = new SharpDX.Direct3D9.PresentParameters { Windowed = true, SwapEffect = SharpDX.Direct3D9.SwapEffect.Discard, DeviceWindowHandle = window, PresentationInterval = PresentInterval.Immediate, }; const CreateFlags deviceFlags = CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve; this.direct3d = new Direct3DEx(); this.imagingFactory = new ImagingFactory(); this.device = Capture.Direct3D11Helper.CreateDevice(); this.d3dDevice = Capture.Direct3D11Helper.CreateSharpDXDevice(this.device); this.d9device = new DeviceEx(this.direct3d, 0, DeviceType.Hardware, IntPtr.Zero, deviceFlags, presentparams); this.IsFrontBufferAvailableChanged += this.GraphicItemD3DImageIsFrontBufferAvailableChanged; this.renderEvent = new ManualResetEventSlim(false); var renderThread = new Thread(this.RenderThread); renderThread.Start(); } }
void InitD3D9() { if (NumActiveImages == 0) { D3DContext = new Direct3DEx(); PresentParameters pp = new PresentParameters(); pp.Windowed = true; pp.SwapEffect = SwapEffect.Discard; pp.DeviceWindowHandle = GetDesktopWindow(); pp.PresentationInterval = PresentInterval.Immediate; pp.Multisample = MultisampleType.None; pp.MultisampleQuality = 0; var format = Format.A8R8G8B8; var adapter = 0; // check for 4xAA if (D3DContext.CheckDeviceMultisampleType(adapter, DeviceType.Hardware, format, true, MultisampleType.FourSamples)) { pp.Multisample = MultisampleType.FourSamples; } // check fo 2xAA else if (D3DContext.CheckDeviceMultisampleType(adapter, DeviceType.Hardware, format, true, MultisampleType.TwoSamples)) { pp.Multisample = MultisampleType.TwoSamples; } D3DDevice = new DeviceEx(D3DContext, adapter, DeviceType.Hardware, IntPtr.Zero, CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve, pp); } }
// private bool IsDeviceReady(Device device) // { // var cooplevel = device.TestCooperativeLevel(); // if (cooplevel.Code != ResultCode.Success.Code) // { // return false; // } // return true; // } private int ResetExHook(IntPtr devicePtr, ref PresentParameters presentparameters, DisplayModeEx displayModeEx) { int hresult = Result.Ok.Code; DeviceEx device = (DeviceEx)devicePtr; try { if (!hooksStarted) { hresult = Direct3DDeviceEx_ResetExHook.Original(devicePtr, ref presentparameters, displayModeEx); return(hresult); } ClearData(); hresult = Direct3DDeviceEx_ResetExHook.Original(devicePtr, ref presentparameters, displayModeEx); if (currentDevice != devicePtr) { hooksStarted = false; currentDevice = devicePtr; } } catch (Exception ex) { DebugMessage(ex.ToString()); } return(hresult); }
/// <summary> /// Creates a new instance of <see cref="SharpDXElement"/> class. /// Initializes the D3D9 runtime. /// </summary> public SharpDXElement() { image = new D3DImage(); var presentparams = new PresentParameters { Windowed = true, SwapEffect = SwapEffect.Discard, DeviceWindowHandle = GetDesktopWindow(), PresentationInterval = PresentInterval.Default }; direct3D = new Direct3DEx(); device9 = new DeviceEx(direct3D, 0, DeviceType.Hardware, IntPtr.Zero, CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve, presentparams); resizeDelayTimer = new DispatcherTimer(DispatcherPriority.Normal); resizeDelayTimer.Interval = SendResizeDelay; resizeDelayTimer.Tick += HandleResizeDelayTimerTick; SizeChanged += HandleSizeChanged; Unloaded += HandleUnloaded; }
private void CleanUp() { logger.Verb("D3DImageRenderer::CleanUp()"); //System.Windows.Media.CompositionTarget.Rendering -= CompositionTarget_Rendering; if (surface != null) { surface.Dispose(); surface = null; } if (direct3D != null) { direct3D.Dispose(); direct3D = null; } if (device != null) { device.Dispose(); device = null; } if (waitEvent != null) { waitEvent.Dispose(); waitEvent = null; } state = RendererState.Closed; }
public D3D11Image(Texture2D renderTarget) { DeviceEx device = D3D9.Value.Device; using (var resource = renderTarget.QueryInterface <SharpDX.DXGI.Resource>()) { IntPtr sharedHandle = resource.SharedHandle; _texture = new Texture( device, renderTarget.Description.Width, renderTarget.Description.Height, 1, Usage.RenderTarget, Format.A8R8G8B8, Pool.Default, ref sharedHandle); } using (Surface surfaceLevel = _texture.GetSurfaceLevel(0)) { _textureSurfaceHandle = surfaceLevel.NativePointer; TrySetBackbufferPointer(_textureSurfaceHandle); } IsFrontBufferAvailableChanged += OnIsFrontBufferAvailableChanged; }
// - private methods ------------------------------------------------------------- private void StartD3D() { var presentParams = GetPresentParameters(); var createFlags = CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve; D3DContext = new Direct3DEx(); D3DDevice = new DeviceEx(D3DContext, 0, DeviceType.Hardware, IntPtr.Zero, createFlags, presentParams); }
// Used in the overlay private unsafe Int32 PresentExHook(IntPtr devicePtr, RawRectangle *sourceRect, RawRectangle *destRect, IntPtr destWindowOverride, IntPtr dirtyRegion, Present presentFlags) { this.IsUsingPresent = true; DeviceEx device = (DeviceEx)devicePtr; this.DoCaptureRenderTarget(device, "PresentEx"); return(this.Direct3DDeviceExPresentExHook.Original(devicePtr, sourceRect, destRect, destWindowOverride, dirtyRegion, presentFlags)); }
// Used in the overlay unsafe int PresentExHook(IntPtr devicePtr, SharpDX.Rectangle *pSourceRect, SharpDX.Rectangle *pDestRect, IntPtr hDestWindowOverride, IntPtr pDirtyRegion, Present dwFlags) { _isUsingPresent = true; DeviceEx device = (DeviceEx)devicePtr; DoCaptureRenderTarget(device, "PresentEx"); return(Direct3DDeviceEx_PresentExHook.Original(devicePtr, pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion, dwFlags)); }
public GraphicsInteropImageSource() { var presentParams = GetPresentParameters(); var createFlags = CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve; D3DContext = new Direct3DEx(); D3DDevice = new DeviceEx(D3DContext, 0, DeviceType.Hardware, IntPtr.Zero, createFlags, presentParams); }
/// <summary> /// Constructs a <see cref="SubtitleRenderer"/> instance. /// </summary> public SubtitleRenderer(Action onTextureInvalidated) { _onTextureInvalidated = onTextureInvalidated; _subtitles = new LinkedList <Subtitle>(); //instance.textCallBack = new TextSubtitleCallback(instance.OnTextSubtitle); _resetCallBack = Reset; _updateTimeoutCallBack = UpdateTimeout; _device = SkinContext.Device; }
public DwmCapture(IntPtr hWnd) { _captureHwnd = hWnd; #region Initialise the Direct3D device int adapterOrdinal = 0; _d3dEx = new Direct3DEx(); _adapterLuid = _d3dEx.GetAdapterLuid(adapterOrdinal); var presentParams = new PresentParameters { PresentFlags = PresentFlags.LockableBackBuffer, Windowed = true, BackBufferFormat = Format.A8R8G8B8, SwapEffect = SwapEffect.Flip }; _deviceEx = new DeviceEx(_d3dEx, adapterOrdinal, DeviceType.Hardware, _captureHwnd, SlimDX.Direct3D9.CreateFlags.Multithreaded | SlimDX.Direct3D9.CreateFlags.SoftwareVertexProcessing, presentParams); #endregion #region Setup the shared surface (using DWM) uint format = 0; IntPtr pSharedHandle = IntPtr.Zero; int hr = NativeMethods.GetSharedSurface(_captureHwnd, _adapterLuid, 0, 0, ref format, out pSharedHandle, 0); NativeMethods.UpdateWindowShared(_captureHwnd, 0, 0, 0, IntPtr.Zero, IntPtr.Zero); RECT winRect; NativeMethods.GetWindowRect(_captureHwnd, out winRect); Size size = new Size(winRect.Right - winRect.Left, winRect.Bottom - winRect.Top); /* Hack because SlimDX does not let you specify a shared handle for creating shared resources we * have to create an IDirect3DDevice9 reference to the device instead */ IDirect3DDevice9 devEx = (IDirect3DDevice9)Marshal.GetObjectForIUnknown(_deviceEx.ComPointer); IntPtr pTexture; devEx.CreateTexture((int)size.Width, (int)size.Height, 1, 1, format, 0, out pTexture, ref pSharedHandle); Texture texture = Texture.FromPointer(pTexture); _sharedSurface = texture.GetSurfaceLevel(0); _renderTarget = Surface.CreateRenderTarget(_deviceEx, (int)size.Width, (int)size.Height, Format.X8R8G8B8, MultisampleType.None, 0, false); _deviceEx.SetRenderTarget(0, _renderTarget); Surface.FromSurface(_renderTarget, _sharedSurface, Filter.None, 0); _systemMemorySurface = Surface.CreateOffscreenPlain(_deviceEx, (int)size.Width, (int)size.Height, Format.X8R8G8B8, Pool.SystemMemory); #endregion }
// - private methods ------------------------------------------------------------- private void StartD3D() { if (ActiveClients != 0) { return; } D3DContext = new Direct3DEx(); D3DDevice = new DeviceEx(D3DContext, 0, DeviceType.Hardware, IntPtr.Zero, CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve, GetPresentParameters()); }
/// <summary> /// Creates or re-creates the DirectX device and the backbuffer. This is necessary in the initialization phase /// of the SkinEngine and after a parameter was changed which affects the DX device creation. /// </summary> internal static void DoReCreateDevice_MainThread() { try { // Note that only the thread which handles window messages is allowed to call CreateDevice and Reset // (see http://msdn.microsoft.com/en-us/library/windows/desktop/bb147224%28v=vs.85%29.aspx ) ServiceRegistration.Get <ILogger>().Debug("GraphicsDevice: Initializing DirectX"); MPDirect3D.Load(); // Cleanup-part: Only necessary during re-initialization UIResourcesHelper.ReleaseUIResources(); if (_backBuffer != null) { _backBuffer.Dispose(); } if (_device != null) { _device.Dispose(); } _device = _setup.SetupDirectX(); // End cleanup part SetupRenderStrategies(); SetupRenderPipelines(); Capabilities deviceCapabilities = _device.Capabilities; _backBuffer = _device.GetRenderTarget(0); _device.MaximumFrameLatency = _setup.PresentParameters.BackBufferCount; // Enables the device to queue as many frames as we have backbuffers defined int ordinal = deviceCapabilities.AdapterOrdinal; AdapterInformation adapterInfo = MPDirect3D.Direct3D.Adapters[ordinal]; DisplayMode currentMode = adapterInfo.CurrentDisplayMode; AdaptTargetFrameRateToDisplayMode(currentMode); LogScreenMode(currentMode); bool firstTimeInitialization = _dxCapabilities == null; _dxCapabilities = DxCapabilities.RequestCapabilities(deviceCapabilities, currentMode); if (firstTimeInitialization) { if (!_dxCapabilities.SupportsShaders) { string text = String.Format("MediaPortal 2 needs a graphics card wich supports shader model 2.0\nYour card does NOT support this.\nMediaportal 2 will continue but migh run slow"); MessageBox.Show(text, "GraphicAdapter", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } SetRenderState(); UIResourcesHelper.ReallocUIResources(); } catch (Exception ex) { ServiceRegistration.Get <ILogger>().Critical("GraphicsDevice: Failed to setup DirectX", ex); Environment.Exit(0); } }
// - private methods ------------------------------------------------------------- private void StartD3D() { if (Dx11ImageSource.ActiveClients != 0) { return; } var presentParams = GetPresentParameters(); var createFlags = CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve; Dx11ImageSource.D3DContext = new Direct3DEx(); Dx11ImageSource.D3DDevice = new DeviceEx(D3DContext, 0, DeviceType.Hardware, IntPtr.Zero, createFlags, presentParams); }
public void ReleaseD3D() { if (device != null) { if (!device.Disposed) { device.Dispose(); device = null; } } d3dimage.Lock(); d3dimage.SetBackBuffer(D3DResourceType.IDirect3DSurface9, IntPtr.Zero); d3dimage.Unlock(); }
public GraphicsDeviceService() { PresentParameters pp = new PresentParameters { SwapEffect = SwapEffect.Discard, DeviceWindowHandle = IntPtr.Zero,// windows[0].WindowHandle, Windowed = true, BackBufferWidth = 1, BackBufferHeight = 1, BackBufferFormat = Format.Unknown }; Device = new DeviceEx( new Direct3DEx(), 0, DeviceType.Hardware, IntPtr.Zero, //windows[0].WindowHandle, CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve, pp); }
/// <summary> /// Initializes the Device /// </summary> private void InitializeDevice(int width, int height) { if (DirectXStatus != DirectXStatus.Available) return; Debug.Assert(Direct3D != null); ReleaseDevice(); IntPtr windowHandle = (new Form()).Handle; //HwndSource hwnd = new HwndSource(0, 0, 0, 0, 0, width, height, "SlimDXControl", IntPtr.Zero); presentParameters = new PresentParameters(); if (UseDeviceEx) presentParameters.SwapEffect = SwapEffect.Discard; else presentParameters.SwapEffect = SwapEffect.Copy; presentParameters.DeviceWindowHandle = windowHandle; presentParameters.Windowed = true; presentParameters.BackBufferWidth = Math.Max(width, 1); presentParameters.BackBufferHeight = Math.Max(height, 1); presentParameters.BackBufferFormat = backbufferFormat; presentParameters.AutoDepthStencilFormat = depthStencilFormat; presentParameters.EnableAutoDepthStencil = true; presentParameters.PresentationInterval = PresentInterval.Immediate; PresentParameters.Multisample = MultisampleType.None; IsAntialiased = false; int qualityLevels; if (Direct3D.CheckDeviceMultisampleType(0, DeviceType.Hardware, backbufferFormat, true, MultisampleType.EightSamples, out qualityLevels)) { PresentParameters.Multisample = MultisampleType.EightSamples; PresentParameters.MultisampleQuality = qualityLevels - 1; IsAntialiased = true; } else if (Direct3D.CheckDeviceMultisampleType(0, DeviceType.Hardware, backbufferFormat, true, MultisampleType.FourSamples, out qualityLevels)) { PresentParameters.Multisample = MultisampleType.FourSamples; PresentParameters.MultisampleQuality = qualityLevels - 1; IsAntialiased = false; } try { if (UseDeviceEx) { deviceEx = new DeviceEx((Direct3DEx)Direct3D, 0, DeviceType.Hardware, windowHandle, createFlags, presentParameters); } else { device = new Device(Direct3D, 0, DeviceType.Hardware, windowHandle, createFlags, presentParameters); } } catch (Direct3D9Exception) { DirectXStatus = DirectXStatus.Unavailable_Unknown; return; } return; }
internal static void Dispose() { if (_backBuffer != null) _backBuffer.Dispose(); _backBuffer = null; if (_device != null) _device.Dispose(); _device = null; MPDirect3D.Unload(); _renderAndResourceAccessLock.Dispose(); }
/// <summary> /// Creates or re-creates the DirectX device and the backbuffer. This is necessary in the initialization phase /// of the SkinEngine and after a parameter was changed which affects the DX device creation. /// </summary> internal static void DoReCreateDevice_MainThread() { try { // Note that only the thread which handles window messages is allowed to call CreateDevice and Reset // (see http://msdn.microsoft.com/en-us/library/windows/desktop/bb147224%28v=vs.85%29.aspx ) ServiceRegistration.Get<ILogger>().Debug("GraphicsDevice: Initializing DirectX"); MPDirect3D.Load(); // Cleanup-part: Only necessary during re-initialization UIResourcesHelper.ReleaseUIResources(); if (_backBuffer != null) _backBuffer.Dispose(); if (_device != null) _device.Dispose(); _device = _setup.SetupDirectX(); // End cleanup part SetupRenderStrategies(); SetupRenderPipelines(); Capabilities deviceCapabilities = _device.Capabilities; _backBuffer = _device.GetRenderTarget(0); _device.MaximumFrameLatency = _setup.PresentParameters.BackBufferCount; // Enables the device to queue as many frames as we have backbuffers defined int ordinal = deviceCapabilities.AdapterOrdinal; AdapterInformation adapterInfo = MPDirect3D.Direct3D.Adapters[ordinal]; DisplayMode currentMode = adapterInfo.CurrentDisplayMode; AdaptTargetFrameRateToDisplayMode(currentMode); LogScreenMode(currentMode); bool firstTimeInitialization = _dxCapabilities == null; _dxCapabilities = DxCapabilities.RequestCapabilities(deviceCapabilities, currentMode); if (firstTimeInitialization) { if (!_dxCapabilities.SupportsShaders) { string text = String.Format("MediaPortal 2 needs a graphics card wich supports shader model 2.0\nYour card does NOT support this.\nMediaportal 2 will continue but migh run slow"); MessageBox.Show(text, "GraphicAdapter", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } SetRenderState(); UIResourcesHelper.ReallocUIResources(); } catch (Exception ex) { ServiceRegistration.Get<ILogger>().Critical("GraphicsDevice: Failed to setup DirectX", ex); Environment.Exit(0); } }
public EVRCallback(RenderDlgt renderDlgt, Action onTextureInvalidated) { _onTextureInvalidated = onTextureInvalidated; _renderDlgt = renderDlgt; _device = SkinContext.Device; }
void Allocate(int width, int height, Format format, Usage usage) { this.Deallocate(); var flags = CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.PureDevice | CreateFlags.FpuPreserve; this.FDevice = new DeviceEx(FContext, 0, DeviceType.Hardware, this.FHiddenControl.Handle, flags, new PresentParameters() { BackBufferWidth = width, BackBufferHeight = height }); this.FWidth = width; this.FHeight = height; this.FUsage = usage; this.FFormat = format; this.FInitialised = true; }
/// <summary> /// Change the size of the rendering. /// </summary> private void ResizeRendering() { if (_gl.IsTexture(_glRenderBufferName) == 1) _gl.DeleteTextures(1, new uint[] { _glRenderBufferName }); if (_gl.IsFramebufferEXT(_framebuffer)) _gl.DeleteFramebuffersEXT(1, new uint[] { _framebuffer }); uint[] names = new uint[1]; _gl.GenTextures(1, names); _glRenderBufferName = names[0]; _gl.GenFramebuffersEXT(1, names); _framebuffer = names[0]; if (_texture != null) { _gl.DXUnregisterObjectNV(_dxDeviceGLHandle, _glRenderBufferHandle); _texture.Dispose(); } if (_renderBuffer != null) _renderBuffer.Dispose(); if (_backBuffer != null) _backBuffer.Dispose(); if (_device != null) _device.Dispose(); if (_dxDeviceGLHandle != IntPtr.Zero) _gl.DXCloseDeviceNV(_dxDeviceGLHandle); PresentParameters pp = new PresentParameters(); pp.DeviceWindowHandle = _hwnd; pp.Windowed = true; pp.SwapEffect = SwapEffect.Flip; pp.PresentationInterval = PresentInterval.Default; pp.BackBufferWidth = (int)ActualWidth; pp.BackBufferHeight = (int)ActualHeight; pp.BackBufferFormat = Format.X8R8G8B8; pp.BackBufferCount = 1; _device = new DeviceEx(_d3dex, 0, DeviceType.Hardware, _hwnd, CreateFlags.HardwareVertexProcessing | CreateFlags.PureDevice | CreateFlags.FpuPreserve | CreateFlags.Multithreaded, pp); _gl.MakeCurrent(); _dxDeviceGLHandle = _gl.DXOpenDeviceNV(_device.ComPointer); _texture = new Texture(_device, (int)ActualWidth, (int)ActualHeight, 1, Usage.None, Format.X8R8G8B8, Pool.Default); _renderBuffer = _texture.GetSurfaceLevel(0); _glRenderBufferHandle = _gl.DXRegisterObjectNV(_dxDeviceGLHandle, _texture.ComPointer, _glRenderBufferName, OpenGL.GL_TEXTURE_2D, OpenGL.WGL_ACCESS_READ_WRITE_NV); _gl.DXLockObjectsNV(_dxDeviceGLHandle, new IntPtr[] { _glRenderBufferHandle }); _gl.BindFramebufferEXT(OpenGL.GL_FRAMEBUFFER_EXT, _framebuffer); _gl.FramebufferTexture2DEXT(OpenGL.GL_FRAMEBUFFER_EXT, OpenGL.GL_COLOR_ATTACHMENT0_EXT, OpenGL.GL_TEXTURE_2D, _glRenderBufferName, 0); uint status = _gl.CheckFramebufferStatusEXT(OpenGL.GL_FRAMEBUFFER_EXT); switch (status) { case OpenGL.GL_FRAMEBUFFER_COMPLETE_EXT: break; case OpenGL.GL_FRAMEBUFFER_UNSUPPORTED_EXT: throw new InvalidOperationException("Not supported framebuffer-format!"); default: throw new InvalidOperationException(status.ToString()); } _gl.SetDimensions((int)ActualWidth, (int)ActualHeight); _gl.Viewport(0, 0, (int)ActualWidth, (int)ActualHeight); _gl.MatrixMode(OpenGL.GL_PROJECTION); _gl.LoadIdentity(); _gl.Ortho(0, ActualWidth, ActualHeight, 0, 0, 1); _gl.MatrixMode(OpenGL.GL_MODELVIEW); _gl.LoadIdentity(); // Pixel-position correction, look there: // http://msdn.microsoft.com/en-us/library/windows/desktop/dd374282(v=vs.85).aspx _gl.Translate(0.375, 0.375, 0); _gl.DXUnlockObjectsNV(_dxDeviceGLHandle, new IntPtr[] { _glRenderBufferHandle }); _image.Lock(); _backBuffer = _device.GetBackBuffer(0, 0); _image.SetBackBuffer(D3DResourceType.IDirect3DSurface9, _backBuffer.ComPointer); _image.Unlock(); }
private void StartD3D() { if (DX11ImageSource.ActiveClients != 0) return; D3DContext = new Direct3DEx(); PresentParameters presentparams = new PresentParameters(); presentparams.Windowed = true; presentparams.SwapEffect = SwapEffect.Discard; presentparams.DeviceWindowHandle = GetDesktopWindow(); presentparams.PresentationInterval = PresentInterval.Default; DX11ImageSource.D3DDevice = new DeviceEx(D3DContext, 0, DeviceType.Hardware, IntPtr.Zero, CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve, presentparams); }
/// <summary> /// Initializes the various Direct3D objects we'll be using. /// </summary> public bool Initialize(bool startThread) { try { StartThread = startThread; ReleaseD3D(); HwndSource hwnd = new HwndSource(0, 0, 0, 0, 0, "test", IntPtr.Zero); pp = new PresentParameters(); pp.SwapEffect = SwapEffect.Discard; pp.DeviceWindowHandle = hwnd.Handle; pp.Windowed = true; pp.BackBufferWidth = (int)ActualWidth; pp.BackBufferHeight = (int)ActualHeight; pp.BackBufferFormat = Format.X8R8G8B8; if (useDeviceEx) { deviceEx = new DeviceEx((Direct3DEx)Direct3D, 0, DeviceType.Hardware, hwnd.Handle, CreateFlags.HardwareVertexProcessing, pp); } else { device = new Device(Direct3D, 0, DeviceType.Hardware, hwnd.Handle, CreateFlags.HardwareVertexProcessing, pp); } // call the users one OnDeviceCreated(EventArgs.Empty); OnDeviceReset(EventArgs.Empty); // only if startThread is true if (StartThread) { CompositionTarget.Rendering += OnRendering; d3dimage.IsFrontBufferAvailableChanged += new DependencyPropertyChangedEventHandler(OnIsFrontBufferAvailableChanged); } d3dimage.Lock(); d3dimage.SetBackBuffer(D3DResourceType.IDirect3DSurface9, Device.GetBackBuffer(0, 0).ComPointer); d3dimage.Unlock(); CustomInitialize(); return true; } catch (Exception exc) { MessageBox.Show(exc.Message); return false; } }
/// <summary> /// Creates the DirectX device. /// </summary> public DeviceEx CreateDevice(D3DConfiguration configuration) { GraphicsAdapterInfo adapterInfo = configuration.AdapterInfo; GraphicsDeviceInfo deviceInfo = configuration.DeviceInfo; // Set up the presentation parameters _presentParams = BuildPresentParamsFromSettings(_currentGraphicsConfiguration = configuration); if ((deviceInfo.Caps.PrimitiveMiscCaps & PrimitiveMiscCaps.NullReference) != 0) // Warn user about null ref device that can't render anything HandleException(new NullReferenceDeviceException(), ApplicationMessage.None); CreateFlags createFlags; if (configuration.DeviceCombo.VertexProcessingTypes.Contains(VertexProcessingType.PureHardware)) createFlags = CreateFlags.HardwareVertexProcessing; // | CreateFlags.PureDevice; else if (configuration.DeviceCombo.VertexProcessingTypes.Contains(VertexProcessingType.Hardware)) createFlags = CreateFlags.HardwareVertexProcessing; else if (configuration.DeviceCombo.VertexProcessingTypes.Contains(VertexProcessingType.Mixed)) createFlags = CreateFlags.MixedVertexProcessing; else if (configuration.DeviceCombo.VertexProcessingTypes.Contains(VertexProcessingType.Software)) createFlags = CreateFlags.SoftwareVertexProcessing; else throw new ApplicationException(); ServiceRegistration.Get<ILogger>().Info("DirectX: Using adapter: {0} {1} {2}", configuration.AdapterInfo.AdapterOrdinal, MPDirect3D.Direct3D.Adapters[configuration.AdapterInfo.AdapterOrdinal].Details.Description, configuration.DeviceInfo.DevType); // Create the device DeviceEx result = new DeviceEx(MPDirect3D.Direct3D, configuration.AdapterInfo.AdapterOrdinal, configuration.DeviceInfo.DevType, _renderTarget.Handle, createFlags | CreateFlags.Multithreaded | CreateFlags.EnablePresentStatistics, _presentParams); // When moving from fullscreen to windowed mode, it is important to // adjust the window size after recreating the device rather than // beforehand to ensure that you get the window size you want. For // example, when switching from 640x480 fullscreen to windowed with // a 1000x600 window on a 1024x768 desktop, it is impossible to set // the window size to 1000x600 until after the display mode has // changed to 1024x768, because windows cannot be larger than the // desktop. StringBuilder sb = new StringBuilder(); // Store device description if (deviceInfo.DevType == DeviceType.Reference) sb.Append("REF"); else if (deviceInfo.DevType == DeviceType.Hardware) sb.Append("HAL"); else if (deviceInfo.DevType == DeviceType.Software) sb.Append("SW"); if (deviceInfo.DevType == DeviceType.Hardware) { sb.Append(": "); sb.Append(adapterInfo.AdapterDetails.Description); } ServiceRegistration.Get<ILogger>().Info("DirectX: {0}", sb.ToString()); return result; }
/// <summary> /// Initializes Direct3D9 and creates a static D3D9 device for interop /// </summary> private static void CreateDevice() { m_direct3D = new Direct3DEx(); /* Create the device present parameters */ var param = new PresentParameters(); param.Windowed = true; param.SwapEffect = SwapEffect.Discard; param.BackBufferFormat = Format.A8R8G8B8; param.PresentationInterval = PresentInterval.Immediate; /* Creates the Direct3D9Ex device. This must be an "Ex" device * to allow resource sharing with D3D10 */ m_device = new DeviceEx(m_direct3D, 0, DeviceType.Hardware, GetDesktopWindow(), CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve, param); }
public Device(IntPtr handle, int width, int height) { if (handle == IntPtr.Zero) throw new ArgumentException("Value must be a valid window handle", "handle"); if (GetSystemMetrics(SM_REMOTESESSION) != 0) throw new Exception("We can't run at all under terminal services"); int renderingTier = (RenderCapability.Tier >> 16); if (renderingTier < 2) throw new Exception("Render capability check failed, low tier=" + renderingTier); // Create D3D try { this.direct3dEx = new Direct3DEx(); UseDeviceEx = true; } catch { this.direct3d = new Direct3D(); UseDeviceEx = false; } // Create device Result result; if (!Direct3D.CheckDeviceType(0, DeviceType.Hardware, this.adapterFormat, this.backbufferFormat, true, out result)) throw new Exception("CheckDeviceType failed: " + result.ToString()); if (!Direct3D.CheckDepthStencilMatch(0, DeviceType.Hardware, this.adapterFormat, this.backbufferFormat, this.depthStencilFormat, out result)) throw new Exception("CheckDepthStencilMatch failed: " + result.ToString()); Capabilities deviceCaps = Direct3D.GetDeviceCaps(0, DeviceType.Hardware); if ((deviceCaps.DeviceCaps & DeviceCaps.HWTransformAndLight) != 0) this.createFlags |= CreateFlags.HardwareVertexProcessing; else this.createFlags |= CreateFlags.SoftwareVertexProcessing; PresentParams = new PresentParameters() { BackBufferFormat = this.backbufferFormat, BackBufferCount = 1, BackBufferWidth = width, BackBufferHeight = height, Multisample = MultisampleType.None, SwapEffect = SwapEffect.Discard, EnableAutoDepthStencil = true, AutoDepthStencilFormat = this.depthStencilFormat, PresentFlags = PresentFlags.DiscardDepthStencil, PresentationInterval = PresentInterval.Immediate, Windowed = true, DeviceWindowHandle = handle, }; if (UseDeviceEx) { this.deviceEx = new DeviceEx(this.direct3dEx, 0, DeviceType.Hardware, handle, this.createFlags, PresentParams); } else { this.device = new SlimDX.Direct3D9.Device(this.direct3d, 0, DeviceType.Hardware, handle, this.createFlags, PresentParams); } // Create vertex declarations TransformedColoredVertexDecl = new TransformedColoredVertexDecl(this); MeshVertexDecl = new MeshVertexDecl(this); TextureVertexDecl = new TexturedVertexDecl(this); ScreenVertexDecl = new ScreenVertexDecl(this); ScreenVertexBuffer = new VertexBuffer<ScreenVertex>(this); var vertices = new ScreenVertex[] { new ScreenVertex() { Position = new Vector3(-1.0f, -1.0f, 0.5f), UV = new Vector2(0.0f, 1.0f) }, new ScreenVertex() { Position = new Vector3(-1.0f, 1.0f, 0.5f), UV = new Vector2(0.0f, 0.0f) }, new ScreenVertex() { Position = new Vector3(1.0f, -1.0f, 0.5f), UV = new Vector2(1.0f, 1.0f) }, new ScreenVertex() { Position = new Vector3(1.0f, 1.0f, 0.5f), UV = new Vector2(1.0f, 0.0f) }, }; ScreenVertexBuffer.Write(vertices); }
/// <summary> /// Constructs a <see cref="SubtitleRenderer"/> instance. /// </summary> public SubtitleRenderer(Action onTextureInvalidated) { _onTextureInvalidated = onTextureInvalidated; _subtitles = new LinkedList<Subtitle>(); //instance.textCallBack = new TextSubtitleCallback(instance.OnTextSubtitle); _resetCallBack = Reset; _updateTimeoutCallBack = UpdateTimeout; _device = SkinContext.Device; }
void InitD3D9() { if (NumActiveImages == 0) { D3DContext = new Direct3DEx(); PresentParameters presentparams = new PresentParameters(); presentparams.Windowed = true; presentparams.SwapEffect = SwapEffect.Discard; presentparams.DeviceWindowHandle = GetDesktopWindow(); presentparams.PresentationInterval = PresentInterval.Immediate; D3DDevice = new DeviceEx(D3DContext, 0, DeviceType.Hardware, IntPtr.Zero, CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve, presentparams); } }
void InitD3D9() { if (NumActiveImages == 0) { D3DContext = new Direct3DEx(); PresentParameters presentparams = new PresentParameters(); presentparams.Windowed = settings.IsWindowed; presentparams.SwapEffect = SwapEffect.Discard; presentparams.DeviceWindowHandle = GetDesktopWindow(); presentparams.PresentationInterval = PresentInterval.Immediate; if (!settings.IsWindowed) { presentparams.FullScreenRefreshRateInHertz = 120; presentparams.BackBufferHeight = settings.ScreenHeight; presentparams.BackBufferWidth = settings.ScreenWidth; presentparams.BackBufferFormat = TranslateFormat(settings.Format); DisplayModeEx fullScreen = new DisplayModeEx() { Format = TranslateFormat(settings.Format), Width = settings.ScreenWidth, Height = settings.ScreenHeight, RefreshRate = 120 }; D3DDevice = new DeviceEx(D3DContext, 0, DeviceType.Hardware, IntPtr.Zero, CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve, presentparams, fullScreen); } else D3DDevice = new DeviceEx(D3DContext, 0, DeviceType.Hardware, IntPtr.Zero, CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve, presentparams); } }
private bool InitializeD3D() { HwndSource hwnd = new HwndSource(0, 0, 0, 0, 0, "null", IntPtr.Zero); // Create the D3D object. d3d = new Direct3DEx(); PresentParameters pp = new PresentParameters(); pp.BackBufferWidth = 512; pp.BackBufferHeight = 512; pp.BackBufferFormat = Format.Unknown; pp.BackBufferCount = 0; pp.Multisample = MultisampleType.None; pp.MultisampleQuality = 0; pp.SwapEffect = SwapEffect.Discard; pp.DeviceWindowHandle = (IntPtr)0; pp.Windowed = true; pp.EnableAutoDepthStencil = false; pp.AutoDepthStencilFormat = Format.Unknown; pp.PresentationInterval = PresentInterval.Default; bDeviceFound = false; CUdevice[] cudaDevices = null; for (g_iAdapter = 0; g_iAdapter < d3d.AdapterCount; g_iAdapter++) { device = new DeviceEx(d3d, d3d.Adapters[g_iAdapter].Adapter, DeviceType.Hardware, hwnd.Handle, CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded, pp); try { cudaDevices = CudaContext.GetDirectXDevices(device.ComPointer, CUd3dXDeviceList.All, CudaContext.DirectXVersion.D3D9); bDeviceFound = cudaDevices.Length > 0; infoLog.AppendText("> Display Device #" + d3d.Adapters[g_iAdapter].Adapter + ": \"" + d3d.Adapters[g_iAdapter].Details.Description + "\" supports Direct3D9 and CUDA.\n"); break; } catch (CudaException) { //No Cuda device found for this Direct3D9 device infoLog.AppendText("> Display Device #" + d3d.Adapters[g_iAdapter].Adapter + ": \"" + d3d.Adapters[g_iAdapter].Details.Description + "\" supports Direct3D9 but not CUDA.\n"); } } // we check to make sure we have found a cuda-compatible D3D device to work on if (!bDeviceFound) { infoLog.AppendText("No CUDA-compatible Direct3D9 device available"); if (device != null) device.Dispose(); return false; } ctx = new CudaContext(cudaDevices[0], device.ComPointer, CUCtxFlags.BlockingSync, CudaContext.DirectXVersion.D3D9); deviceName.Text = "Device name: " + ctx.GetDeviceName(); // Set projection matrix SlimDX.Matrix matProj = SlimDX.Matrix.OrthoOffCenterLH(0, 1, 1, 0, 0, 1); device.SetTransform(TransformState.Projection, matProj); // Turn off D3D lighting, since we are providing our own vertex colors device.SetRenderState(RenderState.Lighting, false); //Load kernels CUmodule module = ctx.LoadModulePTX("kernel.ptx"); addForces_k = new CudaKernel("addForces_k", module, ctx); advectVelocity_k = new CudaKernel("advectVelocity_k", module, ctx); diffuseProject_k = new CudaKernel("diffuseProject_k", module, ctx); updateVelocity_k = new CudaKernel("updateVelocity_k", module, ctx); advectParticles_k = new CudaKernel("advectParticles_k", module, ctx); d3dimage.Lock(); Surface surf = device.GetBackBuffer(0, 0); d3dimage.SetBackBuffer(D3DResourceType.IDirect3DSurface9, surf.ComPointer); d3dimage.Unlock(); surf.Dispose(); //Setup the "real" frame rate counter. //The cuda counter only measures cuda runtime, not the overhead to actually //show the result via DirectX and WPF. realLastTick = Environment.TickCount; return true; }
void Deallocate() { if (this.FDevice != null) { this.FDevice.Dispose(); this.FDevice = null; } if (this.FTextureShared != null) { this.FTextureShared.Dispose(); this.FTextureShared = null; } foreach(var saver in FSavers) { saver.Dispose(); } FSavers.Clear(); FInitialised = false; }
private void InitializeD3D() { // Create the D3D object. d3d = new Direct3DEx(); PresentParameters pp = new PresentParameters(); pp.BackBufferWidth = 512; pp.BackBufferHeight = 512; pp.BackBufferFormat = Format.Unknown; pp.BackBufferCount = 0; pp.Multisample = MultisampleType.None; pp.MultisampleQuality = 0; pp.SwapEffect = SwapEffect.Discard; pp.DeviceWindowHandle = panel1.Handle; pp.Windowed = true; pp.EnableAutoDepthStencil = false; pp.AutoDepthStencilFormat = Format.Unknown; pp.PresentationInterval = PresentInterval.Default; bDeviceFound = false; CUdevice[] cudaDevices = null; for (g_iAdapter = 0; g_iAdapter < d3d.AdapterCount; g_iAdapter++) { device = new DeviceEx(d3d, d3d.Adapters[g_iAdapter].Adapter, DeviceType.Hardware, panel1.Handle, CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded, pp); try { cudaDevices = CudaContext.GetDirectXDevices(device.ComPointer, CUd3dXDeviceList.All, CudaContext.DirectXVersion.D3D9); bDeviceFound = cudaDevices.Length > 0; Console.WriteLine("> Display Device #" + d3d.Adapters[g_iAdapter].Adapter + ": \"" + d3d.Adapters[g_iAdapter].Details.Description + "\" supports Direct3D9 and CUDA."); break; } catch (CudaException) { //No Cuda device found for this Direct3D9 device Console.WriteLine("> Display Device #" + d3d.Adapters[g_iAdapter].Adapter + ": \"" + d3d.Adapters[g_iAdapter].Details.Description + "\" supports Direct3D9 but not CUDA."); } } // we check to make sure we have found a cuda-compatible D3D device to work on if (!bDeviceFound) { Console.WriteLine("No CUDA-compatible Direct3D9 device available"); if (device != null) device.Dispose(); Close(); return; } ctx = new CudaContext(cudaDevices[0], device.ComPointer, CUCtxFlags.BlockingSync, CudaContext.DirectXVersion.D3D9); // Set projection matrix SlimDX.Matrix matProj = SlimDX.Matrix.OrthoOffCenterLH(0, 1, 1, 0, 0, 1); device.SetTransform(TransformState.Projection, matProj); // Turn off D3D lighting, since we are providing our own vertex colors device.SetRenderState(RenderState.Lighting, false); //Load kernels CUmodule module = ctx.LoadModulePTX("kernel.ptx"); addForces_k = new CudaKernel("addForces_k", module, ctx); advectVelocity_k = new CudaKernel("advectVelocity_k", module, ctx); diffuseProject_k = new CudaKernel("diffuseProject_k", module, ctx); updateVelocity_k = new CudaKernel("updateVelocity_k", module, ctx); advectParticles_k = new CudaKernel("advectParticles_k", module, ctx); }
void ShutdownD3D9() { if (NumActiveImages == 0) { if (SharedTexture != null) { SharedTexture.Dispose(); SharedTexture = null; } if (D3DDevice != null) { D3DDevice.Dispose(); D3DDevice = null; } if (D3DContext != null) { D3DContext.Dispose(); D3DContext = null; } } }
private void StartD3D() { if (activeClients != 0) return; context = new Direct3DEx(); var presentparams = new PresentParameters { Windowed = true, SwapEffect = SwapEffect.Discard, DeviceWindowHandle = GetDesktopWindow(), PresentationInterval = PresentInterval.Default, }; device = new DeviceEx(context, this.adapterIndex, DeviceType.Hardware, IntPtr.Zero, CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve, presentparams); }
/// <summary> /// Initializes the Device and starts up the d3dimage object /// </summary> private void InitializeDevice() { if(DirectXStatus != DirectXStatus.Available) return; Debug.Assert(Direct3D != null); ReleaseDevice(); HwndSource hwnd = new HwndSource(0, 0, 0, 0, 0, _d3dimage.PixelWidth, _d3dimage.PixelHeight, "SlimDXControl", IntPtr.Zero); _presentParameters = new PresentParameters(); _presentParameters.SwapEffect = SwapEffect.Copy; _presentParameters.DeviceWindowHandle = hwnd.Handle; _presentParameters.Windowed = true; _presentParameters.BackBufferWidth = ((int) ActualWidth < 0) ? 1 : (int) ActualWidth; _presentParameters.BackBufferHeight = ((int) ActualHeight < 0) ? 1 : (int) ActualHeight; _presentParameters.BackBufferFormat = _backbufferFormat; _presentParameters.AutoDepthStencilFormat = _depthStencilFormat; try { if(UseDeviceEx) { _deviceEx = new DeviceEx((Direct3DEx) Direct3D, 0, DeviceType.Hardware, hwnd.Handle, _createFlags, _presentParameters); } else { _device = new Device(Direct3D, 0, DeviceType.Hardware, hwnd.Handle, _createFlags, _presentParameters); } } catch(Direct3D9Exception) { DirectXStatus = DirectXStatus.Unavailable_Unknown; return; } // call the user's ones OnDeviceCreated(EventArgs.Empty); OnDeviceReset(EventArgs.Empty); { // is it the case that someone else is nulling these out on us? seems so // this means we need to be careful not to let multiple copies of the delegate get onto the list // not sure what else we can do here... CompositionTarget.Rendering -= OnRendering; _d3dimage.IsFrontBufferAvailableChanged -= OnIsFrontBufferAvailableChanged; CompositionTarget.Rendering += OnRendering; _d3dimage.IsFrontBufferAvailableChanged += OnIsFrontBufferAvailableChanged; } _d3dimage.Lock(); _backBufferSurface = Device.GetBackBuffer(0, 0); _d3dimage.SetBackBuffer(D3DResourceType.IDirect3DSurface9, _backBufferSurface.ComPointer); _d3dimage.Unlock(); return; }
private void ReleaseDevice() { if(_device != null) { if(!_device.Disposed) { _device.Dispose(); _device = null; OnDeviceDestroyed(EventArgs.Empty); } } if(_deviceEx != null) { if(!_deviceEx.Disposed) { _deviceEx.Dispose(); _deviceEx = null; OnDeviceDestroyed(EventArgs.Empty); } } _d3dimage.Lock(); _d3dimage.SetBackBuffer(D3DResourceType.IDirect3DSurface9, IntPtr.Zero); _d3dimage.Unlock(); ReleaseBackBuffer(); }
void Initialise() { if (this.FHandle == (IntPtr) 0) throw (new Exception("No shared texture handle set")); this.FContext = new Direct3DEx(); this.FHiddenControl = new Control(); this.FHiddenControl.Visible = false; this.FHiddenControl.Width = this.FWidth; this.FHiddenControl.Height = this.FHeight; var flags = CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.PureDevice | CreateFlags.FpuPreserve; this.FDevice = new DeviceEx(FContext, 0, DeviceType.Hardware, this.FHiddenControl.Handle, flags, new PresentParameters() { BackBufferWidth = this.FWidth, BackBufferHeight = this.FHeight }); this.FTextureShared = new Texture(this.FDevice, this.FWidth, this.FHeight, 1, FUsage, FFormat, Pool.Default, ref this.FHandle); this.FTextureCopied = new Texture(this.FDevice, this.FWidth, this.FHeight, 1, Usage.RenderTarget, FFormat, Pool.Default); var description = FTextureCopied.GetLevelDescription(0); this.FSurfaceOffscreen = Surface.CreateOffscreenPlainEx(FDevice, FWidth, FHeight, description.Format, Pool.SystemMemory, Usage.None); this.FInitialised = true; }