Beispiel #1
0
        public void Init(IntPtr windowHandle)
        {
            // Factory de interfaces de DirectX
            Factory factory = new Factory();

            // Factory para crear el adaptador a la tarjeta grafica (la primera)
            Adapter adapter = factory.GetAdapter(0);

            // Obtengo la salida a monitor primario del adaptador
            Output monitor = adapter.Outputs[0];

            //Obtengo mis posibilidades de salida que soporto que utilicen el formato R8G8B8A8_UNorm
            ModeDescription[] displayModes = monitor.GetDisplayModeList(swapChainFormat, DisplayModeEnumerationFlags.Interlaced);

            //Si utilizo VSync, busco la taza de refresco para la resolución deseada que soporta el monitor
            Rational refreshRate = new Rational(0, 1);

            //if (VSyncEnabled)
                foreach (ModeDescription mode in displayModes)
                    if (mode.Width == SettingsManager.Current.ScreenSize.Width &&
                        mode.Height == SettingsManager.Current.ScreenSize.Height)
                    {
                        refreshRate = mode.RefreshRate;
                        break;
                    }


            // Obtengo los datos sobre la tarjeta de memoria
            AdapterDescription adapterDescription = adapter.Description;
            VideoCardDescription = adapterDescription.Description;
            VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10; // En MB

            DebugManager.LogNotice(VideoCardDescription + " con " + VideoCardMemory + " MB dedicados");

            // Creo el device y el devicecontext
            SharpDX.Direct3D11.Device temp_device;

            SharpDX.Direct3D.FeatureLevel[] features = new FeatureLevel[] { // Array de Feature Level soportados
            FeatureLevel.Level_11_0,
            FeatureLevel.Level_10_1,
            FeatureLevel.Level_10_0,
            FeatureLevel.Level_9_3 };

            DeviceCreationFlags creationFlags; // Creo al device en modo debug si estoy en modo debug
            if (DebugManager.DebugMode)
                creationFlags = DeviceCreationFlags.Debug;
            else
                creationFlags = DeviceCreationFlags.None;


            SampleDescription sampleDescription; // Info de MSAA
            sampleDescription = new SampleDescription(1, 0);


            // Creo swapchain
            SwapChain temp_swapchain;

            // Descripcion de SwapChain
            SwapChainDescription swapChainDesc = new SwapChainDescription()
            {
                BufferCount = 1,
                ModeDescription = new ModeDescription(SettingsManager.Current.ScreenSize.Width,
                    SettingsManager.Current.ScreenSize.Height,
                    refreshRate, swapChainFormat),
                Usage = Usage.RenderTargetOutput,
                OutputHandle = windowHandle,
                // Multisampling
                SampleDescription = sampleDescription,
                IsWindowed = SettingsManager.Current.IsWindowed,
                // Sin flags avanzados
                Flags = SwapChainFlags.None,
                // Descarto el backbuffer despues de presentarlo
                SwapEffect = SwapEffect.Discard
            };

            SharpDX.Direct3D11.Device.CreateWithSwapChain(adapter, creationFlags, features, swapChainDesc, out temp_device, out temp_swapchain);

            DebugManager.LogNotice("DirectX11 Device creado");

            DXDevice = temp_device;
            DXDeviceContext = DXDevice.ImmediateContext;
            swapChain = temp_swapchain;
            DebugManager.LogNotice("Feature Level utilizado: " + DXDevice.FeatureLevel.ToString());
          

            // Libero la salida, el adaptador y el factory
            monitor.Dispose();
            adapter.Dispose();
            factory.Dispose();

            // Puntero al backbuffer
            Texture2D backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            // A partir del puntero creo el render target
            renderTargetView = new RenderTargetView(DXDevice, backBuffer);
            // Libero el backBuffer
            backBuffer.Dispose();

            // Descripcion del depth/stencil buffer
            Texture2DDescription depthBufferDesc = new Texture2DDescription()
            {
                Width = SettingsManager.Current.ScreenSize.Width,
                Height = SettingsManager.Current.ScreenSize.Height,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.D24_UNorm_S8_UInt,
                SampleDescription = sampleDescription,
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None
            };

            // Creo el depth/stencil buffer a partir de la descripcion
            depthStencilBuffer = new Texture2D(DXDevice, depthBufferDesc);
            // Y creo el depth/stencil view
            depthStencilView = new DepthStencilView(DXDevice, depthStencilBuffer);

            DXDeviceContext.OutputMerger.SetTargets(depthStencilView, renderTargetView);

            ViewportF viewport = new ViewportF()
            {
                X = 0,
                Y = 0,
                Width = SettingsManager.Current.ScreenSize.Width,
                Height = SettingsManager.Current.ScreenSize.Height,
                MinDepth = 0,
                MaxDepth = 1
            };

            DXDeviceContext.Rasterizer.SetViewport(viewport.X, viewport.Y, viewport.Width, viewport.Height, viewport.MinDepth, viewport.MaxDepth);
            DebugManager.LogNotice("DX11 inicilizado!");

        }
Beispiel #2
0
        public bool Initialize(SystemConfiguration configuration, IntPtr windowHandle)
        {
            try
            {
                #region Environment Configuration
                // Store the vsync setting.
                VerticalSyncEnabled = SystemConfiguration.VerticalSyncEnabled;

                // Create a DirectX graphics interface factory.
                var factory = new Factory();
                // Use the factory to create an adapter for the primary graphics interface (video card).
                var adapter = factory.GetAdapter(0);
                // Get the primary adapter output (monitor).
                var monitor = adapter.GetOutput(0);
                // Get modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor).
                var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced);
                // Now go through all the display modes and find the one that matches the screen width and height.
                // When a match is found store the the refresh rate for that monitor, if vertical sync is enabled.
                // Otherwise we use maximum refresh rate.
                var rational = new Rational(0, 1);
                if (VerticalSyncEnabled)
                {
                    foreach (var mode in modes)
                    {
                        if (mode.Width == configuration.Width && mode.Height == configuration.Height)
                        {
                            rational = new Rational(mode.RefreshRate.Numerator, mode.RefreshRate.Denominator);
                            break;
                        }
                    }
                }

                // Get the adapter (video card) description.
                var adapterDescription = adapter.Description;

                // Store the dedicated video card memory in megabytes.
                VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10;

                // Convert the name of the video card to a character array and store it.
                VideoCardDescription = adapterDescription.Description;

                // Release the adapter output.
                monitor.Dispose();

                // Release the adapter.
                adapter.Dispose();

                // Release the factory.
                factory.Dispose();
                #endregion

                #region Initialize swap chain and d3d device
                // Initialize the swap chain description.
                var swapChainDesc = new SwapChainDescription()
                {
                    // Set to a single back buffer.
                    BufferCount = 1,
                    // Set the width and height of the back buffer.
                    ModeDescription = new ModeDescription(configuration.Width, configuration.Height, rational, Format.R8G8B8A8_UNorm),
                    // Set the usage of the back buffer.
                    Usage = Usage.RenderTargetOutput,
                    // Set the handle for the window to render to.
                    OutputHandle = windowHandle,
                    // Turn multisampling off.
                    SampleDescription = new SampleDescription(1, 0),
                    // Set to full screen or windowed mode.
                    IsWindowed = !SystemConfiguration.FullScreen,
                    // Don't set the advanced flags.
                    Flags = SwapChainFlags.None,
                    // Discard the back buffer content after presenting.
                    SwapEffect = SwapEffect.Discard
                };

                // Create the swap chain, Direct3D device, and Direct3D device context.
                Device device;
                SwapChain swapChain;
                Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain);

                Device = device;
                SwapChain = swapChain;
                DeviceContext = device.ImmediateContext;
                #endregion

                #region Initialize buffers
                // Get the pointer to the back buffer.
                var backBuffer = Texture2D.FromSwapChain<Texture2D>(SwapChain, 0);

                // Create the render target view with the back buffer pointer.
                RenderTargetView = new RenderTargetView(device, backBuffer);

                // Release pointer to the back buffer as we no longer need it.
                backBuffer.Dispose();

                // Initialize and set up the description of the depth buffer.
                var depthBufferDesc = new Texture2DDescription()
                {
                    Width = configuration.Width,
                    Height = configuration.Height,
                    MipLevels = 1,
                    ArraySize = 1,
                    Format = Format.D24_UNorm_S8_UInt,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage = ResourceUsage.Default,
                    BindFlags = BindFlags.DepthStencil,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None
                };

                // Create the texture for the depth buffer using the filled out description.
                DepthStencilBuffer = new Texture2D(device, depthBufferDesc);
                #endregion

                #region Initialize Depth Enabled Stencil
                // Initialize and set up the description of the stencil state.
                var depthStencilDesc = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = true,
                    DepthWriteMask = DepthWriteMask.All,
                    DepthComparison = Comparison.Less,
                    IsStencilEnabled = true,
                    StencilReadMask = 0xFF,
                    StencilWriteMask = 0xFF,
                    // Stencil operation if pixel front-facing.
                    FrontFace = new DepthStencilOperationDescription()
                    {
                        FailOperation = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Increment,
                        PassOperation = StencilOperation.Keep,
                        Comparison = Comparison.Always
                    },
                    // Stencil operation if pixel is back-facing.
                    BackFace = new DepthStencilOperationDescription()
                    {
                        FailOperation = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Decrement,
                        PassOperation = StencilOperation.Keep,
                        Comparison = Comparison.Always
                    }
                };

                // Create the depth stencil state.
                DepthStencilState = new DepthStencilState(Device, depthStencilDesc);
                #endregion

                #region Initialize Output Merger
                // Set the depth stencil state.
                DeviceContext.OutputMerger.SetDepthStencilState(DepthStencilState, 1);

                // Initialize and set up the depth stencil view.
                var depthStencilViewDesc = new DepthStencilViewDescription()
                {
                    Format = Format.D24_UNorm_S8_UInt,
                    Dimension = DepthStencilViewDimension.Texture2D,
                    Texture2D = new DepthStencilViewDescription.Texture2DResource()
                    {
                        MipSlice = 0
                    }
                };

                // Create the depth stencil view.
                DepthStencilView = new DepthStencilView(Device, DepthStencilBuffer, depthStencilViewDesc);

                // Bind the render target view and depth stencil buffer to the output render pipeline.
                DeviceContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView);
                #endregion

                #region Initialize Raster State
                // Setup the raster description which will determine how and what polygon will be drawn.
                var rasterDesc = new RasterizerStateDescription()
                {
                    IsAntialiasedLineEnabled = false,
                    CullMode = CullMode.Back,
                    DepthBias = 0,
                    DepthBiasClamp = .0f,
                    IsDepthClipEnabled = true,
                    FillMode = FillMode.Solid,
                    IsFrontCounterClockwise = false,
                    IsMultisampleEnabled = false,
                    IsScissorEnabled = false,
                    SlopeScaledDepthBias = .0f
                };

                // Create the rasterizer state from the description we just filled out.
                RasterState = new RasterizerState(Device, rasterDesc);
                #endregion

                #region Initialize Rasterizer
                // Now set the rasterizer state.
                DeviceContext.Rasterizer.State = RasterState;

                // Setup and create the viewport for rendering.
                DeviceContext.Rasterizer.SetViewport(0, 0, configuration.Width, configuration.Height, 0, 1);
                #endregion

                #region Initialize matrices
                // Setup and create the projection matrix.
                ProjectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4f), ((float)configuration.Width / configuration.Height), SystemConfiguration.ScreenNear, SystemConfiguration.ScreenDepth);

                // Initialize the world matrix to the identity matrix.
                WorldMatrix = Matrix.Identity;

                // Create an orthographic projection matrix for 2D rendering.
                OrthoMatrix = Matrix.OrthoLH(configuration.Width, configuration.Height, SystemConfiguration.ScreenNear, SystemConfiguration.ScreenDepth);
                #endregion

                #region Initialize Depth Disabled Stencil
                // Now create a second depth stencil state which turns off the Z buffer for 2D rendering.
                // The difference is that DepthEnable is set to false.
                // All other parameters are the same as the other depth stencil state.
                var depthDisabledStencilDesc = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = false,
                    DepthWriteMask = DepthWriteMask.All,
                    DepthComparison = Comparison.Less,
                    IsStencilEnabled = true,
                    StencilReadMask = 0xFF,
                    StencilWriteMask = 0xFF,
                    // Stencil operation if pixel front-facing.
                    FrontFace = new DepthStencilOperationDescription()
                    {
                        FailOperation = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Increment,
                        PassOperation = StencilOperation.Keep,
                        Comparison = Comparison.Always
                    },
                    // Stencil operation if pixel is back-facing.
                    BackFace = new DepthStencilOperationDescription()
                    {
                        FailOperation = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Decrement,
                        PassOperation = StencilOperation.Keep,
                        Comparison = Comparison.Always
                    }
                };

                // Create the depth stencil state.
                DepthDisabledStencilState = new DepthStencilState(Device, depthDisabledStencilDesc);
                #endregion

                #region Initialize Blend States
                // Create an alpha enabled blend state description.
                var blendStateDesc = new BlendStateDescription();
                blendStateDesc.RenderTarget[0].IsBlendEnabled = true;
                blendStateDesc.RenderTarget[0].SourceBlend = BlendOption.One;
                blendStateDesc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha;
                blendStateDesc.RenderTarget[0].BlendOperation = BlendOperation.Add;
                blendStateDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
                blendStateDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
                blendStateDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
                blendStateDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
                // Create the blend state using the description.
                AlphaEnableBlendingState = new BlendState(device, blendStateDesc);

                // Modify the description to create an disabled blend state description.
                blendStateDesc.RenderTarget[0].IsBlendEnabled = false;
                // Create the blend state using the description.
                AlphaDisableBlendingState = new BlendState(device, blendStateDesc);
                #endregion

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
Beispiel #3
0
        public DX(int width, int height, float screenDepth, float screenNear, bool vSync, bool fullScreen, IntPtr hwnd)
        {
            this.vSync = vSync;
            var factory = new Factory();
            var adapter = factory.GetAdapter(0);
            var monitor = adapter.Outputs[0];
            var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced);

            var rational = new Rational(0, 1);
            if(vSync)
            {
                foreach(var mode in modes)
                {
                    if(mode.Width == width && mode.Height == height)
                    {
                        rational = new Rational(mode.RefreshRate.Numerator, mode.RefreshRate.Denominator);
                        break;
                    }
                }
            }

            monitor.Dispose();
            adapter.Dispose();
            factory.Dispose();

            var swapChainDesc = new SwapChainDescription
            {
                BufferCount = 1,
                ModeDescription = new ModeDescription(width, height, rational, Format.R8G8B8A8_UNorm),
                Usage = Usage.RenderTargetOutput,
                OutputHandle = hwnd,
                SampleDescription = new SampleDescription(1, 0),
                IsWindowed = !fullScreen,
                Flags = SwapChainFlags.None,
                SwapEffect = SwapEffect.Discard
            };

            Device device;
            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, new[] {FeatureLevel.Level_10_0}, swapChainDesc, out device, out swapChain);

            DXDevice = device;
            DXContext = device.ImmediateContext;

            var backBuffer = Resource.FromSwapChain<Texture2D>(swapChain, 0);
            renderTarget = new RenderTargetView(device, backBuffer);
            backBuffer.Dispose();

            var depthBufferDesc = new Texture2DDescription
            {
                Width = width,
                Height = height,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.D24_UNorm_S8_UInt,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None
            };
            depthStenBuffer = new Texture2D(device, depthBufferDesc);

            var depthStencilDesc = new DepthStencilStateDescription
            {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less,
                IsStencilEnabled = true,
                StencilReadMask = 0xFF,
                StencilWriteMask = 0xFF,
                FrontFace = new DepthStencilOperationDescription
                {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Increment,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Always
                },
                BackFace = new DepthStencilOperationDescription
                {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Decrement,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Always
                }
            };

            depthStenState = new DepthStencilState(DXDevice, depthStencilDesc);

            DXContext.OutputMerger.SetDepthStencilState(depthStenState, 1);

            var depthStencilViewDesc = new DepthStencilViewDescription
            {
                Format = Format.D24_UNorm_S8_UInt,
                Dimension = DepthStencilViewDimension.Texture2D,
                Texture2D = new DepthStencilViewDescription.Texture2DResource
                {
                    MipSlice = 0
                }
            };

            depthStenView = new DepthStencilView(DXDevice, depthStenBuffer, depthStencilViewDesc);
            DXContext.OutputMerger.SetTargets(depthStenView, renderTarget);

            var rasterDesc = new RasterizerStateDescription
            {
                IsAntialiasedLineEnabled = false,
                CullMode = CullMode.Back,
                DepthBias = 0,
                DepthBiasClamp = .0f,
                IsDepthClipEnabled = true,
                FillMode = FillMode.Solid,
                IsFrontCounterClockwise = false,
                IsMultisampleEnabled = false,
                IsScissorEnabled = false,
                SlopeScaledDepthBias = .0f
            };

            rasterState = new RasterizerState(DXDevice, rasterDesc);
            DXContext.Rasterizer.State = rasterState;
            DXContext.Rasterizer.SetViewport(0, 0, width, height);

            Projection = Matrix.PerspectiveFovLH((float) (Math.PI / 4), ((float) width) / height, screenNear, screenDepth);
            World = Matrix.Identity;
            Ortho = Matrix.OrthoLH(width, height, screenNear, screenDepth);

            OnCleanup += swapChain.Dispose;
            OnCleanup += rasterState.Dispose;
            OnCleanup += depthStenBuffer.Dispose;
            OnCleanup += depthStenState.Dispose;
            OnCleanup += depthStenView.Dispose;
            OnCleanup += renderTarget.Dispose;
            OnCleanup += DXContext.Dispose;
            OnCleanup += DXDevice.Dispose;
        }
Beispiel #4
0
        public override void Hook()
        {
            this.DebugMessage("Hook: Begin");

            // Determine method addresses in Direct3D10.Device, and DXGI.SwapChain
            if (_d3d10VTblAddresses == null)
            {
                _d3d10VTblAddresses = new List<IntPtr>();
                _dxgiSwapChainVTblAddresses = new List<IntPtr>();
                this.DebugMessage("Hook: Before device creation");
                using (var factory = new Factory())
                {
                    using (var device = new Device(factory.GetAdapter(0), DeviceCreationFlags.None))
                    {
                        this.DebugMessage("Hook: Device created");
                        _d3d10VTblAddresses.AddRange(GetVTblAddresses(device.NativePointer, D3D10_DEVICE_METHOD_COUNT));

                        using (var renderForm = new System.Windows.Forms.Form())
                        {
                            using (SharpDX.DXGI.SwapChain sc = new SharpDX.DXGI.SwapChain(factory, device, DXGI.CreateSwapChainDescription(renderForm.Handle)))
                            {
                                _dxgiSwapChainVTblAddresses.AddRange(GetVTblAddresses(sc.NativePointer, DXGI.DXGI_SWAPCHAIN_METHOD_COUNT));
                            }
                        }
                    }
                }
            }

            // We will capture the backbuffer here
            DXGISwapChain_PresentHook = new Hook<DXGISwapChain_PresentDelegate>(
                _dxgiSwapChainVTblAddresses[(int)DXGI.DXGISwapChainVTbl.Present],
                new DXGISwapChain_PresentDelegate(PresentHook),
                this);

            // We will capture target/window resizes here
            DXGISwapChain_ResizeTargetHook = new Hook<DXGISwapChain_ResizeTargetDelegate>(
                _dxgiSwapChainVTblAddresses[(int)DXGI.DXGISwapChainVTbl.ResizeTarget],
                new DXGISwapChain_ResizeTargetDelegate(ResizeTargetHook),
                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.
             */
            DXGISwapChain_PresentHook.Activate();

            DXGISwapChain_ResizeTargetHook.Activate();

            Hooks.Add(DXGISwapChain_PresentHook);
            Hooks.Add(DXGISwapChain_ResizeTargetHook);
        }
        /// <summary>
        /// Initializes a new engine, sets view , tex manager
        /// camera , mesh manager , texture manager , line manager
        /// volume manager
        /// </summary>
        /// <param name="width">The width of the Render target</param>
        /// <param name="height">The height of the Render target</param>
        public Engine(int Width, int Height, Form form)
        {
            // pass the settings of resolution
            Settings.Resolution = new System.Drawing.Size(Width, Height);

            /// set the handles for full screen or windows
            this.form = form;
            this.FormHandle = form.Handle;

            /// Create the factory which manages general graphics resources
            g_factory = new Factory();
            g_factory.MakeWindowAssociation(this.FormHandle, WindowAssociationFlags.IgnoreAll);

            // find correct adapter
            int adapterCount = g_factory.GetAdapterCount();
            //MessageBox.Show(adapterCount.ToString());

            // we try to select the PerfHUD adapter
            for (int i = 0; i < adapterCount; i++)
            {
                Adapter adapt = g_factory.GetAdapter(i);
                //MessageBox.Show(adapt.Description.Description);

                if (adapt.Description.Description == "NVIDIA PerfHUD")
                {
                    g_device = new Device(
                        adapt,
                        DeviceCreationFlags.Debug);
                }

                Console.WriteLine(i.ToString() + adapt.Description.Description);
            }

            if (g_device == null)
            {

            #if true
                /// Create the DirectX Device
                g_device = new Device(g_factory.GetAdapter(1),
                                      (Settings.Debug) ? DeviceCreationFlags.Debug : DeviceCreationFlags.None,
                                      new FeatureLevel[] { FeatureLevel.Level_11_0 });

            #else
                g_device = new Device(DriverType.Warp,
                                        (Settings.Debug) ? DeviceCreationFlags.Debug : DeviceCreationFlags.None,
                                        new FeatureLevel[] { FeatureLevel.Level_11_0 });
            #endif

                // check if we have one device to our system
                if (!(((g_device.FeatureLevel & FeatureLevel.Level_10_0) != 0) || ((g_device.FeatureLevel & FeatureLevel.Level_10_1) != 0) || ((g_device.FeatureLevel & FeatureLevel.Level_11_0) != 0)))
                {
                    // if we don't have we just simulate
                    #region Create the device base on swapChain
                    /// Create a description of the display mode
                    g_modeDesc = new ModeDescription();
                    /// Standard 32-bit RGBA
                    g_modeDesc.Format = Format.R8G8B8A8_UNorm;
                    /// Refresh rate of 60Hz (60 / 1 = 60)
                    g_modeDesc.RefreshRate = new Rational(60, 1);
                    /// Default
                    g_modeDesc.Scaling = DisplayModeScaling.Unspecified;
                    g_modeDesc.ScanlineOrdering = DisplayModeScanlineOrder.Progressive;

                    /// ClientSize is the size of the
                    /// form without the title and borders
                    g_modeDesc.Width = Width;
                    g_modeDesc.Height = Height;

                    /// Create a description of the samping
                    /// for multisampling or antialiasing
                    g_sampleDesc = new SampleDescription();
                    /// No multisampling
                    g_sampleDesc.Count = 1;
                    g_sampleDesc.Quality = 0;

                    /// Create a description of the swap
                    /// chain or front and back buffers
                    g_swapDesc = new SwapChainDescription();
                    /// link the ModeDescription
                    g_swapDesc.ModeDescription = g_modeDesc;
                    /// link the SampleDescription
                    g_swapDesc.SampleDescription = g_sampleDesc;
                    /// Number of buffers (including the front buffer)
                    g_swapDesc.BufferCount = 1;
                    g_swapDesc.Flags = SwapChainFlags.AllowModeSwitch;
                    g_swapDesc.IsWindowed = true;
                    /// The output window (the windows being rendered to)
                    g_swapDesc.OutputHandle = this.FormHandle;
                    /// Scrap the contents of the buffer every frame
                    g_swapDesc.SwapEffect = SwapEffect.Discard;
                    /// Indicate that this SwapChain
                    /// is going to be a Render target
                    g_swapDesc.Usage = Usage.RenderTargetOutput;

                    //g_swapChain = new SwapChain(g_factory, g_device, g_swapDesc);

                    try
                    {
                        /// Create the actual swap chain
                        /// Here we set and the device type
                        Device.CreateWithSwapChain(DriverType.Warp, (Settings.Debug) ? DeviceCreationFlags.Debug : DeviceCreationFlags.None, new FeatureLevel[] { Settings.FeatureLevel }, g_swapDesc, out g_device, out g_swapChain);
                    }
                    catch (Exception ex)
                    {
                        /// Create the actual swap chain
                        /// Here we set and the device type
                        Device.CreateWithSwapChain(DriverType.Reference, (Settings.Debug) ? DeviceCreationFlags.Debug : DeviceCreationFlags.None, new FeatureLevel[] { Settings.FeatureLevel }, g_swapDesc, out g_device, out g_swapChain);
                    }

                    /// Create the factory which manages general graphics resources
                    g_factory = g_swapChain.GetParent<Factory>();

                    g_factory.MakeWindowAssociation(this.FormHandle, WindowAssociationFlags.IgnoreAll);
                    #endregion
                }
                else
                {
            #if false

                    #region Create the device base on swapChain
                    /// Create a description of the display mode
                    g_modeDesc = new ModeDescription();
                    /// Standard 32-bit RGBA
                    g_modeDesc.Format = Format.R8G8B8A8_UNorm;
                    /// Refresh rate of 60Hz (60 / 1 = 60)
                    g_modeDesc.RefreshRate = new Rational(60, 1);
                    /// Default
                    g_modeDesc.Scaling = DisplayModeScaling.Unspecified;
                    g_modeDesc.ScanlineOrdering = DisplayModeScanlineOrdering.Progressive;

                    /// ClientSize is the size of the
                    /// form without the title and borders
                    g_modeDesc.Width = Width;
                    g_modeDesc.Height = Height;

                    /// Create a description of the samping
                    /// for multisampling or antialiasing
                    g_sampleDesc = new SampleDescription();
                    /// No multisampling
                    g_sampleDesc.Count = 1;
                    g_sampleDesc.Quality = 0;

                    /// Create a description of the swap
                    /// chain or front and back buffers
                    g_swapDesc = new SwapChainDescription();
                    /// link the ModeDescription
                    g_swapDesc.ModeDescription = g_modeDesc;
                    /// link the SampleDescription
                    g_swapDesc.SampleDescription = g_sampleDesc;
                    /// Number of buffers (including the front buffer)
                    g_swapDesc.BufferCount = 1;
                    g_swapDesc.Flags = SwapChainFlags.None;
                    g_swapDesc.IsWindowed = true;
                    /// The output window (the windows being rendered to)
                    g_swapDesc.OutputHandle = FormHandle;
                    /// Scrap the contents of the buffer every frame
                    g_swapDesc.SwapEffect = SwapEffect.Discard;
                    /// Indicate that this SwapChain
                    /// is going to be a Render target
                    g_swapDesc.Usage = Usage.RenderTargetOutput;

                    g_swapChain = new SwapChain(g_factory, g_device, g_swapDesc);

                    #endregion
            #endif
                }

                // set the feature level
                Settings.FeatureLevel = g_device.FeatureLevel;
            }

            /// init mesh manager
            g_MeshManager = new Object3DManager();

            /// init deferred device
            //DeferredDev1 = new DeviceContext( Engine.g_device );
            //DeferredDev2 = new DeviceContext( Engine.g_device );

            // init the image factory...
            g_image_factory = new ImagingFactory();

            /// Set flag to indicate that engine is running
            g_Running = true;

            Logger.WriteLine("The Graphing Engine have be start ");

            // set the event handler
            RenderLoopHandler = new EventHandler(RenderLoop);

            var rtb = new RenderTargetBlendDescription()
            {
                IsBlendEnabled = true,
                BlendOperation = BlendOperation.Add,
                AlphaBlendOperation = BlendOperation.Add,
                DestinationBlend = BlendOption.One,
                DestinationAlphaBlend = BlendOption.Zero,
                SourceBlend = BlendOption.One,
                SourceAlphaBlend = BlendOption.One,
                RenderTargetWriteMask = ColorWriteMaskFlags.All
            };

            BlendStateDescription blendDesc = new BlendStateDescription();
            blendDesc.AlphaToCoverageEnable = false;
            blendDesc.IndependentBlendEnable = false;
            blendDesc.RenderTarget[0] = rtb;

            g_blendState = new BlendState(g_device, blendDesc);

            DepthStencilStateDescription dssd = new DepthStencilStateDescription();
            dssd.DepthComparison = Comparison.Less;
            dssd.IsDepthEnabled = true;
            g_depthStencilState = new DepthStencilState(g_device, new DepthStencilStateDescription());
        }
        public StartForm()
        {
            this.BackgroundImage = null;
            bool FileFail = false;
            InitializeComponent();
            FileStream fs = null;
            try
            {
                fs = new FileStream("Config.bin", FileMode.Open, FileAccess.Read);
                config = Serializer.Deserialize<Config>(fs);
                fs.Close();
            }
            catch(Exception ex)
            {
                FileFail = true;
                if (fs != null) fs.Close();
                System.Windows.Forms.MessageBox.Show("Error! Небыл найден файл настроек\n" + ex.Message);
            }

            ModeDescription[] DML = null;

            using (SharpDX.DXGI.Factory myFactory = new SharpDX.DXGI.Factory())
            {

                int MyAdapterCount = myFactory.GetAdapterCount();
                try
                {
                    using (SharpDX.DXGI.Adapter MyAdapter = myFactory.GetAdapter(MyAdapterCount - 1))
                    {
                        using (Output OP = MyAdapter.Outputs[0])
                            DML = OP.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced);
                    }

                }
                catch (System.Exception ex)
                {
                    using (SharpDX.DXGI.Adapter MyAdapter = myFactory.GetAdapter(MyAdapterCount - 0))
                    {
                        using (Output OP = MyAdapter.Outputs[0])
                            DML = OP.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced);
                    }
                }
            }

            int mw = 0, mh = 0;
            foreach (ModeDescription dm in DML)
            {
                bool cor = true;
                foreach (DisplayMode dmd in LDM)
                {
                    if (dmd.Width == dm.Width && dmd.Height == dm.Height)
                    {
                        cor = false;
                    }
                }

                if (cor && dm.Width >= 1024 && dm.Height >= 768)
                    LDM.Add(new DisplayMode(dm.Width, dm.Height));

                if (dm.Width > mw) mw = dm.Width;
                if (dm.Height > mh) mh = dm.Height;
            }

            if (LDM.Count < 1)
            {
                System.Windows.Forms.MessageBox.Show("Error! Минимальное поддерживаемое разрешение экрана 1024х768");
                this.Close();
            }

            if (config.Width > mw || config.Height > mh)
            {
                FileFail = true;
            }

            if (GetResIndex(config.Width, config.Height, LDM) < 0)
                FileFail = true;

            if (FileFail)
            {
                config = new Config();
                SaveC(config, "Config.bin");
            }
            SetData();

            for (int num = 0; num < LDM.Count; num++)
            {
                comboBox1.Items.Add(LDM[num].Width.ToString() + "x" + LDM[num].Height.ToString());
            }

            int Res = GetResIndex(config.Width, config.Height, LDM);

            if (Res > -1)
            {
                comboBox1.SelectedIndex = Res;
            }

            if (config.VSync>0)
            {
                checkBox1.Checked = true;
            }
            else
            {
                checkBox1.Checked = false;
            }

            if (config.InvAlt > 0)
            {
                checkBox3.Checked = true;
            }
            else
            {
                checkBox3.Checked = false;
            }

            comboBox2.Items.Add("High");
            comboBox2.Items.Add("Medium");
            comboBox2.Items.Add("Low");
            comboBox2.Items.Add("Disable");

            if (config.Shadow < 1)
            {
                comboBox2.SelectedIndex = 3;
            }
            else
            {
                comboBox2.SelectedIndex = config.ShadowQuality;
            }

            comboBox3.Items.Add("Disable");
            comboBox3.Items.Add("Low");
            comboBox3.Items.Add("Medium");
            comboBox3.Items.Add("High");

            if (config.MultiSample > -1 && config.MultiSample < 2)
            {
                comboBox3.SelectedIndex = 0;
            }
            if (config.MultiSample > 1 && config.MultiSample < 4)
            {
                comboBox3.SelectedIndex = 1;
            }
            if (config.MultiSample > 3 && config.MultiSample < 8)
            {
                comboBox3.SelectedIndex = 2;
            }
            if (config.MultiSample > 7)
            {
                comboBox3.SelectedIndex = 3;
            }

            comboBox4.Items.Add("Disable");
            comboBox4.Items.Add("4");
            comboBox4.Items.Add("8");
            comboBox4.Items.Add("12");

            if (config.Light > -1 && config.Light < 4)
            {
                comboBox4.SelectedIndex = 0;
            }
            if (config.Light > 3 && config.Light < 7)
            {
                comboBox4.SelectedIndex = 1;
            }
            if (config.Light > 7 && config.Light < 11)
            {
                comboBox4.SelectedIndex = 2;
            }
            if (config.Light > 11)
            {
                comboBox4.SelectedIndex = 3;
            }

            if (config.FullScr > 0)
            {
                checkBox2.Checked = true;
            }
            else
            {
                checkBox2.Checked = false;
            }

            if (config.Refract > 0)
            {
                checkBox4.Checked = true;
            }
            else
            {
                checkBox4.Checked = false;
            }
        }
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            LDM.Clear();

            ModeDescription[] DML = null;
            using (SharpDX.DXGI.Factory myFactory = new SharpDX.DXGI.Factory())
            {

                int MyAdapterCount = myFactory.GetAdapterCount();
                try
                {
                    using (SharpDX.DXGI.Adapter MyAdapter = myFactory.GetAdapter(MyAdapterCount - 1))
                    {
                        using (Output OP = MyAdapter.Outputs[0])
                            DML = OP.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced);
                    }

                }
                catch (System.Exception ex)
                {
                    using (SharpDX.DXGI.Adapter MyAdapter = myFactory.GetAdapter(MyAdapterCount - 0))
                    {
                        using (Output OP = MyAdapter.Outputs[0])
                            DML = OP.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced);
                    }
                }
            }

            foreach (ModeDescription dm in DML)
            {
                bool cor = true;
                foreach (DisplayMode dmd in LDM)
                {
                    if (dmd.Width == dm.Width && dmd.Height == dm.Height)
                    {
                        cor = false;
                    }
                }

                if (cor && dm.Width >= 1024 && dm.Height >= 768)
                    LDM.Add(new DisplayMode(dm.Width, dm.Height));
            }

            config.Width = LDM[comboBox1.SelectedIndex].Width;
            config.Height = LDM[comboBox1.SelectedIndex].Height;
            SetData();
        }
Beispiel #8
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="dg"></param>
 /// <returns></returns>
 public static IEnumerable<Adapter> GetAdapters(DisposeGroup dg)
 {
     // NOTE: SharpDX 1.3 requires explicit Dispose() of everything
     // hence the DisposeGroup, to enforce it
     using (var f = new Factory())
     {
         int n = AdapterCount;
         for (int i = 0; i < n; i++)
             yield return dg.Add(f.GetAdapter(i));
     }
 }
Beispiel #9
0
        /// <summary>
        /// Crée le Device DirectX 10 et initialise les resources
        /// </summary>
        public void Initialize(int width, int height)
        {
            if (width <= 2)
                throw new ArgumentOutOfRangeException("width");
            else if (height <= 2)
                throw new ArgumentOutOfRangeException("height");

            Width = width;
            Height = height;

            Clean();

            hwndRenderingWindow = new Form();
            hwndRenderingWindow.Width = hwndRenderingWindow.Height = 100;

            var desc = new SwapChainDescription()
            {
                BufferCount = 1,
                ModeDescription =
                    new ModeDescription(Width, Height,
                                        new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed = true,
                OutputHandle = hwndRenderingWindow.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect = SwapEffect.Discard,
                Usage = Usage.RenderTargetOutput
            };

            // Create Device and SwapChain
            //Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, desc, out device, out swapChain);
            Factory factory = new Factory();
            var adapter = factory.GetAdapter(0);
            device = new Device(adapter, DeviceCreationFlags.BgraSupport, SharpDX.Direct3D10.FeatureLevel.Level_10_0);
            swapChain = new SwapChain(factory, device, desc);

            //device = new Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport, SharpDX.Direct3D10.FeatureLevel.Level_10_0);

            Texture2DDescription colordesc = new Texture2DDescription
            {
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                Format = Format.B8G8R8A8_UNorm,
                Width = width,
                Height = height,
                MipLevels = 1,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                OptionFlags = ResourceOptionFlags.Shared,
                CpuAccessFlags = CpuAccessFlags.None,
                ArraySize = 1
            };

            renderBuffer = new Texture2D(device, colordesc);
            renderView = new RenderTargetView(device, renderBuffer);

            LoadRenderShader();

            wpfImage = new DX10ImageSource();
            wpfImage.SetRenderTargetDX10(renderBuffer);

            RaisePropertyChanged("WPFImage");
        }