Пример #1
0
        /// <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);
            }
        }
Пример #2
0
        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();
        }
Пример #3
0
        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;
        }
Пример #4
0
        public void Dispose()
        {
            FTextureShared.Dispose();
            FTextureCopied.Dispose();
            FSurfaceOffscreen.Dispose();

            FContext.Dispose();
            FDevice.Dispose();
            FHiddenControl.Dispose();
        }
Пример #5
0
        private void EndD3D()
        {
            if (_activeClients != 0)
            {
                return;
            }

            _renderTarget?.Dispose();
            _d3DDevice.Dispose();
            _d3DContext.Dispose();
        }
Пример #6
0
 public void Dispose()
 {
     if (!device.IsDisposed)
     {
         running = false;
         renderLocker.Wait();
         renderLocker.Dispose();
         device.Dispose();
         direct3D.Dispose();
         fontRenderer.Dispose();
         textureRenderer.Dispose();
     }
 }
Пример #7
0
        /// <summary>
        /// Disposes all unmanaged resources associated with this instance
        /// </summary>
        public void Dispose()
        {
            if (isDisposed)
            {
                return;
            }

            DisposeD3D9Backbuffer();

            device9.Dispose();
            direct3D.Dispose();

            isDisposed = true;
        }
Пример #8
0
 public void ReleaseD3D()
 {
     if (device != null)
     {
         if (!device.Disposed)
         {
             device.Dispose();
             device = null;
         }
     }
     d3dimage.Lock();
     d3dimage.SetBackBuffer(D3DResourceType.IDirect3DSurface9, IntPtr.Zero);
     d3dimage.Unlock();
 }
Пример #9
0
        private void Dispose(bool dispose_managed)
        {
            if (_disposed)
            {
                return;
            }

            if (dispose_managed)
            {
                _texture?.Dispose();
                _device_ex?.Dispose();
                _d3d_ex?.Dispose();
            }
            _disposed = true;
        }
Пример #10
0
 private void ShutdownD3D9()
 {
     if (ActiveImageCount == 0)
     {
         if (SharedTexture != null)
         {
             SharedTexture.Dispose();
             SharedTexture = null;
         }
         if (D3DDevice != null)
         {
             D3DDevice.Dispose();
             D3DDevice = null;
         }
         if (D3DContext != null)
         {
             D3DContext.Dispose();
             D3DContext = null;
         }
     }
 }
        private void ReleaseDevice()
        {
            if (device != null)
            {
                if (!device.IsDisposed)
                {
                    device.Dispose();
                    device = null;
                }
            }

            if (deviceEx != null)
            {
                if (!deviceEx.IsDisposed)
                {
                    deviceEx.Dispose();
                    device = null;
                }
            }

            //OnDeviceDisposing(EventArgs.Empty);
        }
Пример #12
0
        /// <summary>
        /// Releases the unmanaged resources used by an instance of the <see cref="D3D9"/> class
        /// and optionally releases the managed resources.
        /// </summary>
        /// <param name="disposing">
        /// <see langword="true"/> to release both managed and unmanaged resources;
        /// <see langword="false"/> to release only unmanaged resources.
        /// </param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    // Dispose managed resources.
                    if (_device != null)
                    {
                        _device.Dispose();
                        _device = null;
                    }
                    if (_direct3D != null)
                    {
                        _direct3D.Dispose();
                        _direct3D = null;
                    }
                }

                // Release unmanaged resources.
                _disposed = true;
            }
        }
Пример #13
0
        public void Close()
        {
            logger.Verb("D3DRenderer::Close()");

            if (surface != null)
            {
                surface.Dispose();
                surface = null;
            }

            if (direct3D != null)
            {
                direct3D.Dispose();
                direct3D = null;
            }

            if (device != null)
            {
                device.Dispose();
                device = null;
            }

            state = RendererState.Closed;
        }
Пример #14
0
        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);
        }
Пример #15
0
        private void myWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //Stop render loop before closing
            if (frameTimer != null)
            {
                frameTimer.Tick -= new EventHandler(frameTimer_Tick);
                frameTimer.Stop();
            }

            //Cleanup
            if (graphicsres != null)
            {
                graphicsres.Dispose();
            }
            if (g_mparticles != null)
            {
                g_mparticles.Dispose();
            }
            if (stopwatch != null)
            {
                stopwatch.Dispose();
            }

            if (texref != null)
            {
                texref.Dispose();
            }
            if (g_dvfield != null)
            {
                g_dvfield.Dispose();
            }
            if (g_vxfield != null)
            {
                g_vxfield.Dispose();
            }
            if (g_vyfield != null)
            {
                g_vyfield.Dispose();
            }

            if (g_planc2r != null)
            {
                g_planc2r.Dispose();
            }
            if (g_planr2c != null)
            {
                g_planr2c.Dispose();
            }

            if (g_pVB != null)
            {
                g_pVB.Dispose();
            }
            if (g_pTexture != null)
            {
                g_pTexture.Dispose();
            }

            if (device != null)
            {
                device.Dispose();
            }
            if (d3d != null)
            {
                d3d.Dispose();
            }

            if (ctx != null)
            {
                ctx.Dispose();
            }
        }
Пример #16
0
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            isRunning = false;

            //Cleanup
            if (graphicsres != null)
            {
                graphicsres.Dispose();
            }
            if (g_mparticles != null)
            {
                g_mparticles.Dispose();
            }
            if (stopwatch != null)
            {
                stopwatch.Dispose();
            }

            if (texref != null)
            {
                texref.Dispose();
            }
            if (g_dvfield != null)
            {
                g_dvfield.Dispose();
            }
            if (g_vxfield != null)
            {
                g_vxfield.Dispose();
            }
            if (g_vyfield != null)
            {
                g_vyfield.Dispose();
            }

            if (g_planc2r != null)
            {
                g_planc2r.Dispose();
            }
            if (g_planr2c != null)
            {
                g_planr2c.Dispose();
            }

            if (g_pVB != null)
            {
                g_pVB.Dispose();
            }
            if (g_pTexture != null)
            {
                g_pTexture.Dispose();
            }

            if (device != null)
            {
                device.Dispose();
            }
            if (d3d != null)
            {
                d3d.Dispose();
            }

            if (ctx != null)
            {
                ctx.Dispose();
            }
        }
Пример #17
0
        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);
        }
Пример #18
0
 public void Dispose()
 {
     _device.Dispose();
     _direct3D.Dispose();
 }
Пример #19
0
        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;
        }
Пример #20
0
        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);
        }
        private void OpenSharedResourceIfNeeded(DirectXResource res)
        {
            try
            {
                bool reinit = false;
                _occludedCounter++;

                if (_occludedCounter % 1 == 0) // every 200 ms
                {
                    var  state         = _device?.CheckDeviceState(_windowHandle) ?? DeviceState.Ok;
                    bool occludedState = state == DeviceState.PresentOccluded; // happens when windows is locked; then we could get black screen in preview d3dImage

                    reinit = _occludedState && !occludedState;                 // reinit if change from bad -> good
                    if (reinit)
                    {
                        Core.LogInfo("occluded -> normal");

                        if (_windowStateManager.IsMinimized())
                        {
                            _windowStateManager.IsMinimizedChanged += OnwindowStateManagerIsMinimizedChanged;
                        }
                        else
                        {
                            _ = ReinitSurfacesWithDelay();
                        }
                    }

                    if (!_occludedState && occludedState)
                    {
                        Core.LogInfo("normal -> occluded");
                    }

                    _occludedState = occludedState;
                }

                if (_sharedResource == null ||
                    _sharedResource.Description.Width != res.Texture2D.Description.Width ||
                    _sharedResource.Description.Height != res.Texture2D.Description.Height ||
                    _sharedResourceOwner != res.GetDx() ||
                    _reinitSurfaces)
                {
                    Core.LogInfo("Initing DX Presenter surface");
                    Source          = null;
                    _reinitSurfaces = false;

                    _surfaceD9?.Dispose();
                    _sharedResource?.Dispose();

                    _surfaceD9           = null;
                    _sharedResource      = null;
                    _sharedResourceOwner = null;


                    IntPtr handle = IntPtr.Zero;
                    _surfaceD9 = Surface.CreateRenderTarget(_device, res.Texture2D.Description.Width, res.Texture2D.Description.Height, Format.A8R8G8B8, MultisampleType.None, 0, true, ref handle);
                    if (handle == IntPtr.Zero)
                    {
                        Core.LogWarning("DirectX 9 Device failed to create Surface. Reinit Devices");
                        _device?.Dispose();
                        _direct3d?.Dispose();
                        _device   = null;
                        _direct3d = null;
                        InitDx9();
                        _surfaceD9 = Surface.CreateRenderTarget(_device, res.Texture2D.Description.Width, res.Texture2D.Description.Height, Format.A8R8G8B8, MultisampleType.None, 0, true, ref handle);

                        if (handle == IntPtr.Zero)
                        {
                            Core.LogWarning("DirectX 9 Device failed to create Surface after recreation.");
                        }
                    }
                    _sharedResource      = res.GetDx().Device.OpenSharedResource <Texture2D>(handle);
                    _sharedResourceOwner = res.GetDx();

                    _d3dimage = new D3DImage();
                    _d3dimage.Lock();
                    _d3dimage.SetBackBuffer(D3DResourceType.IDirect3DSurface9, _surfaceD9.NativePointer);
                    _d3dimage.Unlock();

                    Core.LogInfo("Inited DX Presenter surface");
                }
            }
            catch (Exception e)
            {
                Core.LogError(e, "Failed to open shared resource");
            }
        }