示例#1
0
 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();
 }
示例#2
0
        /// <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);
        }
示例#3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DeviceHandlerD3D9"/> class.
        /// </summary>
        /// <param name="dxgiAdapter">The target adapter.</param>
        /// <param name="isSoftwareAdapter">Are we in software mode?</param>
        /// <param name="debugEnabled">Is debug mode enabled?</param>
        internal DeviceHandlerD3D9(DXGI.Adapter1 dxgiAdapter, bool isSoftwareAdapter, bool debugEnabled)
        {
            // Update member variables
            m_dxgiAdapter = dxgiAdapter;

            try
            {
                // Just needed when on true hardware
                if (!isSoftwareAdapter)
                {
                    //Prepare device creation
                    D3D9.CreateFlags createFlags =
                        D3D9.CreateFlags.HardwareVertexProcessing |
                        D3D9.CreateFlags.PureDevice |
                        D3D9.CreateFlags.FpuPreserve |
                        D3D9.CreateFlags.Multithreaded;
                    D3D9.PresentParameters presentparams = new D3D9.PresentParameters();
                    presentparams.Windowed             = true;
                    presentparams.SwapEffect           = D3D9.SwapEffect.Discard;
                    presentparams.DeviceWindowHandle   = GetDesktopWindow();
                    presentparams.PresentationInterval = D3D9.PresentInterval.Default;
                    presentparams.BackBufferCount      = 1;

                    //Create the device finally
                    m_direct3DEx = new D3D9.Direct3DEx();

                    // Try to find the Direct3D9 adapter that maches given DXGI adapter
                    m_adapterIndex = -1;
                    for (int loop = 0; loop < m_direct3DEx.AdapterCount; loop++)
                    {
                        var d3d9AdapterInfo = m_direct3DEx.GetAdapterIdentifier(loop);
                        if (d3d9AdapterInfo.DeviceId == m_dxgiAdapter.Description1.DeviceId)
                        {
                            m_adapterIndex = loop;
                            break;
                        }
                    }

                    // Direct3D 9 is only relevant on the primary device
                    if (m_adapterIndex < 0)
                    {
                        return;
                    }

                    // Try to create the device
                    m_deviceEx = new D3D9.DeviceEx(m_direct3DEx, m_adapterIndex, D3D9.DeviceType.Hardware, IntPtr.Zero, createFlags, presentparams);
                }
                else
                {
                    //Not supported in software mode
                }
            }
            catch (Exception)
            {
                // No direct3d 9 interface support
                GraphicsHelper.SafeDispose(ref m_direct3DEx);
                GraphicsHelper.SafeDispose(ref m_deviceEx);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="HigherD3DImageSource"/> class.
        /// </summary>
        public HigherD3DImageSource(EngineDevice device)
        {
            m_device     = device;
            m_d3dContext = device.ContextD3D9;
            m_d3dDevice  = device.DeviceD3D9;

            if (m_d3dDevice == null)
            {
                throw new SeeingSharpException("Unable to create Wpf image source: No Direct3D 9 device available on " + device);
            }

            s_activeClients++;
        }
示例#5
0
        private void SetRenderTarget(D3D11.Texture2D target)
        {
            var format = TranslateFormat(target);
            var handle = GetSharedHandle(target);

            var presentParams = GetPresentParameters();
            var createFlags   = D3D9.CreateFlags.HardwareVertexProcessing | D3D9.CreateFlags.Multithreaded |
                                D3D9.CreateFlags.FpuPreserve;

            var d3DContext = new D3D9.Direct3DEx();
            var d3DDevice  = new D3D9.DeviceEx(d3DContext, 0, D3D9.DeviceType.Hardware, IntPtr.Zero, createFlags,
                                               presentParams);

            _renderTarget = new D3D9.Texture(d3DDevice, target.Description.Width, target.Description.Height, 1,
                                             D3D9.Usage.RenderTarget, format, D3D9.Pool.Default, ref handle);
        }
        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>
            /// Старт работы подсистемы представления Direct3D9
            /// </summary>
            //---------------------------------------------------------------------------------------------------------
            public static void StartDirect3D9()
            {
                // Если счетчик клиентов больше нуля значит выходим
                if (mActiveClients != 0)
                {
                    return;
                }

                // Создаем структуру для презентации
                var present_params = GetPresentParameters();

                // Флаги создания
                var create_flags = Direct3D9.CreateFlags.HardwareVertexProcessing | Direct3D9.CreateFlags.Multithreaded | Direct3D9.CreateFlags.FpuPreserve;

                // Создаем объект адаптера Direct3D9
                mD3DContext = new Direct3D9.Direct3DEx();

                // Создаем устройство Direct3D9
                mD3DDevice = new Direct3D9.DeviceEx(D3DContext, 0, Direct3D9.DeviceType.Hardware, IntPtr.Zero, create_flags, present_params);
            }
		public static void StartD3D(Window parentWindow)
		{
            _activeClients++;

			if (_activeClients > 1)
				return;

			_d3DContext = new Direct3DEx();

			var presentParameters = new PresentParameters
			{
				Windowed = true,
				SwapEffect = SwapEffect.Discard,
				DeviceWindowHandle = new WindowInteropHelper(parentWindow).Handle,
				PresentationInterval = PresentInterval.Default
			};

			_d3DDevice = new DeviceEx(_d3DContext, 0, DeviceType.Hardware, IntPtr.Zero, 
				CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve,
				presentParameters);
		}
示例#9
0
        /// <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);

            Unloaded += HandleUnloaded;
        }
示例#10
0
        /// <summary>
        /// Creates new instance of <see cref="D3D11Image"/> 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, Direct3D11.Texture2D renderTarget)
        {
            using (var resource = renderTarget.QueryInterface<DXGI.Resource>())
            {
                var handle = resource.SharedHandle;
                texture = new Texture(device,
                                      renderTarget.Description.Width,
                                      renderTarget.Description.Height,
                                      1,
                                      Usage.RenderTarget,
                                      Format.A8R8G8B8,
                                      Pool.Default,
                                      ref handle);
            }

            using (var surface = texture.GetSurfaceLevel(0))
            {
                textureSurfaceHandle = surface.NativePointer;
                TrySetBackbufferPointer(textureSurfaceHandle);
            }

            this.IsFrontBufferAvailableChanged += HandleIsFrontBufferAvailableChanged;
        }
示例#11
0
        private void SetRenderTarget(D3D11.Texture2D target)
        {
            var format = TranslateFormat(target);
            var handle = GetSharedHandle(target);

            var presentParams = GetPresentParameters();
            var createFlags   = D3D9.CreateFlags.HardwareVertexProcessing | D3D9.CreateFlags.Multithreaded |
                                D3D9.CreateFlags.FpuPreserve;

            var d3DContext = new D3D9.Direct3DEx();
            var d3DDevice  = new D3D9.DeviceEx(d3DContext, 0, D3D9.DeviceType.Hardware, IntPtr.Zero, createFlags,
                                               presentParams);

            _renderTarget = new D3D9.Texture(d3DDevice, target.Description.Width, target.Description.Height, 1,
                                             D3D9.Usage.RenderTarget, format, D3D9.Pool.Default, ref handle);

            using (var surface = _renderTarget.GetSurfaceLevel(0))
            {
                _d3D.Lock();
                _d3D.SetBackBuffer(D3DResourceType.IDirect3DSurface9, surface.NativePointer);
                _d3D.Unlock();
            }
        }
示例#12
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 );
        }
示例#13
0
 /// <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;
 }
示例#14
0
 public Subtitle(DeviceEx device)
 {
   _device = device;
   Id = IdCount++;
 }
示例#15
0
文件: Engine.cs 项目: nydehi/openuo
        public Engine(IKernel kernel)
        {
            _kernel = kernel;
            _resouces = new List<IResourceContainer>();
            _updatables = new List<IUpdatable>();
            _renderables = new List<IRenderable>();

            IDeviceProvider deviceProvider = kernel.Get<IDeviceProvider>();

            _form = deviceProvider.RenderForm;
            _form.ResizeBegin += OnResizeBegin;
            _form.ResizeEnd += OnResizeEnd;
            _form.FormClosed += OnFormClosed;
            _form.Resize += new EventHandler(OnFormResize);
            _form.KeyDown += new KeyEventHandler(_form_KeyDown);

            _device = new DeviceEx(deviceProvider.Device.NativePointer);
            _presentParameters = deviceProvider.PresentParameters;
            _totalGameTime = TimeSpan.Zero;
            _lastFrameElapsedGameTime = TimeSpan.Zero;
            _drawState = new DrawState();
            _updateState = new UpdateState();
            _clock = new GameClock();
        }
 public void Dispose()
 {
     if (this.sharedSurface != null)
     {
         this.sharedSurface.Dispose();
         this.sharedSurface = null;
         this.device.Dispose();
         this.device = null;
     }
     if (this.glControl != null)
     {
         this.glControl.Dispose();
         this.glControl = null;
     }
 }
示例#17
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;
            }
        }
示例#18
0
        static void ShutdownD3D9()
        {
            s_numActiveClients--;

            if (s_numActiveClients != 0)
                return;

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

            if (s_context != null)
            {
                s_context.Dispose();
                s_context = null;
            }
        }
示例#19
0
        private void RenderFrame(object sender, EventArgs e)
        {
            if (DisableRendering)
                return;

            var args = (RenderingEventArgs) e;

            var w = _outputWidth;
            var h = _outputHeight;
            if (w <= 0 || h <= 0)
            {
                return;
            }

            if (Device == null)
            {
                var presentParams = new PresentParameters(w, h)
                {
                    Windowed = true,
                    SwapEffect = SwapEffect.Discard,
                    DeviceWindowHandle = GetDesktopWindow(),
                    PresentationInterval = PresentInterval.Default
                };
                Device = new DeviceEx(new Direct3DEx(),
                    0,
                    DeviceType.Hardware,
                    IntPtr.Zero,
                    CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve,
                    presentParams);
            }

            if (_activeSystem == null && ActiveSystem != null)
            {
                _activeSystem = ParticleSystem.FromSpec(Device, DataPath, ActiveSystem.ToSpec());
            }

            if (D3Dimg.IsFrontBufferAvailable && _lastRender != args.RenderingTime)
            {
                if (_renderTargetSurface == null || _renderTargetWidth != w || _renderTargetHeight != h)
                {
                    _renderTargetWidth = w;
                    _renderTargetHeight = h;

                    _renderTargetSurface?.Dispose();
                    _renderTargetDepth?.Dispose();

                    _renderTargetSurface = Surface.CreateRenderTarget(Device,
                        _renderTargetWidth,
                        _renderTargetHeight,
                        Format.X8R8G8B8,
                        MultisampleType.None,
                        0,
                        false);
                    _renderTargetDepth = Surface.CreateDepthStencil(Device,
                        _renderTargetWidth,
                        _renderTargetHeight,
                        Format.D16,
                        MultisampleType.None,
                        0,
                        true);
                }

                D3Dimg.Lock();

                Device.SetRenderTarget(0, _renderTargetSurface);
                Device.DepthStencilSurface = _renderTargetDepth;

                RenderParticleSystem(w, h, args.RenderingTime);

                D3Dimg.SetBackBuffer(D3DResourceType.IDirect3DSurface9, _renderTargetSurface.NativePointer);
                D3Dimg.AddDirtyRect(new Int32Rect(0, 0, _renderTargetWidth, _renderTargetHeight));
                D3Dimg.Unlock();

                _lastRender = args.RenderingTime;
            }
        }
示例#20
0
        public override void Hook()
        {
            this.DebugMessage("Hook: Begin");
            // First we need to determine the function address for IDirect3DDevice9
            Device device;
            id3dDeviceFunctionAddresses = new List<IntPtr>();
            //id3dDeviceExFunctionAddresses = new List<IntPtr>();
            this.DebugMessage("Hook: Before device creation");
            using (Direct3D d3d = new Direct3D())
            {
                using (var renderForm = new System.Windows.Forms.Form())
                {
                    using (device = new Device(d3d, 0, DeviceType.NullReference, IntPtr.Zero, CreateFlags.HardwareVertexProcessing, new PresentParameters() { BackBufferWidth = 1, BackBufferHeight = 1, DeviceWindowHandle = renderForm.Handle }))
                    {
                        this.DebugMessage("Hook: Device created");
                        id3dDeviceFunctionAddresses.AddRange(GetVTblAddresses(device.NativePointer, D3D9_DEVICE_METHOD_COUNT));
                    }
                }
            }

            try
            {
                using (Direct3DEx d3dEx = new Direct3DEx())
                {
                    this.DebugMessage("Hook: Direct3DEx...");
                    using (var renderForm = new System.Windows.Forms.Form())
                    {
                        using (var deviceEx = new DeviceEx(d3dEx, 0, DeviceType.NullReference, IntPtr.Zero, CreateFlags.HardwareVertexProcessing, new PresentParameters() { BackBufferWidth = 1, BackBufferHeight = 1, DeviceWindowHandle = renderForm.Handle }, new DisplayModeEx() { Width = 800, Height = 600 }))
                        {
                            this.DebugMessage("Hook: DeviceEx created - PresentEx supported");
                            id3dDeviceFunctionAddresses.AddRange(GetVTblAddresses(deviceEx.NativePointer, D3D9_DEVICE_METHOD_COUNT, D3D9Ex_DEVICE_METHOD_COUNT));
                            _supportsDirect3D9Ex = true;
                        }
                    }
                }
            }
            catch (Exception)
            {
                _supportsDirect3D9Ex = false;
            }

            // We want to hook each method of the IDirect3DDevice9 interface that we are interested in

            // 42 - EndScene (we will retrieve the back buffer here)
            Direct3DDevice_EndSceneHook = new Hook<Direct3D9Device_EndSceneDelegate>(
                id3dDeviceFunctionAddresses[(int)Direct3DDevice9FunctionOrdinals.EndScene],
                // On Windows 7 64-bit w/ 32-bit app and d3d9 dll version 6.1.7600.16385, the address is equiv to:
                // (IntPtr)(GetModuleHandle("d3d9").ToInt32() + 0x1ce09),
                // A 64-bit app would use 0xff18
                // Note: GetD3D9DeviceFunctionAddress will output these addresses to a log file
                new Direct3D9Device_EndSceneDelegate(EndSceneHook),
                this);

            unsafe
            {
                // If Direct3D9Ex is available - hook the PresentEx
                if (_supportsDirect3D9Ex)
                {
                    Direct3DDeviceEx_PresentExHook = new Hook<Direct3D9DeviceEx_PresentExDelegate>(
                        id3dDeviceFunctionAddresses[(int)Direct3DDevice9ExFunctionOrdinals.PresentEx],
                        new Direct3D9DeviceEx_PresentExDelegate(PresentExHook),
                        this);
                }

                // Always hook Present also (device will only call Present or PresentEx not both)
                Direct3DDevice_PresentHook = new Hook<Direct3D9Device_PresentDelegate>(
                    id3dDeviceFunctionAddresses[(int)Direct3DDevice9FunctionOrdinals.Present],
                    new Direct3D9Device_PresentDelegate(PresentHook),
                    this);
            }

            // 16 - Reset (called on resolution change or windowed/fullscreen change - we will reset some things as well)
            Direct3DDevice_ResetHook = new Hook<Direct3D9Device_ResetDelegate>(
                id3dDeviceFunctionAddresses[(int)Direct3DDevice9FunctionOrdinals.Reset],
                // On Windows 7 64-bit w/ 32-bit app and d3d9 dll version 6.1.7600.16385, the address is equiv to:
                //(IntPtr)(GetModuleHandle("d3d9").ToInt32() + 0x58dda),
                // A 64-bit app would use 0x3b3a0
                // Note: GetD3D9DeviceFunctionAddress will output these addresses to a log file
                new Direct3D9Device_ResetDelegate(ResetHook),
                this);

            /*
             * Don't forget that all hooks will start deactivated...
             * The following ensures that all threads are intercepted:
             * Note: you must do this for each hook.
             */
            
            Direct3DDevice_EndSceneHook.Activate();
            Hooks.Add(Direct3DDevice_EndSceneHook);

            Direct3DDevice_PresentHook.Activate();
            Hooks.Add(Direct3DDevice_PresentHook);

            if (_supportsDirect3D9Ex)
            {
                Direct3DDeviceEx_PresentExHook.Activate();
                Hooks.Add(Direct3DDeviceEx_PresentExHook);
            }

            Direct3DDevice_ResetHook.Activate();
            Hooks.Add(Direct3DDevice_ResetHook);

            this.DebugMessage("Hook: End");
        }
示例#21
0
        public override unsafe void Hook()
        {
            this.DebugMessage("Hook: Begin");

            this.DebugMessage("Hook: Before device creation");
            using (var d3d = new Direct3D())
            {
                this.DebugMessage("Hook: Direct3D created");
                using (
                    var device = new Device(
                        d3d,
                        0,
                        DeviceType.NullReference,
                        IntPtr.Zero,
                        CreateFlags.HardwareVertexProcessing,
                        new PresentParameters() { BackBufferWidth = 1, BackBufferHeight = 1 }))
                {
                    this.id3dDeviceFunctionAddresses.AddRange(this.GetVTblAddresses(device.NativePointer, D3D9_DEVICE_METHOD_COUNT));
                }
            }

            try
            {
                using (var d3dEx = new Direct3DEx())
                {
                    this.DebugMessage("Hook: Try Direct3DEx...");
                    using (
                        var deviceEx = new DeviceEx(
                            d3dEx,
                            0,
                            DeviceType.NullReference,
                            IntPtr.Zero,
                            CreateFlags.HardwareVertexProcessing,
                            new PresentParameters() { BackBufferWidth = 1, BackBufferHeight = 1 },
                            new DisplayModeEx() { Width = 800, Height = 600 }))
                    {
                        this.id3dDeviceFunctionAddresses.AddRange(
                            this.GetVTblAddresses(deviceEx.NativePointer, D3D9_DEVICE_METHOD_COUNT, D3D9Ex_DEVICE_METHOD_COUNT));
                        this.supportsDirect3DEx = true;
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }

            this.DebugMessage("Setting up Direct3D hooks...");
            this.Direct3DDevice_EndSceneHook =
                new HookData<Direct3D9Device_EndSceneDelegate>(
                    this.id3dDeviceFunctionAddresses[(int)Direct3DDevice9FunctionOrdinals.EndScene],
                    new Direct3D9Device_EndSceneDelegate(this.EndSceneHook),
                    this);

            this.Direct3DDevice_EndSceneHook.ReHook();
            this.Hooks.Add(this.Direct3DDevice_EndSceneHook.Hook);

            this.Direct3DDevice_PresentHook =
                new HookData<Direct3D9Device_PresentDelegate>(
                    this.id3dDeviceFunctionAddresses[(int)Direct3DDevice9FunctionOrdinals.Present],
                    new Direct3D9Device_PresentDelegate(this.PresentHook),
                    this);

            this.Direct3DDevice_ResetHook =
                new HookData<Direct3D9Device_ResetDelegate>(
                    this.id3dDeviceFunctionAddresses[(int)Direct3DDevice9FunctionOrdinals.Reset],
                    new Direct3D9Device_ResetDelegate(this.ResetHook),
                    this);

            if (this.supportsDirect3DEx)
            {
                this.DebugMessage("Setting up Direct3DEx hooks...");
                this.Direct3DDeviceEx_PresentExHook =
                    new HookData<Direct3D9DeviceEx_PresentExDelegate>(
                        this.id3dDeviceFunctionAddresses[(int)Direct3DDevice9ExFunctionOrdinals.PresentEx],
                        new Direct3D9DeviceEx_PresentExDelegate(this.PresentExHook),
                        this);

                this.Direct3DDeviceEx_ResetExHook =
                    new HookData<Direct3D9DeviceEx_ResetExDelegate>(
                        this.id3dDeviceFunctionAddresses[(int)Direct3DDevice9ExFunctionOrdinals.ResetEx],
                        new Direct3D9DeviceEx_ResetExDelegate(this.ResetExHook),
                        this);
            }

            this.Direct3DDevice_ResetHook.ReHook();
            this.Hooks.Add(this.Direct3DDevice_ResetHook.Hook);

            this.Direct3DDevice_PresentHook.ReHook();
            this.Hooks.Add(this.Direct3DDevice_PresentHook.Hook);

            if (this.supportsDirect3DEx)
            {
                this.Direct3DDeviceEx_PresentExHook.ReHook();
                this.Hooks.Add(this.Direct3DDeviceEx_PresentExHook.Hook);

                this.Direct3DDeviceEx_ResetExHook.ReHook();
                this.Hooks.Add(this.Direct3DDeviceEx_ResetExHook.Hook);
            }

            this.DebugMessage("Hook: End");
        }
        /// <summary>
        /// Create D3D9Ex context and OpenGL framebuffer
        /// </summary>
        /// <param name="handle"></param>
        /// <param name="hasDepthBuffer"></param>
        /// <param name="hasStencilBuffer"></param>
        private void CreateD3D9ExContext(IntPtr handle, bool hasDepthBuffer, bool hasStencilBuffer)
        {
            var d3d = new Direct3DEx();

            int initW = Size.Width;
            int initH = Size.Height;

            this.presentparams = new PresentParameters();
            this.presentparams.Windowed = true;
            this.presentparams.SwapEffect = SwapEffect.Discard;
            this.presentparams.DeviceWindowHandle = handle;
            this.presentparams.PresentationInterval = PresentInterval.Default;
            // FpuPreserve for WPF
            // Multithreaded so that resources are actually sharable between DX and GL
            this.device = new DeviceEx(
                d3d,
                0,
                DeviceType.Hardware,
                IntPtr.Zero,
                CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve,
                this.presentparams);

            // create shared surface
            this.sharedSurface = Surface.CreateRenderTarget(
                this.device,
                initW,
                initH,
                Format.A8R8G8B8,
                MultisampleType.None,
                0,
                false);

            #region OpenGL Interop

            this.wgl = new WGL_NV_DX_interop();
            this.wglHandleDevice = wgl.WglDXOpenDeviceNV(device.NativePointer);
            this.glSharedSurface = GL.GenTexture();
            this.fbo = GL.GenFramebuffer();

            // refer D3D9 surface and OpenGL Texture2D
            this.wglHandleSharedSurface = wgl.WglDXRegisterObjectNV(
                this.wglHandleDevice,
                this.sharedSurface.NativePointer,
                (uint)this.glSharedSurface,
                (uint)TextureTarget.Texture2D,
                WGL_NV_DX_interop.WGL_ACCESS_READ_WRITE_NV);
            this.singleWglHandleSharedSurfaceArray = new IntPtr[] { this.wglHandleSharedSurface };

            // setup framebuffer
            Console.WriteLine(GL.GetError());
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, this.fbo);
            Console.WriteLine(GL.GetError());
            GL.FramebufferTexture2D(
                FramebufferTarget.Framebuffer,
                FramebufferAttachment.ColorAttachment0,
                TextureTarget.Texture2D,
                this.glSharedSurface,
                0);
            Console.WriteLine(GL.GetError());
            if (hasDepthBuffer)
            {
                var depth = GL.GenRenderbuffer();
                GL.FramebufferRenderbuffer(
                    FramebufferTarget.Framebuffer,
                    FramebufferAttachment.DepthAttachment,
                    RenderbufferTarget.Renderbuffer,
                    depth);
                GL.DeleteRenderbuffer(depth);
            }
            if (hasStencilBuffer)
            {
                var stencil = GL.GenRenderbuffer();
                GL.FramebufferRenderbuffer(
                    FramebufferTarget.Framebuffer,
                    FramebufferAttachment.StencilAttachment,
                    RenderbufferTarget.Renderbuffer,
                    stencil);
                GL.DeleteRenderbuffer(stencil);
            }

            GL.DrawBuffer((DrawBufferMode)FramebufferAttachment.ColorAttachment0);

            #endregion
        }
示例#23
0
 /// <summary>
 /// Unloads all loaded resources.
 /// </summary>
 internal void UnloadResources()
 {
     m_deviceEx   = CommonTools.DisposeObject(m_deviceEx);
     m_direct3DEx = CommonTools.DisposeObject(m_direct3DEx);
 }
示例#24
0
 public EVRCallback(RenderDlgt renderDlgt, Action onTextureInvalidated)
 {
   _onTextureInvalidated = onTextureInvalidated;
   _renderDlgt = renderDlgt;
   _device = SkinContext.Device;
 }
        /// <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, "SharpDXControl", 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.MultiSampleType = MultisampleType.None;
            IsAntialiased = false;
            int qualityLevels;
            if (Direct3D.CheckDeviceMultisampleType(0, DeviceType.Hardware, backbufferFormat, true, MultisampleType.EightSamples, out qualityLevels))
            {
                presentParameters.MultiSampleType = MultisampleType.EightSamples;
                presentParameters.MultiSampleQuality = qualityLevels - 1;
                IsAntialiased = true;
            }
            else if (Direct3D.CheckDeviceMultisampleType(0, DeviceType.Hardware, backbufferFormat, true, MultisampleType.FourSamples, out qualityLevels))
            {
                presentParameters.MultiSampleType = 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 (Exception) //Direct3D9Exception
            {
                DirectXStatus = DirectXStatus.Unavailable_Unknown;
                return;
            }
            return;
        }
示例#26
0
		private static void StartD3D()
		{
			_d3DContext = new Direct3DEx();

			PresentParameters presentparams = new PresentParameters();
			presentparams.Windowed = true;
			presentparams.SwapEffect = SwapEffect.Discard;
			presentparams.DeviceWindowHandle = GetDesktopWindow();
			presentparams.PresentationInterval = PresentInterval.Default;

			D3D10ImageSource._d3DDevice = new DeviceEx(_d3DContext, 0, DeviceType.Hardware, IntPtr.Zero, CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve, presentparams);
		}
示例#27
0
        /// <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;
        }
示例#28
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);
      }
    }
示例#29
0
    /// <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;
    }
示例#30
0
    internal static void Dispose()
    {
      if (_backBuffer != null)
        _backBuffer.Dispose();
      _backBuffer = null;

      if (_device != null)
        _device.Dispose();
      _device = null;
      MPDirect3D.Unload();
      _renderAndResourceAccessLock.Dispose();
    }
示例#31
0
        private void StartD3D()
        {
            if (DX10ImageSource.ActiveClients != 0)
                return;

            D3DContext = new Direct3DEx();

            PresentParameters presentparams = new PresentParameters();
            presentparams.Windowed = true;
            presentparams.SwapEffect = SwapEffect.Discard;
            presentparams.DeviceWindowHandle = GetDesktopWindow();
            presentparams.PresentationInterval = PresentInterval.Default;

            DisplayModeEx[] mode = new DisplayModeEx[0];
            PresentParameters[] presentParams = new PresentParameters[] { presentparams };

            DX10ImageSource.D3DDevice = new DeviceEx(D3DContext, 0, DeviceType.Hardware, IntPtr.Zero, CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve, presentParams, mode);
        }
示例#32
0
        static void InitD3D9()
        {
            if (s_numActiveClients == 0)
            {
                s_context = new D3D9.Direct3DEx();

                var presentparams = new D3D9.PresentParameters()
                {
                    Windowed = true,
                    SwapEffect = D3D9.SwapEffect.Discard,
                    DeviceWindowHandle = GetDesktopWindow(),
                    PresentationInterval = D3D9.PresentInterval.Immediate,
                };

                s_device = new D3D9.DeviceEx(s_context, 0, D3D9.DeviceType.Hardware, IntPtr.Zero,
                    D3D9.CreateFlags.HardwareVertexProcessing | D3D9.CreateFlags.Multithreaded | D3D9.CreateFlags.FpuPreserve, presentparams);
            }

            s_numActiveClients++;
        }