private void PlatformConstruct(GraphicsDevice graphicsDevice, int width, int height, bool mipMap,
            SurfaceFormat preferredFormat, DepthFormat preferredDepthFormat, int preferredMultiSampleCount, RenderTargetUsage usage)
        {
            // Setup the multisampling description.
            var multisampleDesc = new SharpDX.DXGI.SampleDescription(1, 0);
            if (preferredMultiSampleCount > 1)
            {
                multisampleDesc.Count = preferredMultiSampleCount;
                multisampleDesc.Quality = (int)StandardMultisampleQualityLevels.StandardMultisamplePattern;
            }

            // Create a descriptor for the depth/stencil buffer.
            // Allocate a 2-D surface as the depth/stencil buffer.
            // Create a DepthStencil view on this surface to use on bind.
            using (var depthBuffer = new SharpDX.Direct3D11.Texture2D(graphicsDevice._d3dDevice, new Texture2DDescription
            {
                Format = SharpDXHelper.ToFormat(preferredDepthFormat),
                ArraySize = 1,
                MipLevels = 1,
                Width = width,
                Height = height,
                SampleDescription = multisampleDesc,
                BindFlags = BindFlags.DepthStencil,
            }))
            {
                // Create the view for binding to the device.
                _depthStencilView = new DepthStencilView(graphicsDevice._d3dDevice, depthBuffer, new DepthStencilViewDescription()
                {
                    Format = SharpDXHelper.ToFormat(preferredDepthFormat),
                    Dimension = DepthStencilViewDimension.Texture2D
                });
            }
        }
Exemple #2
0
        internal MyTextureArray(TexId[] mergeList)
        {
            var srcDesc = MyTextures.GetView(mergeList[0]).Description;
            Size = MyTextures.GetSize(mergeList[0]);
            ArrayLen = mergeList.Length;

            Texture2DDescription desc = new Texture2DDescription();
            desc.ArraySize = ArrayLen;
            desc.BindFlags = BindFlags.ShaderResource;
            desc.CpuAccessFlags = CpuAccessFlags.None;
            desc.Format = srcDesc.Format;
            desc.Height = (int)Size.Y;
            desc.Width = (int)Size.X;
            desc.MipLevels = 0;
            desc.SampleDescription.Count = 1;
            desc.SampleDescription.Quality = 0;
            desc.Usage = ResourceUsage.Default;
            m_resource = new Texture2D(MyRender11.Device, desc);

            // foreach mip
            var mipmaps = (int)Math.Log(Size.X, 2) + 1;

            for (int a = 0; a < ArrayLen; a++)
            {
                for (int m = 0; m < mipmaps; m++)
                {
                    MyRender11.Context.CopySubresourceRegion(MyTextures.Textures.Data[mergeList[a].Index].Resource, Resource.CalculateSubResourceIndex(m, 0, mipmaps), null, Resource,
                        Resource.CalculateSubResourceIndex(m, a, mipmaps));
                }
            }

            ShaderView = new ShaderResourceView(MyRender11.Device, Resource);
        }
Exemple #3
0
        /// <summary>
        /// 参考自:https://github.com/sharpdx/SharpDX-Samples/blob/master/StoreApp/OldSamplesToBeBackPorted/CommonDX/TextureLoader.cs 和noire项目
        /// </summary>
        /// <param name="device">设备对象</param>
        /// <param name="bitmapSource"></param>
        /// <returns></returns>
        public static SharpDX.Direct3D11.ShaderResourceView CreateShaderResourceViewFromFile(SharpDX.Direct3D11.Device device, string fileName)
        {
            Texture2D tempTex;

            using (var bitmapSource = LoadBitmapSourceFromFile(_factory, fileName)) {
                // Allocate DataStream to receive the WIC image pixels
                int stride = bitmapSource.Size.Width * 4;
                using (var buffer = new SharpDX.DataStream(bitmapSource.Size.Height * stride, true, true)) {
                    // Copy the content of the WIC to the buffer
                    bitmapSource.CopyPixels(stride, buffer);
                    tempTex = new SharpDX.Direct3D11.Texture2D(
                        device,
                        new SharpDX.Direct3D11.Texture2DDescription()
                    {
                        Width             = bitmapSource.Size.Width,
                        Height            = bitmapSource.Size.Height,
                        ArraySize         = 1,
                        BindFlags         = SharpDX.Direct3D11.BindFlags.ShaderResource,
                        Usage             = SharpDX.Direct3D11.ResourceUsage.Immutable,
                        CpuAccessFlags    = SharpDX.Direct3D11.CpuAccessFlags.None,
                        Format            = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
                        MipLevels         = 1,
                        OptionFlags       = SharpDX.Direct3D11.ResourceOptionFlags.None,
                        SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                    },
                        new SharpDX.DataRectangle(buffer.DataPointer, stride));
                    bitmapSource.Dispose();
                }
            }
            return(new ShaderResourceView(device, tempTex));
        }
Exemple #4
0
        private void SwapChainPanel_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            // Check if resources have been initialized.
            if (isDXInitialized)
            {
                Size2 newSize = RenderSizeToPixelSize(e.NewSize);

                // If the requested swap chain is bigger than the current one,
                if (newSize.Width > swapChain.Description1.Width || newSize.Height > swapChain.Description1.Height)
                {
                    // Destroy resources.
                    Utilities.Dispose(ref this.backBufferView);
                    Utilities.Dispose(ref this.backBufferTexture);

                    // Resize swap chain while conserving format and flags.
                    swapChain.ResizeBuffers(swapChain.Description.BufferCount, (int)e.NewSize.Width, (int)e.NewSize.Height, swapChain.Description1.Format, swapChain.Description1.Flags);

                    // Recreate resources.
                    this.backBufferTexture = D3D11.Texture2D.FromSwapChain <D3D11.Texture2D>(this.swapChain, 0);
                    this.backBufferView    = new D3D11.RenderTargetView(this.device, this.backBufferTexture);
                }

                // Set source size propery
                swapChain.SourceSize = newSize;
            }
        }
Exemple #5
0
        void InitializeSharedBackBuffer(IntPtr resourcePtr)
        {
            // convert native pointer to DXGI shared resource
            Resource resource = CppObject.FromPointer <Resource>(resourcePtr).QueryInterface <Resource>();

            // convert shared resource to D3D11 Texture
            D3D11.Texture2D sharedBackbuffer = device.OpenSharedResource <D3D11.Texture2D>(resource.SharedHandle);

            // release reference
            resource.Dispose();

            // use D3D11 Texture as render target
            D3D11.RenderTargetViewDescription desc = new D3D11.RenderTargetViewDescription();
            desc.Format             = Format.B8G8R8A8_UNorm;
            desc.Dimension          = D3D11.RenderTargetViewDimension.Texture2D;
            desc.Texture2D.MipSlice = 0;

            renderTargetView = new D3D11.RenderTargetView(device, sharedBackbuffer, desc);
            deviceContext.OutputMerger.SetRenderTargets(renderTargetView);

            // release reference
            sharedBackbuffer.Dispose();

            // setup viewport
            Size size = Utils.WpfSizeToPixels(ImageGrid);

            deviceContext.Rasterizer.SetViewport(new Viewport(0, 0, (int)size.Width, (int)size.Height, 0.0f, 1.0f));
        }
        private void PlatformConstruct(GraphicsDevice graphicsDevice, int width, int height, bool mipMap,
                                       DepthFormat preferredDepthFormat, int preferredMultiSampleCount, RenderTargetUsage usage)
        {
            // Setup the multisampling description.
            var multisampleDesc = new SharpDX.DXGI.SampleDescription(1, 0);

            if (preferredMultiSampleCount > 1)
            {
                multisampleDesc.Count   = preferredMultiSampleCount;
                multisampleDesc.Quality = (int)StandardMultisampleQualityLevels.StandardMultisamplePattern;
            }

            // Create a descriptor for the depth/stencil buffer.
            // Allocate a 2-D surface as the depth/stencil buffer.
            // Create a DepthStencil view on this surface to use on bind.
            using (var depthBuffer = new SharpDX.Direct3D11.Texture2D(graphicsDevice._d3dDevice, new Texture2DDescription
            {
                Format = SharpDXHelper.ToFormat(preferredDepthFormat),
                ArraySize = 1,
                MipLevels = 1,
                Width = width,
                Height = height,
                SampleDescription = multisampleDesc,
                BindFlags = BindFlags.DepthStencil,
            }))
            {
                // Create the view for binding to the device.
                _depthStencilView = new DepthStencilView(graphicsDevice._d3dDevice, depthBuffer, new DepthStencilViewDescription()
                {
                    Format    = SharpDXHelper.ToFormat(preferredDepthFormat),
                    Dimension = DepthStencilViewDimension.Texture2D
                });
            }
        }
        protected override void InitializeInternal()
        {
            var sourceTextures = _textures.Select(t =>
            {
                var view = t.ShaderResourceView;
                if(view == null)
                    throw new InvalidOperationException(string.Format("Texture array cannot be created because source texture '{0}' is not initialized", t.Id));
                return view.Resource.QueryInterface<Texture2D>();
            }).ToArray();

            var descr = sourceTextures[0].Description;
            descr.ArraySize = _textures.Length;
            _textureArray = new Texture2D(DeviceManager.Device, descr);
            ShaderResourceView = new ShaderResourceView(DeviceManager.Device, _textureArray);

            var mipLevels = descr.MipLevels;
            for(var i = 0; i < mipLevels; i++)
            {
                for(var j = 0; j < _textures.Length; j++)
                {
                    var texture = sourceTextures[j];
                    DeviceManager.Context.CopySubresourceRegion(texture, i, null, _textureArray, mipLevels * j + i);
                }
            }
        }
Exemple #8
0
        private void InitializeBackBuffer(D2D.DeviceContext deviceContext, SharpDX.Size2F size)
        {
            this.backBitmap?.Dispose();

            Size2 pixelSize = Helpers.GetPixelSize(size, this.Factory.DesktopDpi);

            var p = new D2D.BitmapProperties1(
                new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied),
                this.Factory.DesktopDpi.Width,
                this.Factory.DesktopDpi.Height,
                D2D.BitmapOptions.Target);

            var desc = new D3D11.Texture2DDescription()
            {
                ArraySize         = 1,
                BindFlags         = D3D11.BindFlags.RenderTarget | D3D11.BindFlags.ShaderResource,
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                Format            = DXGI.Format.B8G8R8A8_UNorm,
                MipLevels         = 1,
                OptionFlags       = D3D11.ResourceOptionFlags.Shared,
                Usage             = D3D11.ResourceUsage.Default,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                Width             = pixelSize.Width,
                Height            = pixelSize.Height,
            };

            using (var buffer = new D3D11.Texture2D(this.Device, desc))
                using (var surface = buffer.QueryInterface <DXGI.Surface>())
                {
                    this.backBitmap = new D2D.Bitmap1(this.DeviceContext, surface, p);
                }

            this.DeviceContext.Target = this.backBitmap;
        }
Exemple #9
0
        public Texture2D(int width, int height, Format format, bool mipMaps = true) : base(Dimension.Texture2D, width, height, format)
        {
            MipMapCount = mipMaps ? GetNumMipLevels(width, height) : 1;
            var bindFlags = BindFlags.ShaderResource;

            if (MipMapCount > 1)
            {
                bindFlags |= BindFlags.RenderTarget;
            }
            var resourceOptionFlags = ResourceOptionFlags.None;

            if (mipMaps)
            {
                resourceOptionFlags |= ResourceOptionFlags.GenerateMipMaps;
            }
            dxTexture = new SharpDX.Direct3D11.Texture2D(Renderer.Dev, new Texture2DDescription {
                Width             = width,
                Height            = height,
                Format            = format,
                ArraySize         = 1,
                BindFlags         = bindFlags,
                CpuAccessFlags    = CpuAccessFlags.None,
                MipLevels         = MipMapCount,
                OptionFlags       = resourceOptionFlags,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
            });
            SRV = new ShaderResourceView(Renderer.Dev, dxTexture);

            pixels = new byte[width * height * format.SizeOfInBytes()];
        }
        public static SharpDX.Direct3D11.Texture2D CreateTex2DFromBitmap(SharpDX.Direct3D11.DeviceContext device, BitmapSource bsource)
        {
            SharpDX.Direct3D11.Texture2DDescription desc;
            desc.Width                     = bsource.Size.Width;
            desc.Height                    = bsource.Size.Height;
            desc.ArraySize                 = 1;
            desc.BindFlags                 = SharpDX.Direct3D11.BindFlags.ShaderResource;
            desc.Usage                     = SharpDX.Direct3D11.ResourceUsage.Default;
            desc.CpuAccessFlags            = SharpDX.Direct3D11.CpuAccessFlags.None;
            desc.Format                    = Format.R8G8B8A8_UNorm;
            desc.MipLevels                 = 1;
            desc.OptionFlags               = SharpDX.Direct3D11.ResourceOptionFlags.None;
            desc.SampleDescription.Count   = 1;
            desc.SampleDescription.Quality = 0;

            var s = new DataStream(bsource.Size.Height * bsource.Size.Width * 4, true, true);

            bsource.CopyPixels(bsource.Size.Width * 4, s);

            var rect = new DataRectangle(s.DataPointer, bsource.Size.Width * 4);

            var t2D = new SharpDX.Direct3D11.Texture2D(device.Device, desc, rect);

            return(t2D);
        }
Exemple #11
0
        private void BuildTexture(int width, int height)
        {
            // TODO: This should probably be a dynamic texture, with updates performed via mapping. Work it out.
            texture = new D3D11.Texture2D(DxHandler.Device, new D3D11.Texture2DDescription()
            {
                Width             = width,
                Height            = height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = DXGI.Format.B8G8R8A8_UNorm,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                Usage             = D3D11.ResourceUsage.Default,
                //Usage = D3D11.ResourceUsage.Dynamic,
                BindFlags      = D3D11.BindFlags.ShaderResource,
                CpuAccessFlags = D3D11.CpuAccessFlags.None,
                //CpuAccessFlags = D3D11.CpuAccessFlags.Write,
                OptionFlags = D3D11.ResourceOptionFlags.None,
            });

            var view = new D3D11.ShaderResourceView(DxHandler.Device, texture, new D3D11.ShaderResourceViewDescription()
            {
                Format    = texture.Description.Format,
                Dimension = D3D.ShaderResourceViewDimension.Texture2D,
                Texture2D = { MipLevels = texture.Description.MipLevels },
            });

            textureWrap = new D3DTextureWrap(view, texture.Description.Width, texture.Description.Height);
        }
Exemple #12
0
        public static D3D.Texture2D CreateSurface(this D3D.Device device, int width, int height, DXGI.SampleDescription sampleDescription, out D3D.RenderTargetView renderTarget)
        {
            var desc = new D3D.Texture2DDescription
            {
                Width             = width,
                Height            = height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = DXGI.Format.R8G8B8A8_UNorm,
                SampleDescription = sampleDescription,
                Usage             = D3D.ResourceUsage.Default,
                BindFlags         = D3D.BindFlags.RenderTarget | D3D.BindFlags.ShaderResource,
                CpuAccessFlags    = D3D.CpuAccessFlags.None,
                OptionFlags       = D3D.ResourceOptionFlags.Shared,
            };
            var surface = new D3D.Texture2D(device, desc);

            var targetDesc = new D3D.RenderTargetViewDescription
            {
                Format    = desc.Format,
                Dimension = desc.SampleDescription.Count == 1
                        ? D3D.RenderTargetViewDimension.Texture2D
                        : D3D.RenderTargetViewDimension.Texture2DMultisampled,
            };

            renderTarget = new D3D.RenderTargetView(device, surface, targetDesc);

            return(surface);
        }
        public override void OnPopupSize(Rect rect)
        {
            popupRect = rect;

            // I'm really not sure if this happens. If it does, frequently - will probably need 2x shared textures and some jazz.
            var texDesc = texture.Description;

            if (rect.Width > texDesc.Width || rect.Height > texDesc.Height)
            {
                Console.Error.WriteLine($"Trying to build popup layer ({rect.Width}x{rect.Height}) larger than primary surface ({texDesc.Width}x{texDesc.Height}).");
            }

            // Get a reference to the old texture, we'll make sure to assign a new texture before disposing the old one.
            var oldTexture = popupTexture;

            // Build a texture for the new sized popup
            popupTexture = new D3D11.Texture2D(texture.Device, new D3D11.Texture2DDescription()
            {
                Width             = rect.Width,
                Height            = rect.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = DXGI.Format.B8G8R8A8_UNorm,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                Usage             = D3D11.ResourceUsage.Default,
                BindFlags         = D3D11.BindFlags.ShaderResource,
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                OptionFlags       = D3D11.ResourceOptionFlags.None,
            });

            if (oldTexture != null)
            {
                oldTexture.Dispose();
            }
        }
Exemple #14
0
        private D3D11.ShaderResourceView LoadTexture(string name)
        {
            var converter = new SharpDX.WIC.FormatConverter(imagingFactory);
            var decoder   = new SharpDX.WIC.BitmapDecoder(imagingFactory, name, SharpDX.WIC.DecodeOptions.CacheOnDemand);

            converter.Initialize(decoder.GetFrame(0), SharpDX.WIC.PixelFormat.Format32bppBGRA, SharpDX.WIC.BitmapDitherType.None, null, 0.0, SharpDX.WIC.BitmapPaletteType.Custom);

            var stride     = converter.Size.Width * 4;
            var size       = converter.Size.Height * stride;
            var dataStream = new SharpDX.DataStream(size, true, true);

            converter.CopyPixels(stride, dataStream);
            D3D11.Texture2D tex = new D3D11.Texture2D(d3dDevice,
                                                      new D3D11.Texture2DDescription()
            {
                Width             = converter.Size.Width,
                Height            = converter.Size.Height,
                ArraySize         = 1,
                BindFlags         = D3D11.BindFlags.ShaderResource,
                Usage             = D3D11.ResourceUsage.Immutable,
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                MipLevels         = 1,
                OptionFlags       = D3D11.ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
            },
                                                      new SharpDX.DataRectangle(dataStream.DataPointer, stride)
                                                      );

            return(new D3D11.ShaderResourceView(d3dDevice, tex));
        }
 /// <summary>
 /// Disposes all loaded view resources.
 /// </summary>
 private void OnRenderLoopDisposeViewResources(EngineDevice engineDevice)
 {
     m_renderTargetDepth = GraphicsHelper.DisposeObject(m_renderTargetDepth);
     m_depthBuffer       = GraphicsHelper.DisposeObject(m_depthBuffer);
     m_renderTargetView  = GraphicsHelper.DisposeObject(m_renderTargetView);
     m_backBuffer        = GraphicsHelper.DisposeObject(m_backBuffer);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="Direct2DOverlayRenderer"/> class.
        /// </summary>
        internal Direct2DOverlayRenderer(EngineDevice device, D3D11.Texture2D renderTarget3D, int viewWidth, int viewHeight, DpiScaling dpiScaling, bool forceInit)
        {
            m_device         = device;
            m_renderTarget3D = renderTarget3D;

            CreateResources(viewWidth, viewHeight, dpiScaling, forceInit);
        }
Exemple #17
0
        /// <summary>
        /// Copies the content of the specified texture.
        /// </summary>
        /// <param name="device">The Direct3D 11 device.</param>
        /// <param name="source">The source texture.</param>
        /// <param name="target">The target texture.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="device"/>, <paramref name="source"/> or <paramref name="target"/> is
        /// <see langword="null"/>.
        /// </exception>
        public static void Copy(Device device, Texture2D source, Texture2D target)
        {
            if (device == null)
            {
                throw new ArgumentNullException("device");
            }
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            int sourceWidth  = source.Description.Width;
            int sourceHeight = source.Description.Height;
            int targetWidth  = target.Description.Width;
            int targetHeight = target.Description.Height;

            if (sourceWidth == targetWidth && sourceHeight == targetHeight)
            {
                device.ImmediateContext.CopyResource(source, target);
            }
            else
            {
                int width  = Math.Min(sourceWidth, targetWidth);
                int height = Math.Min(sourceHeight, targetHeight);
                var region = new ResourceRegion(0, 0, 0, width, height, 1);
                device.ImmediateContext.CopySubresourceRegion(source, 0, region, target, 0);
            }
        }
Exemple #18
0
        /// <summary>
        /// Creates the depth stencil.
        /// </summary>
        /// <returns>D3D11.DepthStencilView.</returns>
        /// <exception cref="System.Exception"></exception>
        private D3D11.DepthStencilView CreateDepthStencil()
        {
            if (swapChain == null || d3dDevice == null)
            {
                throw new Exception(MethodBase.GetCurrentMethod().Name + "Device or SwapChain is null");
            }

            var DepthStencilTextureDesc = new D3D11.Texture2DDescription
            {
                Format            = DXGI.Format.D16_UNorm,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = width,
                Height            = height,
                SampleDescription = swapChain.Description.SampleDescription,
                Usage             = D3D11.ResourceUsage.Default,
                BindFlags         = D3D11.BindFlags.DepthStencil,
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                OptionFlags       = D3D11.ResourceOptionFlags.None
            };

            using (D3D11.Texture2D backBuffer = new D3D11.Texture2D(d3dDevice, DepthStencilTextureDesc))
            {
                return(new D3D11.DepthStencilView(d3dDevice, backBuffer));
            }
        }
Exemple #19
0
        public RenderTexture(Device device, Vector2I screenSize)
        {
            var textureDesc = new Texture2DDescription()
            {
                Width = screenSize.X,
                Height = screenSize.Y,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.R32G32B32A32_Float,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None
            };

            _renderTargetTexture = new Texture2D(device, textureDesc);

            _renderTargetView = new RenderTargetView(device, _renderTargetTexture,
                new RenderTargetViewDescription
                {
                    Format = textureDesc.Format,
                    Dimension = RenderTargetViewDimension.Texture2D,
                    Texture2D = {MipSlice = 0},
                });

            // Create the render target view.
            ShaderResourceView = new ShaderResourceView(device, _renderTargetTexture,
                new ShaderResourceViewDescription
                {
                    Format = textureDesc.Format,
                    Dimension = ShaderResourceViewDimension.Texture2D,
                    Texture2D = { MipLevels = 1, MostDetailedMip = 0 },
                });
        }
        private void InitializeDeviceResources()
        {
            ModeDescription backBufferDesc = new ModeDescription(Size.X, Size.Y, new Rational(60, 1), Format.R8G8B8A8_UNorm);

            SwapChainDescription swapChainDesc = new SwapChainDescription()
            {
                ModeDescription   = backBufferDesc,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = 2,
                IsWindowed        = true,
                OutputHandle      = Form.Handle
            };

            viewport = new Viewport(0, 0, Size.X, Size.Y);

            D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.Debug, swapChainDesc, out device, out swapChain);

            deviceContext = device.ImmediateContext;

            using (D3D11.Texture2D backBuffer = swapChain.GetBackBuffer <D3D11.Texture2D>(0))
            {
                view = new D3D11.RenderTargetView(device, backBuffer);
            }

            deviceContext.OutputMerger.SetRenderTargets(view);

            deviceContext.Rasterizer.SetViewport(viewport);

            vertexBuffer          = D3D11.Buffer.Create <Vertex>(device, D3D11.BindFlags.VertexBuffer, new Vertex[1]);
            lastVertexArrayLength = 1;
        }
 /// <summary>
 /// Инициализирует объекты связанные с графическим устройство - Девайс его контекст и Свапчейн
 /// </summary>
 private void InitializeDeviceResources()
 {
     //Создаем объектное преставление нашего GPU, его контекст и класс который будет менят местами буфферы в которые рисует наша GPU
     DX11.Device.CreateWithSwapChain(
         SharpDX.Direct3D.DriverType.Hardware,
         DX11.DeviceCreationFlags.None | DX11.DeviceCreationFlags.BgraSupport,
         new[] { SharpDX.Direct3D.FeatureLevel.Level_11_0 },
         new SwapChainDescription()
     {
         ModeDescription = new ModeDescription(
             _renderForm.ClientSize.Width,
             _renderForm.ClientSize.Height,
             new Rational(60, 1),
             Format.R8G8B8A8_UNorm),
         SampleDescription = new SampleDescription(4, 0),
         Usage             = Usage.BackBuffer | Usage.RenderTargetOutput,
         BufferCount       = 2,
         OutputHandle      = _renderForm.Handle,
         IsWindowed        = true,
         SwapEffect        = SwapEffect.Discard,
         Flags             = SwapChainFlags.None
     },
         out _dx11Device,
         out _swapChain);
     //Игноровать все события видновс
     _factory = _swapChain.GetParent <Factory>();
     _factory.MakeWindowAssociation(_renderForm.Handle, WindowAssociationFlags.IgnoreAll);
     // Создаем буффер и вьюшку глубины
     using (var _depthBuffer = new DX11.Texture2D(
                _dx11Device,
                new DX11.Texture2DDescription()
     {
         Format = Format.D32_Float_S8X24_UInt,
         ArraySize = 1,
         MipLevels = 1,
         Width = _renderForm.ClientSize.Width,
         Height = _renderForm.ClientSize.Height,
         SampleDescription = _swapChain.Description.SampleDescription,
         Usage = DX11.ResourceUsage.Default,
         BindFlags = DX11.BindFlags.DepthStencil,
         CpuAccessFlags = DX11.CpuAccessFlags.None,
         OptionFlags = DX11.ResourceOptionFlags.None
     }))
         _depthView = new DX11.DepthStencilView(_dx11Device, _depthBuffer, new SharpDX.Direct3D11.DepthStencilViewDescription()
         {
             Dimension = (SwapChain.Description.SampleDescription.Count > 1 ||
                          SwapChain.Description.SampleDescription.Quality > 0) ?
                         DX11.DepthStencilViewDimension.Texture2DMultisampled :
                         DX11.DepthStencilViewDimension.Texture2D,
             Flags = DX11.DepthStencilViewFlags.None
         });
     //Создаем буффер и вьюшку для рисования
     using (DX11.Texture2D backBuffer = _swapChain.GetBackBuffer <DX11.Texture2D>(0))
         _renderView = new DX11.RenderTargetView(_dx11Device, backBuffer);
     //Создаем контекст нашего GPU
     _dx11DeviceContext = _dx11Device.ImmediateContext;
     //Устанавливаем размер конечной картинки
     _dx11DeviceContext.Rasterizer.SetViewport(0, 0, _renderForm.ClientSize.Width, _renderForm.ClientSize.Height);
     _dx11DeviceContext.OutputMerger.SetTargets(_depthView, _renderView);
 }
Exemple #22
0
 public void Dispose()
 {
     if (Texture != null) {
         Texture.Dispose();
         Texture = null;
     }
 }
Exemple #23
0
        public static Texture2D FromColor(Device device, Color color)
        {
            var value = new Texture2D();

            Texture2DDescription textureDesc = new Texture2DDescription()
            {
                MipLevels         = 1,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = 1,
                Height            = 1,
                ArraySize         = 1,
                BindFlags         = BindFlags.ShaderResource,
                Usage             = ResourceUsage.Immutable,
                SampleDescription = new SampleDescription(1, 0)
            };

            uint          bgra   = color.ToArgb();
            GCHandle      gc     = GCHandle.Alloc(bgra, GCHandleType.Pinned);
            DataRectangle rect   = new DataRectangle(gc.AddrOfPinnedObject(), sizeof(uint));
            var           buffer = new Texture2D11(device.NativeDevice, textureDesc, rect);

            gc.Free();
            var resourceView = new ShaderResourceView(device.NativeDevice, buffer);

            buffer.Dispose();

            var texture = new Texture2D();

            texture.NativeResourceView = resourceView;
            return(texture);
        }
Exemple #24
0
        /// <summary>
        /// Create texture inplace with new parameters.
        /// Old texture will be completely discarded
        /// </summary>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="format"></param>
        /// <param name="mips"></param>
        void CreateFromFile(byte[] fileInMemory, string name, bool forceSRgb)
        {
            IntPtr resource     = new IntPtr(0);
            IntPtr resourceView = new IntPtr(0);
            bool   result;

            lock (device.DeviceContext) {
                if ((char)fileInMemory[0] == 'D' &&
                    (char)fileInMemory[1] == 'D' &&
                    (char)fileInMemory[2] == 'S' &&
                    (char)fileInMemory[3] == ' ')
                {
                    result = DdsLoader.CreateTextureFromMemory(device.Device.NativePointer, fileInMemory, forceSRgb, ref resource, ref resourceView);
                }
                else
                {
                    result = WicLoader.CreateTextureFromMemory(device.Device.NativePointer, fileInMemory, forceSRgb, ref resource, ref resourceView);
                }

                if (!result)
                {
                    throw new GraphicsException("Failed to load texture: " + name);
                }

                tex2D = new D3D.Texture2D(resource);
                SRV   = new D3D.ShaderResourceView(resourceView);
            }

            Width    = tex2D.Description.Width;
            Height   = tex2D.Description.Height;
            Depth    = 1;
            mipCount = tex2D.Description.MipLevels;
            format   = Converter.Convert(tex2D.Description.Format);
        }
 public void RemoveTexture(Texture2D texture)
 {
     if (m_textureMap.ContainsKey(texture))
     {
         m_textureMap.Remove(texture);
     }
 }
        public void SetGraphicItem(GraphicsCaptureItem item)
        {
            this.ResetState();
            this.item = item;

            if (this.item != null)
            {
                this.renderTargetDescription = new Texture2DDescription
                {
                    CpuAccessFlags    = CpuAccessFlags.None,
                    Width             = item.Size.Width,
                    Height            = item.Size.Height,
                    Usage             = ResourceUsage.Default,
                    Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    ArraySize         = 1,
                    BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    OptionFlags       = ResourceOptionFlags.Shared,
                    MipLevels         = 1,
                    SampleDescription = new SampleDescription(1, 0),
                };
                this.renderTarget = new Texture2D(d3dDevice, this.renderTargetDescription);

                framePool = Direct3D11CaptureFramePool.Create(device, DirectXPixelFormat.B8G8R8A8UIntNormalized, 2, this.item.Size);
                session   = framePool.CreateCaptureSession(this.item);
                lastSize  = this.item.Size;

                framePool.FrameArrived += this.OnFrameArrived;
                session.StartCapture();
            }
        }
        public D3D11.Texture2D GenerateCubemap(D3D11.Device device, Shader shader, int size, D3D11.Texture2D texture, int mipLevels, int mip)
        {
            Format format = Format.B8G8R8A8_UNorm;

            D3D11.Texture2DDescription renderTextureDesc = GetTexture2DDescription(size, format, mipLevels);

            D3D11.SamplerState sampler = GetSamplerState(device);

            D3D11.Texture2D RenderTexture = new D3D11.Texture2D(device, renderTextureDesc);

            D3D11.RenderTargetView[] skyRTVs = CreateRTVArray(device, format, RenderTexture, mip);

            perFaceBuffer = new D3D11.Buffer(device, SharpDX.Utilities.SizeOf <KDX_SKYBOX_ENV_RENDERER_BUFFER>(),
                                             D3D11.ResourceUsage.Default,
                                             D3D11.BindFlags.ConstantBuffer,
                                             D3D11.CpuAccessFlags.None,
                                             D3D11.ResourceOptionFlags.None, 0);


            //D3D11.DeviceContext deviceContext = device.ImmediateContext;

            SetupContext(device, size, shader, sampler, texture);
            Render(device, skyRTVs);


            return(RenderTexture);
        }
Exemple #28
0
        /// <summary>
        /// Creates texture
        /// </summary>
        /// <param name="device"></param>
        public Texture2D(GraphicsDevice device, int width, int height, ColorFormat format, int mipCount, bool srgb) : base(device)
        {
            this.Width    = width;
            this.Height   = height;
            this.Depth    = 1;
            this.format   = format;
            this.mipCount = mipCount;

            var texDesc = new Texture2DDescription();

            texDesc.ArraySize                 = 1;
            texDesc.BindFlags                 = BindFlags.ShaderResource;
            texDesc.CpuAccessFlags            = CpuAccessFlags.None;
            texDesc.Format                    = srgb ? MakeSRgb(Converter.Convert(format)) : Converter.Convert(format);
            texDesc.Height                    = Height;
            texDesc.MipLevels                 = mipCount;
            texDesc.OptionFlags               = ResourceOptionFlags.None;
            texDesc.SampleDescription.Count   = 1;
            texDesc.SampleDescription.Quality = 0;
            texDesc.Usage = ResourceUsage.Default;
            texDesc.Width = Width;

            lock (device.DeviceContext) {
                tex2D = new D3D.Texture2D(device.Device, texDesc);
                SRV   = new ShaderResourceView(device.Device, tex2D);
            }
        }
 public Player(Texture2D aTexture, Vector2 aLocation, Rectangle aGameBoundaries)
 {
     this._texture = aTexture;
     this.Location = aLocation;
     this.Velocity = Vector2.Zero;
     this.gameBoundaries = aGameBoundaries;
 }
Exemple #30
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="device"></param>
        /// <param name="size"></param>
        /// <param name="count"></param>
        /// <param name="format"></param>
        /// <param name="mips"></param>
        public TextureCubeArray(GraphicsDevice device, int size, int count, ColorFormat format, bool mips) : base(device)
        {
            if (count > 2048 / 6)
            {
                throw new GraphicsException("Too much elements in texture array");
            }

            this.Width    = size;
            this.Depth    = 1;
            this.Height   = size;
            this.MipCount = mips ? ShaderResource.CalculateMipLevels(Width, Height) : 1;

            var texDesc = new Texture2DDescription();

            texDesc.ArraySize                 = 6 * count;
            texDesc.BindFlags                 = BindFlags.ShaderResource;
            texDesc.CpuAccessFlags            = CpuAccessFlags.None;
            texDesc.Format                    = MakeTypeless(Converter.Convert(format));
            texDesc.Height                    = Height;
            texDesc.MipLevels                 = 0;
            texDesc.OptionFlags               = ResourceOptionFlags.TextureCube;
            texDesc.SampleDescription.Count   = 1;
            texDesc.SampleDescription.Quality = 0;
            texDesc.Usage = ResourceUsage.Default;
            texDesc.Width = Width;


            texCubeArray = new D3D.Texture2D(device.Device, texDesc);
            SRV          = new ShaderResourceView(device.Device, texCubeArray);
        }
		/// <summary>
		/// 
		/// </summary>
		/// <param name="device"></param>
		/// <param name="size"></param>
		/// <param name="count"></param>
		/// <param name="format"></param>
		/// <param name="mips"></param>
		public TextureCubeArray ( GraphicsDevice device, int size, int count, ColorFormat format, bool mips ) : base(device)
		{
			if (count>2048/6) {
				throw new GraphicsException("Too much elements in texture array");
			}

			this.Width		=	size;
			this.Depth		=	1;
			this.Height		=	size;
			this.MipCount	=	mips ? ShaderResource.CalculateMipLevels(Width,Height) : 1;

			var texDesc = new Texture2DDescription();

			texDesc.ArraySize		=	6 * count;
			texDesc.BindFlags		=	BindFlags.ShaderResource;
			texDesc.CpuAccessFlags	=	CpuAccessFlags.None;
			texDesc.Format			=	MakeTypeless( Converter.Convert( format ) );
			texDesc.Height			=	Height;
			texDesc.MipLevels		=	0;
			texDesc.OptionFlags		=	ResourceOptionFlags.TextureCube;
			texDesc.SampleDescription.Count	=	1;
			texDesc.SampleDescription.Quality	=	0;
			texDesc.Usage			=	ResourceUsage.Default;
			texDesc.Width			=	Width;


			texCubeArray	=	new D3D.Texture2D( device.Device, texDesc );
			SRV				=	new ShaderResourceView( device.Device, texCubeArray );
		}
 internal void ReleaseDevices()
 {
     IsRendererSuppressed = true;
     RenderTarget.Dispose();
     Backbuffer.Dispose();
     RenderTargetSurface.Dispose();
     RenderTargetView.Dispose();
     D2DDeviceContext.Dispose();
     D2DDevice.Dispose();
     D2DFactory.Dispose();
     DXGIDevice.Dispose();
     D3DDevice.Dispose();
     D3DDefaultDevice.Dispose();
     SwapChain.Dispose();
     SwapChain           = null;
     RenderTarget        = null;
     RenderTargetSurface = null;
     Backbuffer          = null;
     RenderTargetView    = null;
     D2DDeviceContext    = null;
     D2DFactory          = null;
     D2DDevice           = null;
     DXGIDevice          = null;
     D3DDevice           = null;
     D3DDefaultDevice    = null;
 }
Exemple #33
0
        protected void InitializeDeviceResources()
        {
            ModeDescription backBufferDesc = new ModeDescription(Width, Height, new Rational(60, 1), Format.R8G8B8A8_UNorm);

            SwapChainDescription swapChainDesc = new SwapChainDescription()
            {
                ModeDescription   = backBufferDesc,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = 1,
                OutputHandle      = renderForm.Handle,
                IsWindowed        = true
            };

            D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.None, swapChainDesc, out d3dDevice, out swapChain);
            d3dDeviceContext = d3dDevice.ImmediateContext;

            viewport = new Viewport(0, 0, Width, Height);
            d3dDeviceContext.Rasterizer.SetViewport(viewport);

            using (D3D11.Texture2D backBuffer = swapChain.GetBackBuffer <D3D11.Texture2D>(0))
            {
                renderTargetView = new D3D11.RenderTargetView(d3dDevice, backBuffer);
            }
        }
Exemple #34
0
        public DepthBuffer(Dx11ChainedDevice device, int width, int height)
        {
            try
            {
                _device = device;
                _depthBuffer = new Texture2D(_device.Device, new Texture2DDescription
                {
                    Format = Format.D32_Float_S8X24_UInt,
                    ArraySize = 1,
                    MipLevels = 1,
                    Width = width,
                    Height = height,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage = ResourceUsage.Default,
                    BindFlags = BindFlags.DepthStencil,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None
                });

                _depthView = new DepthStencilView(device.Device, _depthBuffer);
            }
            catch
            {
                Dispose();
                throw;
            }
        }
        void ResizeSurface()
        {
            Math.Rectangle newBounds = surface.Bounds;
            SurfaceSize   = newBounds.Size;
            SurfaceBounds = newBounds;

            deviceContext.OutputMerger.ResetTargets();
            swapChain.ResizeBuffers(0, (int)newBounds.Width, (int)newBounds.Height, DXGI.Format.R8G8B8A8_UNorm, DXGI.SwapChainFlags.None);
            deviceContext.Rasterizer.SetViewport(0, 0, newBounds.Width, newBounds.Height);

            viewMatrix  = Matrix.Transpose(Matrix.Scaling(2f / newBounds.Width, -2f / newBounds.Height, 1));
            viewMatrix *= Matrix.Transpose(Matrix.Translation(-newBounds.Width / 2f, -newBounds.Height / 2f, 0));
            UpdateMatrixBuffer();

            depthStencilView?.Dispose();
            depthStencilBuffer?.Dispose();
            surfaceTarget?.Dispose();
            surfaceView?.Dispose();
            surfaceTexture?.Dispose();

            depthStencilBuffer = device.CreateDepthStencilBuffer((int)newBounds.Width, (int)newBounds.Height, sampleDescription, out depthStencilView);
            surfaceTexture     = device.CreateSurface((int)newBounds.Width, (int)newBounds.Height, sampleDescription, out surfaceTarget);
            deviceContext.OutputMerger.SetTargets(depthStencilView, surfaceTarget);
            surfaceView = new D3D11.ShaderResourceView(device, surfaceTexture);
        }
        void OnResize(object sender, EventArgs args)
        {
            var texDesc = new Texture2DDescription
            {
                ArraySize = 1, BindFlags = BindFlags.None,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                Height = ClientSize.Height,
                Width = ClientSize.Width,
                Usage = ResourceUsage.Default,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                OptionFlags = ResourceOptionFlags.None,
                MipLevels = 1
            };

            if (mResolveTexture != null)
                mResolveTexture.Dispose();

            mResolveTexture = new Texture2D(WorldFrame.Instance.GraphicsContext.Device, texDesc);

            if (mMapTexture != null) mMapTexture.Dispose();

            texDesc.CpuAccessFlags = CpuAccessFlags.Read;
            texDesc.Usage = ResourceUsage.Staging;
            mMapTexture = new Texture2D(WorldFrame.Instance.GraphicsContext.Device, texDesc);

            mTarget.Resize(ClientSize.Width, ClientSize.Height, true);
            mCamera.SetAspect((float) ClientSize.Width / ClientSize.Height);
        }
Exemple #37
0
        /// <summary>
        /// Internal constructor to create RT for backbuffer.
        /// </summary>
        /// <param name="device"></param>
        /// <param name="backbufColor"></param>
        internal RenderTarget2D(GraphicsDevice device, D3D.Texture2D backbufColor, RenderTargetViewDescription?desc = null) : base(device)
        {
            Log.Debug("RenderTarget2D: from backbuffer.");

            if (backbufColor.Description.Format != DXGI.Format.R8G8B8A8_UNorm)
            {
                Log.Warning("R8G8B8A8_UNorm");
            }

            Width       = backbufColor.Description.Width;
            Height      = backbufColor.Description.Height;
            Format      = ColorFormat.Rgba8;
            MipCount    = 1;
            SampleCount = backbufColor.Description.SampleDescription.Count;
            SRV         = null;

            tex2D    = backbufColor;
            surfaces = new RenderTargetSurface[1];

            if (desc.HasValue)
            {
                surfaces[0] = new RenderTargetSurface(new RenderTargetView(device.Device, backbufColor, desc.Value), null, tex2D, 0, Format, Width, Height, SampleCount);
            }
            else
            {
                surfaces[0] = new RenderTargetSurface(new RenderTargetView(device.Device, backbufColor), null, tex2D, 0, Format, Width, Height, SampleCount);
            }
        }
Exemple #38
0
        /// <summary>
        /// Creates a new graphics resource.
        /// </summary>
        /// <param name="device">The graphics device to use.</param>
        /// <param name="dimensions">The resource dimensions.</param>
        /// <param name="format">The resource's DXGI format.</param>
        /// <param name="renderTargetView">Whether to bind as RTV.</param>
        /// <param name="shaderResourceView">Whether to bind as SRV.</param>
        /// <param name="hasMipMaps">Whether to enable mip-maps for this texture.</param>
        public GraphicsResource(Device device, Size dimensions, Format format, Boolean renderTargetView = true, Boolean shaderResourceView = true, Boolean hasMipMaps = false)
        {
            if ((!renderTargetView) && (!shaderResourceView))
                throw new ArgumentException("The requested resource cannot be bound at all to the pipeline.");

            if ((hasMipMaps) && ((!renderTargetView) || (!shaderResourceView)))
                throw new ArgumentException("A resource with mipmaps must be bound as both input and output.");

            BindFlags bindFlags = (renderTargetView ? BindFlags.RenderTarget : 0) | (shaderResourceView ? BindFlags.ShaderResource : 0);
            ResourceOptionFlags optionFlags = (hasMipMaps ? ResourceOptionFlags.GenerateMipMaps : 0);
            int mipLevels = (hasMipMaps ? MipLevels(dimensions) : 1);

            Resource = new Texture2D(device, new Texture2DDescription()
            {
                Format = format,
                BindFlags = bindFlags,
                Width = dimensions.Width,
                Height = dimensions.Height,

                ArraySize = 1,
                MipLevels = mipLevels,
                OptionFlags = optionFlags,
                Usage = ResourceUsage.Default,
                CpuAccessFlags = CpuAccessFlags.None,
                SampleDescription = new SampleDescription(1, 0),
            });

            RTV = (  renderTargetView ?   new RenderTargetView(device, Resource) : null);
            SRV = (shaderResourceView ? new ShaderResourceView(device, Resource) : null);
        }
Exemple #39
0
        public SoftwareRasterizerCore(Renderer renderer)
        {
            rasterizerMode = RasterizerMode.Both;
            outputMode     = OutputMode.Color;

            this.renderer = renderer;

            D3D11.Texture2DDescription texture2DDescription = new D3D11.Texture2DDescription
            {
                CpuAccessFlags    = D3D11.CpuAccessFlags.Write,
                BindFlags         = D3D11.BindFlags.None,
                Format            = DXGI.Format.R8G8B8A8_UNorm,
                Width             = renderer.width,
                Height            = renderer.height,
                OptionFlags       = D3D11.ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = D3D11.ResourceUsage.Staging
            };

            backbufferBitmap = new Bitmap(renderer.width, renderer.height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            depthbufferBitmap = new Bitmap(renderer.width, renderer.height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            screenTexture = new D3D11.Texture2D(renderer.device, texture2DDescription);
        }
Exemple #40
0
 private IntPtr GetSharedHandle(D3D11.Texture2D texture)
 {
     using (var resource = texture.QueryInterface <DXGI.Resource>())
     {
         return(resource.SharedHandle);
     }
 }
Exemple #41
0
        /// <summary>
        /// Copies the content of the specified texture.
        /// </summary>
        /// <param name="device">The Direct3D 11 device.</param>
        /// <param name="source">The source texture.</param>
        /// <param name="target">The target texture.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="device"/>, <paramref name="source"/> or <paramref name="target"/> is
        /// <see langword="null"/>.
        /// </exception>
        public static void Copy(Device device, Texture2D source, Texture2D target)
        {
            if (device == null)
            throw new ArgumentNullException("device");
              if (source == null)
            throw new ArgumentNullException("source");
              if (target == null)
            throw new ArgumentNullException("target");

              int sourceWidth = source.Description.Width;
              int sourceHeight = source.Description.Height;
              int targetWidth = target.Description.Width;
              int targetHeight = target.Description.Height;

              if (sourceWidth == targetWidth && sourceHeight == targetHeight)
              {
            device.ImmediateContext.CopyResource(source, target);
              }
              else
              {
            int width = Math.Min(sourceWidth, targetWidth);
            int height = Math.Min(sourceHeight, targetHeight);
            var region = new ResourceRegion(0, 0, 0, width, height, 1);
            device.ImmediateContext.CopySubresourceRegion(source, 0, region, target, 0);
              }
        }
Exemple #42
0
        /// <summary>
        /// Creates texture
        /// </summary>
        /// <param name="device"></param>
        public TextureCube(GraphicsDevice device, int size, ColorFormat format, bool mips, bool srgb = false) : base(device)
        {
            this.Width    = size;
            this.Depth    = 1;
            this.Height   = size;
            this.format   = format;
            this.mipCount = mips ? ShaderResource.CalculateMipLevels(Width, Height) : 1;

            //Log.Warning("CHECK ARRAY SIZE!");

            var texDesc = new Texture2DDescription();

            texDesc.ArraySize                 = 6;
            texDesc.BindFlags                 = BindFlags.ShaderResource;
            texDesc.CpuAccessFlags            = CpuAccessFlags.None;
            texDesc.Format                    = MakeTypeless(Converter.Convert(format));
            texDesc.Height                    = Height;
            texDesc.MipLevels                 = mipCount;
            texDesc.OptionFlags               = ResourceOptionFlags.TextureCube;
            texDesc.SampleDescription.Count   = 1;
            texDesc.SampleDescription.Quality = 0;
            texDesc.Usage = ResourceUsage.Default;
            texDesc.Width = Width;

            texCube = new D3D.Texture2D(device.Device, texDesc);
            SRV     = new ShaderResourceView(device.Device, texCube);
        }
        /// <summary>
        /// Creates a dynamic depth texture, allocates GPU resources
        /// </summary>
        /// <param name="device">Direct3D Device</param>
        public DynamicLongExposureInfraredTexture(Device device)
        {
            if (device == null)
                throw new ArgumentNullException("device");

            this.texture = new Texture2D(device, InfraredTextureDescriptors.DynamicResource);
            this.shaderView = new ShaderResourceView(device, this.texture);
        }
        /// <summary>
        /// Creates a dynamic color texture, allocates GPU resources
        /// </summary>
        /// <param name="device">Direct3D Device</param>
        public DynamicColorRGBATexture(Device device)
        {
            if (device == null)
                throw new ArgumentNullException("device");

            this.texture = new Texture2D(device, ColorTextureDescriptors.DynamicRGBAResource);
            this.rawView = new ShaderResourceView(device,this.texture);
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="device">Direct3D11 Device</param>
        public DynamicDepthToColorTexture(Device device)
        {
            if (device == null)
                throw new ArgumentNullException("device");

            this.texture = new Texture2D(device, CoordinateMapTextureDescriptors.DynamicDepthToColor);
            this.shaderView = new ShaderResourceView(device, this.texture);
        }
Exemple #46
0
        /// <summary>
        /// Creates render target
        /// </summary>
        /// <param name="rs"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="format"></param>
        public DepthStencilCube( GraphicsDevice device, DepthFormat format, int size, int samples, string debugName = "" )
            : base(device)
        {
            bool msaa	=	samples > 1;

            CheckSamplesCount( samples );

            SampleCount	=	samples;

            Format		=	format;
            SampleCount	=	samples;
            Width		=	size;
            Height		=	size;
            Depth		=	1;

            var	texDesc	=	new Texture2DDescription();
                texDesc.Width				=	Width;
                texDesc.Height				=	Height;
                texDesc.ArraySize			=	6;
                texDesc.BindFlags			=	BindFlags.RenderTarget | BindFlags.ShaderResource;
                texDesc.CpuAccessFlags		=	CpuAccessFlags.None;
                texDesc.Format				=	Converter.ConvertToTex( format );
                texDesc.MipLevels			=	1;
                texDesc.OptionFlags			=	ResourceOptionFlags.TextureCube;
                texDesc.SampleDescription	=	new DXGI.SampleDescription(samples, 0);
                texDesc.Usage				=	ResourceUsage.Default;

            texCube	=	new D3D.Texture2D( device.Device, texDesc );

            var srvDesc	=	new ShaderResourceViewDescription();
                srvDesc.Dimension			=	samples > 1 ? ShaderResourceViewDimension.Texture2DMultisampled : ShaderResourceViewDimension.Texture2D;
                srvDesc.Format				=	Converter.ConvertToSRV( format );
                srvDesc.Texture2D.MostDetailedMip	=	0;
                srvDesc.Texture2D.MipLevels			=	1;

            SRV		=	new ShaderResourceView( device.Device, texCube );

            //
            //	Create surfaces :
            //
            surfaces	=	new DepthStencilSurface[ 6 ];

            for ( int face=0; face<6; face++) {

                var rtvDesc = new DepthStencilViewDescription();
                    rtvDesc.Texture2DArray.MipSlice			=	0;
                    rtvDesc.Texture2DArray.FirstArraySlice	=	face;
                    rtvDesc.Texture2DArray.ArraySize		=	1;
                    rtvDesc.Dimension						=	msaa ? DepthStencilViewDimension.Texture2DMultisampledArray : DepthStencilViewDimension.Texture2DArray;
                    rtvDesc.Format							=	Converter.ConvertToDSV( format );

                var dsv	=	new DepthStencilView( device.Device, texCube, rtvDesc );

                int subResId	=	Resource.CalculateSubResourceIndex( 0, face, 1 );

                surfaces[face]	=	new DepthStencilSurface( dsv, format, Width, Height, SampleCount );
            }
        }
        /// <summary>
        /// Creates a dynamic depth texture, allocates GPU resources
        /// </summary>
        /// <param name="device">Direct3D Device</param>
        public DynamicDepthTexture(Device device)
        {
            if (device == null)
                throw new ArgumentNullException("device");

            this.texture = new Texture2D(device, DepthTextureDescriptors.DynamicResource);
            this.rawView = new ShaderResourceView(device,this.texture, DepthTextureDescriptors.RawView);
            this.normalizedView = new ShaderResourceView(device,this.texture, DepthTextureDescriptors.NormalizedView);
        }
 public TextureAsset(Device device, string name, Texture2D texture)
 {
     if (texture == null)
         throw new ArgumentNullException("texture");
         
     _device = device;
     _texture = texture;
     Name = name;
 }
Exemple #49
0
 public DXImage(Device device, DeviceContext deviceContext): base("DXImage")
 {
     _device = device;
     _deviceContext = deviceContext;
     _tex = null;
     _texSRV = null;
     _texWidth = 0;
     _texHeight = 0;
 }
Exemple #50
0
        public void LoadFromLoadInfo(IO.Files.Texture.TextureLoadInfo loadInfo)
        {
            var texDesc = new Texture2DDescription
            {
                ArraySize = 1,
                BindFlags = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = loadInfo.Format,
                Height = loadInfo.Height,
                Width = loadInfo.Width,
                MipLevels = loadInfo.Layers.Count,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default
            };

            if (mTexture != gDefaultTexture)
            {
                if (mTexture != null)
                    mTexture.Dispose();
                if (NativeView != null)
                    NativeView.Dispose();
            }

            var boxes = new DataBox[texDesc.MipLevels];
            var streams = new DataStream[texDesc.MipLevels];
            try
            {
                for(var i = 0; i < texDesc.MipLevels; ++i)
                {
                    streams[i] = new DataStream(loadInfo.Layers[i].Length, true, true);
                    streams[i].WriteRange(loadInfo.Layers[i]);
                    streams[i].Position = 0;
                    boxes[i] = new DataBox(streams[i].DataPointer, loadInfo.RowPitchs[i], 0);
                }

                mTexture = new Texture2D(mContext.Device, texDesc, boxes);
                var srvd = new ShaderResourceViewDescription
                {
                    Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D,
                    Format = loadInfo.Format,
                    Texture2D = new ShaderResourceViewDescription.Texture2DResource { MipLevels = boxes.Length, MostDetailedMip = 0 }
                };

                NativeView = new ShaderResourceView(mContext.Device, mTexture, srvd);
            }
            finally
            {
                foreach (var stream in streams)
                {
                    if (stream != null)
                        stream.Dispose();
                }
            }
        }
Exemple #51
0
        /// <summary>
        /// Creates depth stencil texture, view and shader resource with format D24S8
        /// </summary>
        /// <param name="rs"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="format"></param>
        public DepthStencil2D( GraphicsDevice device, DepthFormat format, int width, int height, int samples = 1 )
            : base(device)
        {
            CheckSamplesCount( samples );

            Width		=	width;
            Height		=	height;
            Depth		=	1;
            Format		=	format;
            SampleCount	=	samples;

            var bindFlags	=	BindFlags.DepthStencil;

            if (device.GraphicsProfile==GraphicsProfile.HiDef) {
                bindFlags	|=	BindFlags.ShaderResource;

            } else if (device.GraphicsProfile==GraphicsProfile.Reach) {
                if (samples==1) {
                    bindFlags	|=	BindFlags.ShaderResource;
                }
            }

            var	texDesc	=	new Texture2DDescription();
                texDesc.Width				=	width;
                texDesc.Height				=	height;
                texDesc.ArraySize			=	1;
                texDesc.BindFlags			=	bindFlags;
                texDesc.CpuAccessFlags		=	CpuAccessFlags.None;
                texDesc.Format				=	Converter.ConvertToTex( format );
                texDesc.MipLevels			=	1;
                texDesc.OptionFlags			=	ResourceOptionFlags.None;
                texDesc.SampleDescription	=	new DXGI.SampleDescription(samples, 0);
                texDesc.Usage				=	ResourceUsage.Default;

            var dsvDesc	=	new DepthStencilViewDescription();
                dsvDesc.Dimension			=	samples > 1 ? DepthStencilViewDimension.Texture2DMultisampled : DepthStencilViewDimension.Texture2D;
                dsvDesc.Format				=	Converter.ConvertToDSV( format );
                dsvDesc.Flags				=	DepthStencilViewFlags.None;

            var srvDesc	=	new ShaderResourceViewDescription();
                srvDesc.Dimension			=	samples > 1 ? ShaderResourceViewDimension.Texture2DMultisampled : ShaderResourceViewDimension.Texture2D;
                srvDesc.Format				=	Converter.ConvertToSRV( format );
                srvDesc.Texture2D.MostDetailedMip	=	0;
                srvDesc.Texture2D.MipLevels			=	1;

            tex2D		=	new D3D.Texture2D		( device.Device, texDesc );

            var dsv		=	new DepthStencilView	( device.Device, tex2D,	dsvDesc );

            if (bindFlags.HasFlag( BindFlags.ShaderResource)) {
                SRV		=	new ShaderResourceView	( device.Device, tex2D,	srvDesc );
            }

            surface		=	new DepthStencilSurface	( dsv, format, width, height, samples );
        }
Exemple #52
0
        public bool Initialise(System.Drawing.Bitmap bitmap)
        {
            RemoveAndDispose(ref _tex);
            RemoveAndDispose(ref _texSRV);

            //Debug.Assert(bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            System.Drawing.Imaging.BitmapData bmData;

            _texWidth = bitmap.Width;
            _texHeight = bitmap.Height;

            bmData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, _texWidth, _texHeight), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            try
            {
                Texture2DDescription texDesc = new Texture2DDescription();
                texDesc.Width = _texWidth;
                texDesc.Height = _texHeight;
                texDesc.MipLevels = 1;
                texDesc.ArraySize = 1;
                texDesc.Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm;
                texDesc.SampleDescription.Count = 1;
                texDesc.SampleDescription.Quality = 0;
                texDesc.Usage = ResourceUsage.Immutable;
                texDesc.BindFlags = BindFlags.ShaderResource;
                texDesc.CpuAccessFlags = CpuAccessFlags.None;
                texDesc.OptionFlags = ResourceOptionFlags.None;

                SharpDX.DataBox data;
                data.DataPointer = bmData.Scan0;
                data.RowPitch = bmData.Stride;// _texWidth * 4;
                data.SlicePitch = 0;

                _tex = ToDispose(new Texture2D(_device, texDesc, new[] { data }));
                if (_tex == null)
                    return false;

                ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription();
                srvDesc.Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm;
                srvDesc.Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D;
                srvDesc.Texture2D.MipLevels = 1;
                srvDesc.Texture2D.MostDetailedMip = 0;

                _texSRV = ToDispose(new ShaderResourceView(_device, _tex, srvDesc));
                if (_texSRV == null)
                    return false;
            }
            finally
            {
                bitmap.UnlockBits(bmData);
            }

            _initialised = true;

            return true;
        }
        public void Dispose()
        {
            if (_fontSheetTex != null)
                _fontSheetTex.Dispose();
            if (_fontSheetSRV != null)
                _fontSheetSRV.Dispose();

            _fontSheetTex = null;
            _fontSheetSRV = null;
            _device = null;
            _deviceContext = null;
        }
Exemple #54
0
 public DXFont(Device device, DeviceContext deviceContext)
 {
     _device = device;
     _deviceContext = deviceContext;
     _initialized = false;
     _fontSheetTex = null;
     _fontSheetSRV = null;
     _texWidth = 1024;
     _texHeight = 0;
     _spaceWidth = 0;
     _charHeight = 0;
 }
        /// <summary>
        /// Creates a dynamic depth texture, allocates GPU resources
        /// </summary>
        /// <param name="device">Direct3D Device</param>
        /// <param name="frameData">Initial frame data</param>
        public ImmutableInfraredTexture(Device device, InfraredFrameData frameData)
        {
            if (device == null)
                throw new ArgumentNullException("device");
            if (frameData == null)
                throw new ArgumentNullException("frameData");

            DataRectangle rect = new DataRectangle(frameData.DataPointer, Consts.DepthWidth * sizeof(ushort));

            this.texture = new Texture2D(device, InfraredTextureDescriptors.DynamicResource,rect);
            this.shaderView = new ShaderResourceView(device, this.texture);
        }
        public bool Initialize(Device device, SystemConfiguration configuration)
        {
            try
            {
                // Initialize and set up the render target description.
                var textureDesc = new Texture2DDescription()
                {
                    Width = configuration.Width,
                    Height = configuration.Height,
                    MipLevels = 1,
                    ArraySize = 1,
                    Format = Format.R32G32B32A32_Float,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage = ResourceUsage.Default,
                    BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None
                };

                // Create the render target texture.
                RenderTargetTexture = new Texture2D(device, textureDesc);

                // Initialize and setup the render target view
                var renderTargetViewDesc = new RenderTargetViewDescription()
                {
                    Format = textureDesc.Format,
                    Dimension = RenderTargetViewDimension.Texture2D,
                };
                renderTargetViewDesc.Texture2D.MipSlice = 0;

                // Create the render target view.
                RenderTargetView = new RenderTargetView(device, RenderTargetTexture, renderTargetViewDesc);

                // Initialize and setup the shader resource view
                var shaderResourceViewDesc = new ShaderResourceViewDescription()
                {
                    Format = textureDesc.Format,
                    Dimension = ShaderResourceViewDimension.Texture2D,
                };
                shaderResourceViewDesc.Texture2D.MipLevels = 1;
                shaderResourceViewDesc.Texture2D.MostDetailedMip = 0;

                // Create the render target view.
                ShaderResourceView = new ShaderResourceView(device, RenderTargetTexture, shaderResourceViewDesc);

                return true;
            }
            catch
            {
                return false;
            }
        }
Exemple #57
0
        /// <summary>
        /// Convenience factory to create table from Kinect point list
        /// </summary>
        /// <param name="device">Direct3D Device</param>
        /// <param name="initialData">Initial points array</param>
        /// <returns>Ray table texture</returns>
        public static unsafe RayTableTexture FromPoints(Device device, PointF[] initialData)
        {
            if (initialData.Length != Consts.DepthPixelCount)
                throw new ArgumentException("initialData", "Initial data length should be same size as depth frame pixel count");

            fixed (PointF* ptr = &initialData[0])
            {
                DataRectangle rect = new DataRectangle(new IntPtr(ptr), Consts.DepthWidth * 8);
                var texture = new Texture2D(device, LookupTableTextureDescriptors.DepthToCameraRayTable, rect);
                var view = new ShaderResourceView(device, texture);
                return new RayTableTexture(texture, view);
            }
        }
 public static void CopyToTexture(DeviceContext1 context, Texture2D source, Texture2D destination, int subResource = 0)
 {
     if (source.Description.SampleDescription.Count > 1 || source.Description.SampleDescription.Quality > 0)
     {
         context.ResolveSubresource(source, subResource, destination, 0, destination.Description.Format);
     }
     else
     {
         // Not multisampled, so just copy to the destination
         context.CopySubresourceRegion(source, subResource, null, destination, 0);
         //context.CopyResource(source, destination);
     }
 }
        /// <summary>
        /// Creates an immutable depth texture, allocates GPU resources
        /// </summary>
        /// <param name="device">Direct3D Device</param>
        /// <param name="data">Depth frame data</param>
        public ImmutableDepthTexture(Device device, DepthFrameData data)
        {
            if (device == null)
                throw new ArgumentNullException("device");
            if (data == null)
                throw new ArgumentNullException("data");

            DataRectangle dr = new DataRectangle(data.DataPointer, Consts.DepthWidth * sizeof(ushort));

            this.texture = new Texture2D(device, DepthTextureDescriptors.ImmutableResource, dr);
            this.rawView = new ShaderResourceView(device,this.texture, DepthTextureDescriptors.RawView);
            this.normalizedView = new ShaderResourceView(device,this.texture, DepthTextureDescriptors.NormalizedView);
        }
 protected override void UninitializeInternal()
 {
     if(ShaderResourceView != null)
     {
         ShaderResourceView.Dispose();
         ShaderResourceView = null;
     }
     if(_textureArray != null)
     {
         _textureArray.Dispose();
         _textureArray = null;
     }
 }