public InfoText(Device device)
        {
            this.device = device;
            outputMerger = device.OutputMerger;

            font = new Font(device, 20, 0, FontWeight.Normal, 0, false, FontCharacterSet.Default,
              FontPrecision.Default, FontQuality.ClearTypeNatural, FontPitchAndFamily.DontCare, "tahoma");

            renderTexture = new Texture2D(device, new Texture2DDescription()
            {
                ArraySize = 1,
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.R8G8B8A8_UNorm,
                Height = rect.Height,
                Width = rect.Width,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default
            });
            renderTextureView = new RenderTargetView(device, renderTexture);
            renderViews = new[] { renderTextureView };

            OverlayBufferRes = new ShaderResourceView(device, renderTexture, new ShaderResourceViewDescription()
            {
                Format = Format.R8G8B8A8_UNorm,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource()
                {
                    MipLevels = 1,
                    MostDetailedMip = 0
                }
            });
        }
 /// <summary>	
 /// Get references to the render targets that are available to the {{output-merger stage}}.	
 /// </summary>	
 /// <remarks>	
 /// Any returned interfaces will have their reference count incremented by one. Applications should call {{IUnknown::Release}} on the returned interfaces when they are no longer needed to avoid memory leaks. 	
 /// </remarks>	
 /// <param name="numViews">Number of render targets to retrieve. </param>
 /// <returns>an array of render targets views (see <see cref="SharpDX.Direct3D10.RenderTargetView"/>) to be filled with the render targets from the device.</returns>
 /// <unmanaged>void OMGetRenderTargets([In] int NumViews,[Out, Buffer, Optional] ID3D10RenderTargetView** ppRenderTargetViews,[Out, Optional] ID3D10DepthStencilView** ppDepthStencilView)</unmanaged>
 public SharpDX.Direct3D10.RenderTargetView[] GetRenderTargets(int numViews)
 {
     var renderTargets = new RenderTargetView[numViews];
     DepthStencilView depthStencilView;
     GetRenderTargets(numViews, renderTargets, out depthStencilView);
     if (depthStencilView != null)
         depthStencilView.Dispose();
     return renderTargets;
 }
        //*******************************************************//
        //                      METHODS                          //
        //*******************************************************//
        public void Initialize(Device1 device, RenderTargetView renderTarget, DX10RenderCanvas canvasControl)
        {
            _Device = device;

            _RenderTargetView = renderTarget;
            _RenderControl = canvasControl;
            _Camera = new Camera();
            _Gizmo = new Gizmo(_Device);
            
            GameObjectManager.Instance().Initialize(device);
            InputManager.Initialize();

        }
        public Direct3D10RenderContext(Window window)
        {
            SwapChainDescription desc = new SwapChainDescription
            {
                BufferCount = 1,
                ModeDescription = new ModeDescription(window.Width, window.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed = true,
                OutputHandle = window.DisplayHandle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect = SwapEffect.Discard,
                Usage = Usage.RenderTargetOutput
            };

            Device1.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, desc, FeatureLevel.Level_10_0, out m_device, out m_swapChain);

            Factory factory = m_swapChain.GetParent<Factory>();
            factory.MakeWindowAssociation(window.DisplayHandle, WindowAssociationFlags.IgnoreAll);

            m_backBuffer = Resource.FromSwapChain<Texture2D>(m_swapChain, 0);

            m_backBufferView = new RenderTargetView(m_device, m_backBuffer);
        }
Beispiel #5
0
        protected void CreateSizeDependentComponents()
        {
            backBuffer     = Direct3D.Resource.FromSwapChain <Direct3D.Texture2D>(swapChain, 0);
            backBufferView = new Direct3D.RenderTargetView(device, backBuffer);

            factory        = new Direct2D1.Factory();
            imagingFactory = new ImagingFactory();

            using (var surface = backBuffer.QueryInterface <DXGI.Surface>()) {
                renderTarget = new Direct2D1.RenderTarget(factory, surface,
                                                          new Direct2D1.RenderTargetProperties(new Direct2D1.PixelFormat(DXGI.Format.Unknown, Direct2D1.AlphaMode.Premultiplied)));
            }

            renderTarget.AntialiasMode     = Direct2D1.AntialiasMode.PerPrimitive;
            renderTarget.TextAntialiasMode = Direct2D1.TextAntialiasMode.Cleartype;

            var imageLoader = ImageLoader as ImageLoader;

            if (imageLoader != null)
            {
                imageLoader.ReloadAll();
            }
        }
 /// <summary>
 ///   Binds a single render target to the output-merger stage.
 /// </summary>
 /// <param name = "renderTargetView">A view of the render target to bind.</param>
 public void SetTargets(RenderTargetView renderTargetView)
 {
     SetTargets((DepthStencilView)null, renderTargetView);
 }
Beispiel #7
0
        protected override void Initialize(DemoConfiguration demoConfiguration)
        {
            // SwapChain description
            var desc = new SwapChainDescription()
            {
                BufferCount = 1,
                ModeDescription = 
                    new ModeDescription(demoConfiguration.Width, demoConfiguration.Height,
                                        new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed = true,
                OutputHandle = DisplayHandle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect = SwapEffect.Discard,
                Usage = Usage.RenderTargetOutput
            };

            // Create Device and SwapChain
            Device1.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, desc, FeatureLevel.Level_10_0, out _device, out _swapChain);

            // Ignore all windows events
            Factory factory = _swapChain.GetParent<Factory>();
            factory.MakeWindowAssociation(DisplayHandle, WindowAssociationFlags.IgnoreAll);

            // New RenderTargetView from the backbuffer
            _backBuffer = Texture2D.FromSwapChain<Texture2D>(_swapChain, 0);

            _backBufferView = new RenderTargetView(_device, _backBuffer);


        }
Beispiel #8
0
        private static void Main()
        {
            var form = new RenderForm("SharpDX - MiniCube Direct3D 10 Sample");

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

            // Create Device and SwapChain
            Device device;
            SwapChain swapChain;
            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain);
            var context = device;

            // Ignore all windows events
            var factory = swapChain.GetParent<Factory>();
            factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            // New RenderTargetView from the backbuffer
            var backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            var renderView = new RenderTargetView(device, backBuffer);

            // Compile Vertex and Pixel shaders
            var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "VS", "vs_4_0");
            var vertexShader = new VertexShader(device, vertexShaderByteCode);

            var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "PS", "ps_4_0");
            var pixelShader = new PixelShader(device, pixelShaderByteCode);

            // Layout from VertexShader input signature
            var layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[]
                    {
                        new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                        new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
                    });

            // Instantiate Vertex buiffer from vertex data
            var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[]
                                  {
                                      new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), // Front
                                      new Vector4(-1.0f,  1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),

                                      new Vector4(-1.0f, -1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), // BACK
                                      new Vector4( 1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f, -1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f, -1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),

                                      new Vector4(-1.0f, 1.0f, -1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), // Top
                                      new Vector4(-1.0f, 1.0f,  1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, 1.0f,  1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f, 1.0f, -1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, 1.0f,  1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, 1.0f, -1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),

                                      new Vector4(-1.0f,-1.0f, -1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), // Bottom
                                      new Vector4( 1.0f,-1.0f,  1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f,-1.0f,  1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f,-1.0f, -1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,-1.0f, -1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,-1.0f,  1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),

                                      new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), // Left
                                      new Vector4(-1.0f, -1.0f,  1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f,  1.0f,  1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f,  1.0f,  1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f,  1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),

                                      new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), // Right
                                      new Vector4( 1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, -1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                            });

            // Create Constant Buffer
            var contantBuffer = new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None);

            // Create Depth Buffer & View
            var depthBuffer = new Texture2D(device, new Texture2DDescription()
                    {
                        Format = Format.D32_Float_S8X24_UInt,
                        ArraySize = 1,
                        MipLevels = 1,
                        Width = form.ClientSize.Width,
                        Height = form.ClientSize.Height,
                        SampleDescription = new SampleDescription(1, 0),
                        Usage = ResourceUsage.Default,
                        BindFlags = BindFlags.DepthStencil,
                        CpuAccessFlags = CpuAccessFlags.None,
                        OptionFlags = ResourceOptionFlags.None
                    });

            var depthView = new DepthStencilView(device, depthBuffer);

            // Prepare All the stages
            context.InputAssembler.InputLayout = layout;
            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, Utilities.SizeOf<Vector4>() * 2, 0));
            context.VertexShader.SetConstantBuffer(0, contantBuffer);
            context.VertexShader.Set(vertexShader);
            context.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
            context.PixelShader.Set(pixelShader);

            // Prepare matrices
            var view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY);
            var proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, 0.1f, 100.0f);
            var viewProj = Matrix.Multiply(view, proj);

            // Use clock
            var clock = new Stopwatch();
            clock.Start();

            // Main loop
            RenderLoop.Run(form, () =>
                {
                    var time = clock.ElapsedMilliseconds / 1000.0f;

                    // Clear views
                    context.OutputMerger.SetTargets(depthView, renderView);

                    context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0);
                    context.ClearRenderTargetView(renderView, Color.Black);

                    // Update WorldViewProj Matrix
                    var worldViewProj = Matrix.RotationX(time) * Matrix.RotationY(time * 2) * Matrix.RotationZ(time * .7f) * viewProj;
                    worldViewProj.Transpose();
                    context.UpdateSubresource(ref worldViewProj, contantBuffer);

                    // Draw the cube
                    context.Draw(36, 0);

                    // Present!
                    swapChain.Present(0, PresentFlags.None);
                });

            // Release all resources
            vertexShaderByteCode.Dispose();
            vertexShader.Dispose();
            pixelShaderByteCode.Dispose();
            pixelShader.Dispose();
            vertices.Dispose();
            layout.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            context.ClearState();
            context.Flush();
            device.Dispose();
            context.Dispose();
            swapChain.Dispose();
            factory.Dispose();
        }
        public void Dispose()
        {
            if (renderTexture != null)
            {
                renderTexture.Dispose();
                renderTexture = null;
            }

            if (renderTextureView != null)
            {
                renderTextureView.Dispose();
                renderTextureView = null;
            }
        }
Beispiel #10
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");
        }
        void CreateBuffers()
        {
            DisposeBuffers();

            // New RenderTargetView from the backbuffer
            using (var bb = Texture2D.FromSwapChain<Texture2D>(_swapChain, 0))
            {
                renderView = new RenderTargetView(_device, bb);
                renderViews[0] = renderView;
            }

            Texture2DDescription gBufferDesc = new Texture2DDescription()
            {
                ArraySize = 1,
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.R8G8B8A8_UNorm,
                Width = _width,
                Height = _height,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default
            };

            gBufferLight = new Texture2D(_device, gBufferDesc);
            gBufferLightView = new RenderTargetView(_device, gBufferLight);

            gBufferNormal = new Texture2D(_device, gBufferDesc);
            gBufferNormalView = new RenderTargetView(_device, gBufferNormal);

            gBufferDiffuse = new Texture2D(_device, gBufferDesc);
            gBufferDiffuseView = new RenderTargetView(_device, gBufferDiffuse);

            gBufferViews = new RenderTargetView[] { gBufferLightView, gBufferNormalView, gBufferDiffuseView };

            ShaderResourceViewDescription gBufferResourceDesc = new ShaderResourceViewDescription()
            {
                Format = Format.R8G8B8A8_UNorm,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource()
                {
                    MipLevels = 1,
                    MostDetailedMip = 0
                }
            };
            lightBufferRes = new ShaderResourceView(_device, gBufferLight, gBufferResourceDesc);
            normalBufferRes = new ShaderResourceView(_device, gBufferNormal, gBufferResourceDesc);
            diffuseBufferRes = new ShaderResourceView(_device, gBufferDiffuse, gBufferResourceDesc);

            Texture2DDescription depthDesc = new Texture2DDescription()
            {
                ArraySize = 1,
                BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.R32_Typeless,
                Width = _width,
                Height = _height,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default
            };

            DepthStencilViewDescription depthViewDesc = new DepthStencilViewDescription()
            {
                Dimension = DepthStencilViewDimension.Texture2D,
                Format = Format.D32_Float,
            };

            ShaderResourceViewDescription resourceDesc = new ShaderResourceViewDescription()
            {
                Format = Format.R32_Float,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource()
                {
                    MipLevels = 1,
                    MostDetailedMip = 0
                }
            };

            depthTexture = new Texture2D(_device, depthDesc);
            depthView = new DepthStencilView(_device, depthTexture, depthViewDesc);
            depthRes = new ShaderResourceView(_device, depthTexture, resourceDesc);

            lightDepthTexture = new Texture2D(_device, depthDesc);
            lightDepthView = new DepthStencilView(_device, lightDepthTexture, depthViewDesc);
            lightDepthRes = new ShaderResourceView(_device, lightDepthTexture, resourceDesc);

            lightBufferVar = effect2.GetVariableByName("lightBuffer").AsShaderResource();
            normalBufferVar = effect2.GetVariableByName("normalBuffer").AsShaderResource();
            diffuseBufferVar = effect2.GetVariableByName("diffuseBuffer").AsShaderResource();
            depthMapVar = effect2.GetVariableByName("depthMap").AsShaderResource();
            lightDepthMapVar = effect2.GetVariableByName("lightDepthMap").AsShaderResource();

            _device.Rasterizer.SetViewports(new Viewport(0, 0, _width, _height));
        }
Beispiel #12
0
		public void Export(int sizeX, int sizeY, ID3D10Scene scene, Altaxo.Graph.Gdi.GraphExportOptions options, System.IO.Stream toStream)
		{
			var device = new Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug, FeatureLevel.Level_10_0);

			// try to get the highest MSAA level with the highest quality
			int sampleCount = 32;
			int qlevel_sampleCount = 0;

			for (; sampleCount >= 0; sampleCount /= 2)
			{
				if (0 != (qlevel_sampleCount = device.CheckMultisampleQualityLevels(Format.B8G8R8A8_UNorm, sampleCount))) // quality level for sample count
					break;
			}

			Texture2DDescription colordesc = new Texture2DDescription
			{
				BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
				Format = Format.B8G8R8A8_UNorm_SRgb,
				Width = sizeX,
				Height = sizeY,
				MipLevels = 1,
				SampleDescription = new SampleDescription(sampleCount, qlevel_sampleCount - 1),
				Usage = ResourceUsage.Default,
				OptionFlags = ResourceOptionFlags.Shared,
				CpuAccessFlags = CpuAccessFlags.None,
				ArraySize = 1
			};

			Texture2DDescription depthdesc = new Texture2DDescription
			{
				BindFlags = BindFlags.DepthStencil,
				Format = Format.D32_Float_S8X24_UInt,
				Width = sizeX,
				Height = sizeY,
				MipLevels = 1,
				SampleDescription = new SampleDescription(sampleCount, qlevel_sampleCount - 1),
				Usage = ResourceUsage.Default,
				OptionFlags = ResourceOptionFlags.None,
				CpuAccessFlags = CpuAccessFlags.None,
				ArraySize = 1,
			};

			var renderTarget = new Texture2D(device, colordesc);
			var depthStencil = new Texture2D(device, depthdesc);
			var renderTargetView = new RenderTargetView(device, renderTarget);
			var depthStencilView = new DepthStencilView(device, depthStencil);

			// Rendering

			device.OutputMerger.SetTargets(depthStencilView, renderTargetView);
			device.Rasterizer.SetViewports(new Viewport(0, 0, sizeX, sizeY, 0.0f, 1.0f));
			Color4 clearColor = new Color4(1, 1, 1, 0); // Transparent
			if (options.BackgroundBrush != null)
			{
				var axoColor = options.BackgroundBrush.Color.Color;
				clearColor = new Color4(axoColor.ScR, axoColor.ScG, axoColor.ScB, axoColor.ScA);
			}
			device.ClearRenderTargetView(renderTargetView, clearColor);
			device.ClearDepthStencilView(depthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);

			scene.Attach(device, new PointD2D(sizeX, sizeY));
			scene.Render();

			device.Flush();

			Texture2D renderTarget2 = null;

			if (sampleCount > 1) // if renderTarget is an MSAA render target, we first have to copy it into a non-MSAA render target before we can copy it to a CPU texture and then hope to save it
			{
				// create a non-MSAA render target with the same size
				Texture2DDescription renderTarget2Description = new Texture2DDescription
				{
					BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
					Format = Format.B8G8R8A8_UNorm_SRgb,
					Width = sizeX,
					Height = sizeY,
					MipLevels = 1,
					SampleDescription = new SampleDescription(1, 0), // non MSAA
					Usage = ResourceUsage.Default,
					OptionFlags = ResourceOptionFlags.Shared,
					CpuAccessFlags = CpuAccessFlags.None,
					ArraySize = 1
				};

				renderTarget2 = new Texture2D(device, renderTarget2Description); // create non-MSAA render target
				device.ResolveSubresource(renderTarget, 0, renderTarget2, 0, renderTarget.Description.Format); // copy from MSAA render target to the non-MSAA render target

				var h = renderTarget; // exchange renderTarget with renderTarget2
				renderTarget = renderTarget2;
				renderTarget2 = h;
			}

			// renderTarget is now a non-MSAA renderTarget
			Texture2DExtensions.SaveToStream(renderTarget, options.ImageFormat, options.DestinationDpiResolution, toStream);

			scene.Detach();

			Disposer.RemoveAndDispose(ref depthStencilView);
			Disposer.RemoveAndDispose(ref renderTargetView);
			Disposer.RemoveAndDispose(ref renderTarget2);
			Disposer.RemoveAndDispose(ref renderTarget);
			Disposer.RemoveAndDispose(ref depthStencil);
			Disposer.RemoveAndDispose(ref device);
		}
 /// <summary>	
 /// Get an array of render-targets.	
 /// </summary>	
 /// <param name="offset">The zero-based array index to get the first interface. </param>
 /// <param name="count">The number of elements in the array. </param>
 /// <returns>Returns an array of <see cref="SharpDX.Direct3D10.RenderTargetView"/>. </returns>
 /// <unmanaged>HRESULT ID3D10EffectRenderTargetViewVariable::GetRenderTargetArray([Out, Buffer] ID3D10RenderTargetView** ppResources,[None] int Offset,[None] int Count)</unmanaged>
 public SharpDX.Direct3D10.RenderTargetView[] GetRenderTargetArray(int offset, int count)
 {
     var temp = new RenderTargetView[count];
     GetRenderTargetArray(temp, offset, count);
     return temp;
 }  
 /// <summary>	
 /// Get references to the render targets and the depth-stencil buffer that are available to the {{output-merger stage}}.	
 /// </summary>	
 /// <remarks>	
 /// Any returned interfaces will have their reference count incremented by one. Applications should call {{IUnknown::Release}} on the returned interfaces when they are no longer needed to avoid memory leaks. 	
 /// </remarks>	
 /// <param name="numViews">Number of render targets to retrieve. </param>
 /// <param name="depthStencilViewRef">Pointer to a depth-stencil view (see <see cref="SharpDX.Direct3D10.DepthStencilView"/>) to be filled with the depth-stencil information from the device.</param>
 /// <returns>an array of render targets views (see <see cref="SharpDX.Direct3D10.RenderTargetView"/>) to be filled with the render targets from the device.</returns>
 /// <unmanaged>void OMGetRenderTargets([In] int NumViews,[Out, Buffer, Optional] ID3D10RenderTargetView** ppRenderTargetViews,[Out, Optional] ID3D10DepthStencilView** ppDepthStencilView)</unmanaged>
 public SharpDX.Direct3D10.RenderTargetView[] GetRenderTargets(int numViews, out SharpDX.Direct3D10.DepthStencilView depthStencilViewRef)
 {
     var renderTargets = new RenderTargetView[numViews];
     GetRenderTargets(numViews, renderTargets, out depthStencilViewRef);
     return renderTargets;
 }
Beispiel #15
0
 /// <summary>
 ///   Binds a single render target to the output-merger stage.
 /// </summary>
 /// <param name = "renderTargetView">A view of the render target to bind.</param>
 public void SetTargets(RenderTargetView renderTargetView)
 {
     SetTargets((DepthStencilView)null, renderTargetView);
 }
        private void initD3D()
        {
            if (drawForm == null)
                return;

            swapChainDesc = new SwapChainDescription
            {
                BufferCount = 2,
                ModeDescription = new ModeDescription
                {
                    Width = drawForm.Width,
                    Height = drawForm.Height,
                    Format = Format.R8G8B8A8_UNorm,
                },
                Usage = Usage.RenderTargetOutput,
            };

            swapChainDesc.ModeDescription.RefreshRate.Numerator = 60;
            swapChainDesc.ModeDescription.RefreshRate.Denominator = 1;

            swapChainDesc.SampleDescription.Quality = 0;
            swapChainDesc.SampleDescription.Count = 1;

            swapChainDesc.OutputHandle = drawHandle;
            swapChainDesc.IsWindowed = true;

            D3D10.Device.CreateWithSwapChain(
                D3D10.DriverType.Hardware,
                DeviceCreationFlags.None,
                swapChainDesc,
                out d3d10Device,
                out swapChain
            );

            using (Texture2D backBuffer = swapChain.GetBackBuffer<Texture2D>(0))
                renderTargetView = new RenderTargetView(d3d10Device, backBuffer);

            d3d10Device.OutputMerger.SetTargets(renderTargetView);

            viewport = new Viewport
            {
                Width = drawForm.Width,
                Height = drawForm.Height,
                MinDepth = 0.0f,
                MaxDepth = 1.0f,
                X = 0,
                Y = 0
            };

            d3d10Device.Rasterizer.SetViewports(viewport);

            var zBufferTextureDescription = new Texture2DDescription
            {
                Format = Format.D16_UNorm,
                ArraySize = 1,
                MipLevels = 1,
                Width = drawForm.Width,
                Height = drawForm.Height,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None
            };
            using (var zBufferTexture = new Texture2D(this.d3d10Device, zBufferTextureDescription))
                depthStencilView = new DepthStencilView(this.d3d10Device, zBufferTexture);
            d3d10Device.OutputMerger.SetTargets(depthStencilView, renderTargetView);

            depthState = 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
                }
            };
            depthNonState = new DepthStencilStateDescription()
            {
                IsDepthEnabled = false
            };
            d3d10Device.OutputMerger.SetDepthStencilState(
                new DepthStencilState(
                    d3d10Device,
                    depthState
                ), 1
            );

            // Generic font?

            // Camera?

            d3d10Device.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

            d3d10Device.Rasterizer.State = new RasterizerState(d3d10Device,
                new RasterizerStateDescription
                {
                    CullMode = CullMode.Back,
                    FillMode = FillMode.Solid
                }
            );
        }
		private void CreateAndBindTargets(int sizeX, int sizeY)
		{
			_d3dImageSource.SetRenderTargetDX10(null);

			Disposer.RemoveAndDispose(ref this._renderTargetView);
			Disposer.RemoveAndDispose(ref this._renderTargetIntermediateView);
			Disposer.RemoveAndDispose(ref this._renderTargetIntermediateShaderResourceView);
			Disposer.RemoveAndDispose(ref this._depthStencilView);
			Disposer.RemoveAndDispose(ref this._renderTarget);
			Disposer.RemoveAndDispose(ref this._renderTargetIntermediate);
			Disposer.RemoveAndDispose(ref this._depthStencil);
			Disposer.RemoveAndDispose(ref this._gammaCorrector);

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

				Texture2DDescription renderTextureDescriptionForD3D9 = new Texture2DDescription
				{
					BindFlags = BindFlags.None,
					Format = Format.B8G8R8A8_UNorm,
					Width = sizeX,
					Height = sizeY,
					MipLevels = 1,
					SampleDescription = new SampleDescription(1, 0),
					Usage = ResourceUsage.Staging,
					OptionFlags = ResourceOptionFlags.Shared,
					CpuAccessFlags = CpuAccessFlags.Read,
					ArraySize = 1
				};

				Texture2DDescription depthdesc = new Texture2DDescription
				{
					BindFlags = BindFlags.DepthStencil,
					Format = Format.D32_Float_S8X24_UInt,
					Width = sizeX,
					Height = sizeY,
					MipLevels = 1,
					SampleDescription = new SampleDescription(1, 0),
					Usage = ResourceUsage.Default,
					OptionFlags = ResourceOptionFlags.None,
					CpuAccessFlags = CpuAccessFlags.None,
					ArraySize = 1,
				};

				this._renderTarget = new Texture2D(this._device, colordesc);
				this._renderTargetIntermediate = new Texture2D(this._device, colordesc);
				this._depthStencil = new Texture2D(this._device, depthdesc);
				this._renderTargetIntermediateView = new RenderTargetView(this._device, this._renderTargetIntermediate);
				this._renderTargetIntermediateShaderResourceView = new ShaderResourceView(this._device, this._renderTargetIntermediate);
				this._renderTargetView = new RenderTargetView(this._device, this._renderTarget);
				this._depthStencilView = new DepthStencilView(this._device, this._depthStencil);
				this._gammaCorrector = new D3D10GammaCorrector(_device, "Altaxo.CompiledShaders.Effects.GammaCorrector.cso");

				this._d3dImageSource.SetRenderTargetDX10(this._renderTarget);
			}
		}
        private void CreateAndBindTargets()
        {
            _d3DSurface.SetRenderTargetDX10(null);

            Disposer.RemoveAndDispose(ref _renderTargetView);
            Disposer.RemoveAndDispose(ref _depthStencilView);
            Disposer.RemoveAndDispose(ref _renderTarget);
            Disposer.RemoveAndDispose(ref _depthStencil);

            int width = Math.Max((int)base.ActualWidth, 100);
            int height = Math.Max((int)base.ActualHeight, 100);

            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
            };

            Texture2DDescription depthdesc = new Texture2DDescription
            {
                BindFlags = BindFlags.DepthStencil,
                Format = Format.D32_Float_S8X24_UInt,
                Width = width,
                Height = height,
                MipLevels = 1,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                OptionFlags = ResourceOptionFlags.None,
                CpuAccessFlags = CpuAccessFlags.None,
                ArraySize = 1,
            };

            _renderTarget = new Texture2D(_device, colordesc);
            _depthStencil = new Texture2D(_device, depthdesc);
            _renderTargetView = new RenderTargetView(_device, _renderTarget);
            _depthStencilView = new DepthStencilView(_device, _depthStencil);

            _d3DSurface.SetRenderTargetDX10(_renderTarget);
        }
        private static void Main()
        {
            var form = new RenderForm("SharpDX - MiniTri Direct3D 10 Sample");

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

            // Create Device and SwapChain
            Device device;
            SwapChain swapChain;
            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device, out swapChain);

            // Ignore all windows events
            Factory factory = swapChain.GetParent<Factory>();
            factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            // New RenderTargetView from the backbuffer
            Texture2D backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            var renderView = new RenderTargetView(device, backBuffer);

            // Compile Vertex and Pixel shaders
            var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "VS", "vs_4_0", ShaderFlags.None,
                                                                      EffectFlags.None);
            var vertexShader = new VertexShader(device, vertexShaderByteCode);

            var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "PS", "ps_4_0", ShaderFlags.None,
                                                                     EffectFlags.None);
            var pixelShader = new PixelShader(device, pixelShaderByteCode);

            // Layout from VertexShader input signature
            var layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] {
                new InputElement("POSITION",0,Format.R32G32B32A32_Float,0,0),
                new InputElement("COLOR",0,Format.R32G32B32A32_Float,16,0)
            });

            // Write vertex data to a datastream
            var stream = new DataStream(32*3, true, true);
            stream.WriteRange(new[]
                                  {
                                      new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                                      new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f)
                                  });
            stream.Position = 0;

            // Instantiate Vertex buiffer from vertex data
            var vertices = new Buffer(device, stream, new BufferDescription()
                                                          {
                                                              BindFlags = BindFlags.VertexBuffer,
                                                              CpuAccessFlags = CpuAccessFlags.None,
                                                              OptionFlags = ResourceOptionFlags.None,
                                                              SizeInBytes = 32*3,
                                                              Usage = ResourceUsage.Default,
                                                          });
            stream.Release();

            // Prepare All the stages
            device.InputAssembler.SetInputLayout(layout);
            device.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleList);
            device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 32, 0));
            device.VertexShader.Set(vertexShader);
            device.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
            device.PixelShader.Set(pixelShader);
            device.OutputMerger.SetTargets(renderView);

            // Main loop
            RenderLoop.Run(form, () =>
                                      {
                                          device.ClearRenderTargetView(renderView, new Color4(1.0f, 0.0f, 0.0f, 0.0f));
                                          device.Draw(3, 0);
                                          swapChain.Present(0, PresentFlags.None);
                                      });

            // Release all resources
            vertexShaderByteCode.Release();
            vertexShader.Release();
            pixelShaderByteCode.Release();
            pixelShader.Release();
            vertices.Release();
            layout.Release();
            renderView.Release();
            backBuffer.Release();
            device.ClearState();
            device.Flush();
            device.Release();
            device.Release();
            swapChain.Release();
            factory.Release();
        }
 /// <summary>
 ///   Binds a depth-stencil buffer and a single render target to the output-merger stage.
 /// </summary>
 /// <param name = "depthStencilView">A view of the depth-stencil buffer to bind.</param>
 /// <param name = "renderTargetView">A view of the render target to bind.</param>
 public void SetTargets(DepthStencilView depthStencilView, RenderTargetView renderTargetView)
 {
     SetTargets(depthStencilView, new[] { renderTargetView });
 }
Beispiel #21
0
 /// <summary>
 ///   Binds a depth-stencil buffer and a single render target to the output-merger stage.
 /// </summary>
 /// <param name = "depthStencilView">A view of the depth-stencil buffer to bind.</param>
 /// <param name = "renderTargetView">A view of the render target to bind.</param>
 public void SetTargets(DepthStencilView depthStencilView, RenderTargetView renderTargetView)
 {
     SetTargets(depthStencilView, new[] { renderTargetView });
 }
        private void Initialize()
        {
            // Create the form
            form = CreateForm();

            // SwapChain description
            var desc = new SwapChainDescription()
            {
                BufferCount = 1,
                ModeDescription =
                    new ModeDescription((int)Config.SCREEN_WIDTH, (int)Config.SCREEN_HEIGHT,
                                        new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed = true,
                OutputHandle = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect = SwapEffect.Discard,
                Usage = Usage.RenderTargetOutput
            };
            //Create the device and swapchain
            try
            {
                Device1.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, desc, out device, out swapChain);
            }
            catch (Exception e)
            {
                Device1.CreateWithSwapChain(DriverType.Warp, DeviceCreationFlags.BgraSupport, desc, out device, out swapChain);
                Console.WriteLine("Could not create Hardware drivertype, using Warp instead. \n" + e.ToString());
            }

            // Ignore all Windows events
            SharpDX.DXGI.Factory factory = swapChain.GetParent<SharpDX.DXGI.Factory>();
            factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            // New RenderTargetView from the backbuffer
            backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            backBufferView = new RenderTargetView(device, backBuffer);

            // Create the rendertarget for the form
            factory2D = new SharpDX.Direct2D1.Factory();
            Surface surface = backBuffer.QueryInterface<Surface>();
            renderTarget = new RenderTarget(factory2D, surface, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));
            renderTarget.AntialiasMode = AntialiasMode.Aliased;
            // Initialize the global resources used for drawing and writing.
            Resources.Initialize(renderTarget);
            runnableComponent.InitBase();
        }
Beispiel #23
0
        private static void Main()
        {
            var form = new RenderForm("SharpDX - MiniTri Direct2D - Direct3D 10 Sample");

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

            // Create Device and SwapChain
            Device1 device;
            SwapChain swapChain;
            Device1.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, desc, FeatureLevel.Level_10_0, out device, out swapChain);

            var d2dFactory = new SharpDX.Direct2D1.Factory();

            int width = form.ClientSize.Width;
            int height = form.ClientSize.Height;

            var rectangleGeometry = new RoundedRectangleGeometry(d2dFactory, new RoundedRectangle() { RadiusX = 32, RadiusY = 32, Rect = new RectangleF(128, 128, width - 128 * 2, height-128 * 2) });

            // Ignore all windows events
            Factory factory = swapChain.GetParent<Factory>();
            factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            // New RenderTargetView from the backbuffer
            Texture2D backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            var renderView = new RenderTargetView(device, backBuffer);

            Surface surface = backBuffer.QueryInterface<Surface>();


            var d2dRenderTarget = new RenderTarget(d2dFactory, surface,
                                                            new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));

            var solidColorBrush = new SolidColorBrush(d2dRenderTarget, Color.White);

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            // Main loop
            RenderLoop.Run(form, () =>
                                      {
                                          d2dRenderTarget.BeginDraw();
                                          d2dRenderTarget.Clear(Color.Black);
                                          solidColorBrush.Color = new Color4(1, 1, 1, (float)Math.Abs(Math.Cos(stopwatch.ElapsedMilliseconds * .001)));
                                          d2dRenderTarget.FillGeometry(rectangleGeometry, solidColorBrush, null);
                                          d2dRenderTarget.EndDraw();

                                          swapChain.Present(0, PresentFlags.None);
                                      });

            // Release all resources
            renderView.Dispose();
            backBuffer.Dispose();
            device.ClearState();
            device.Flush();
            device.Dispose();
            device.Dispose();
            swapChain.Dispose();
            factory.Dispose();
        }
Beispiel #24
0
        private void HandleClientSizeChanged(object sender, EventArgs e)
        {
            // reconfigure the direct3d rendering surface
            _Device.OutputMerger.SetTargets((RenderTargetView)null);

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

            _SwapChain.ResizeBuffers(
                1,
                Math.Max(1, _Form.ClientSize.Width),
                Math.Max(1, _Form.ClientSize.Height),
                Format.R8G8B8A8_UNorm,
                0);

            using(var backBuffer = Resource.FromSwapChain<Texture2D>(_SwapChain, 0))
            {
                _RenderView = new RenderTargetView(_Device, backBuffer);
            }

            _Device.OutputMerger.SetTargets(_RenderView);

            Viewport view = new Viewport
            {
                X = 0,
                Y = 0,
                Width = _Form.ClientSize.Width,
                Height = _Form.ClientSize.Height,
                MinDepth = 0.0f,
                MaxDepth = 1.0f
            };

            _Device.Rasterizer.SetViewports(view);

            // reconfigure the Frost rendering surface
            Size formSize = new Size(_Form.ClientSize.Width, _Form.ClientSize.Height);

            if(_Target != null)
            {
                _Target.Forget();
            }

            _Target = new Canvas(formSize, SurfaceUsage.External);

            formSize = new Size(Math.Max(formSize.Width, 640), Math.Max(formSize.Height, 480));

            _Device2D.Resources.PageSize = new Size(formSize.Width * 2, formSize.Height * 2);

            _IsResetQueued = true;
        }
Beispiel #25
0
        private void _initializeGraphics()
        {
            Console.Write("Initializing graphic device... ");

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

            Device1.CreateWithSwapChain(
                DriverType.Hardware,
            #if DEBUG
             DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug | DeviceCreationFlags.SingleThreaded,
            #else
                DeviceCreationFlags.BgraSupport,
            #endif
             desc,
                out _device,
                out _swapChain);

            if (_device == null)
                throw new SharpDXException("Failed to initialize graphics device.");

            if (_swapChain == null)
                throw new SharpDXException("Failed to initialize swap chain.");

            ToDispose<Device1>(_device);
            ToDispose<SwapChain>(_swapChain);
            Factory2D = ToDispose<Factory2D>(new Factory2D());

            _factoryDXGI = ToDispose<FactoryDXGI>(_swapChain.GetParent<FactoryDXGI>());
            _factoryDXGI.MakeWindowAssociation(DisplayHandle, WindowAssociationFlags.IgnoreAll);

            _backBuffer = ToDispose<Texture2D>(Texture2D.FromSwapChain<Texture2D>(_swapChain, 0));
            _backBufferRenderTargetView = ToDispose<RenderTargetView>(new RenderTargetView(_device, _backBuffer));

            Viewport = new Viewport(0, 0, _appConfiguration.Width, _appConfiguration.Height);
            using (var surface = _backBuffer.QueryInterface<Surface>()) {
                RenderTarget2D = ToDispose<RenderTarget>(
                    new RenderTarget(Factory2D,
                        surface,
                        new RenderTargetProperties(
                            new PixelFormat(
                                Format.Unknown,
                                AlphaMode.Premultiplied))));
            }
            RenderTarget2D.AntialiasMode = AntialiasMode.PerPrimitive;

            _vsync = Config.VSync;

            ScreenSize = new DrawingSizeF(Viewport.Width, Viewport.Height);

            Console.WriteLine("done.");
        }
Beispiel #26
0
        private static void Main()
        {
            var form = new RenderForm("SharpDX - MiniTri Direct3D 10 Sample");

            Configuration.EnableObjectTracking = true;

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

            // Create Device and SwapChain
            Device device;
            SwapChain swapChain;
            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain);

            // Ignore all windows events
            var factory = swapChain.GetParent<Factory>();
            factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            // New RenderTargetView from the backbuffer
            var backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            var renderView = new RenderTargetView(device, backBuffer);

            // Compile Vertex and Pixel shaders
            var effectByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None);
            var effect = new Effect(device, effectByteCode);
            var technique = effect.GetTechniqueByIndex(0);
            var pass = technique.GetPassByIndex(0);

            // Layout from VertexShader input signature
            var passSignature = pass.Description.Signature;
            var layout = new InputLayout(device, passSignature, new[]
                                                                                 {
                                                                                     new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                                                                                     new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
                                                                                 });

            // Instantiate Vertex buiffer from vertex data
            var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[]
                                  {
                                      new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                                      new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f)
                                  });

            // Prepare All the stages
            device.InputAssembler.InputLayout = layout;
            device.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 32, 0));
            device.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
            device.OutputMerger.SetTargets(renderView);

            // Main loop
            RenderLoop.Run(form, () =>
                                      {
                                          device.ClearRenderTargetView(renderView, Color.Black);
                                          for (int i = 0; i < technique.Description.PassCount; ++i)
                                          {
                                              pass.Apply();
                                              device.Draw(3, 0);
                                          }
                                          swapChain.Present(0, PresentFlags.None);
                                      });

            // Release all resources
            passSignature.Dispose();
            effect.Dispose();
            effectByteCode.Dispose();
            vertices.Dispose();
            layout.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            device.ClearState();
            device.Flush();
            device.Dispose();
            swapChain.Dispose();
            factory.Dispose();           
        }