public unsafe Span <T> AsSpan <T>(ID3D11Texture2D resource, int mipSlice, int arraySlice) where T : unmanaged
    {
        resource.CalculateSubResourceIndex(mipSlice, arraySlice, out int mipSize);
        Span <byte> source = new Span <byte>(DataPointer.ToPointer(), mipSize * RowPitch);

        return(MemoryMarshal.Cast <byte, T>(source));
    }
Пример #2
0
        void resize()
        {
            if (renderView == null)//first show
            {
                var dxgiFactory = device.QueryInterface <IDXGIDevice>().GetParent <IDXGIAdapter>().GetParent <IDXGIFactory>();

                var swapchainDesc = new SwapChainDescription()
                {
                    BufferCount       = 1,
                    BufferDescription = new ModeDescription(Win32Window.Width, Win32Window.Height, format),
                    IsWindowed        = true,
                    OutputWindow      = Win32Window.Handle,
                    SampleDescription = new SampleDescription(1, 0),
                    SwapEffect        = SwapEffect.Discard,
                    Usage             = Vortice.DXGI.Usage.RenderTargetOutput
                };

                swapChain = dxgiFactory.CreateSwapChain(device, swapchainDesc);
                dxgiFactory.MakeWindowAssociation(Win32Window.Handle, WindowAssociationFlags.IgnoreAll);

                backBuffer = swapChain.GetBuffer <ID3D11Texture2D>(0);
                renderView = device.CreateRenderTargetView(backBuffer);
            }
            else
            {
                renderView.Dispose();
                backBuffer.Dispose();

                swapChain.ResizeBuffers(1, Win32Window.Width, Win32Window.Height, format, SwapChainFlags.None);

                backBuffer = swapChain.GetBuffer <ID3D11Texture2D1>(0);
                renderView = device.CreateRenderTargetView(backBuffer);
            }
        }
Пример #3
0
        public D3D11GraphicsDevice(bool validation, Window window)
        {
            Window = window;
            if (CreateDXGIFactory1(out Factory).Failure)
            {
                throw new InvalidOperationException("Cannot create IDXGIFactory1");
            }

            var creationFlags = DeviceCreationFlags.BgraSupport;

            if (validation)
            {
                creationFlags |= DeviceCreationFlags.Debug;
            }

            if (D3D11CreateDevice(
                    null,
                    DriverType.Hardware,
                    creationFlags,
                    _featureLevels,
                    out Device, out FeatureLevel, out DeviceContext).Failure)
            {
                // Remove debug flag not being supported.
                creationFlags &= ~DeviceCreationFlags.Debug;

                var result = D3D11CreateDevice(null, DriverType.Hardware,
                                               creationFlags, _featureLevels,
                                               out Device, out FeatureLevel, out DeviceContext);
                if (result.Failure)
                {
                    // This will fail on Win 7 due to lack of 11.1, so re-try again without it
                    D3D11CreateDevice(
                        null,
                        DriverType.Hardware,
                        creationFlags,
                        _featureLevelsNoLevel11,
                        out Device, out FeatureLevel, out DeviceContext).CheckError();
                }
            }

            var hwnd = (IntPtr)window.Handle;

            var swapChainDescription = new SwapChainDescription()
            {
                BufferCount       = FrameCount,
                BufferDescription = new ModeDescription(window.Width, window.Height, Format.B8G8R8A8_UNorm),
                IsWindowed        = true,
                OutputWindow      = hwnd,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Vortice.DirectX.Usage.RenderTargetOutput
            };

            SwapChain = Factory.CreateSwapChain(Device, swapChainDescription);
            Factory.MakeWindowAssociation(hwnd, WindowAssociationFlags.IgnoreAltEnter);

            BackBuffer       = SwapChain.GetBuffer <ID3D11Texture2D>(0);
            RenderTargetView = Device.CreateRenderTargetView(BackBuffer);
        }
        private ID3D11Texture2D GetHolographicBackBuffer()
        {
            HolographicSurface         = HolographicFrame.GetRenderingParameters(HolographicFrame.CurrentPrediction.CameraPoses[0]).Direct3D11BackBuffer;
            using IDXGISurface surface = Direct3DInterop.CreateDXGISurface(HolographicSurface);

            ID3D11Texture2D d3DBackBuffer = new ID3D11Texture2D(surface.NativePointer);

            PresentationParameters.BackBufferFormat = (PixelFormat)d3DBackBuffer.Description.Format;
            PresentationParameters.BackBufferWidth  = d3DBackBuffer.Description.Width;
            PresentationParameters.BackBufferHeight = d3DBackBuffer.Description.Height;

            return(d3DBackBuffer);
        }
    /// <summary>
    /// Initializes a new instance of the <see cref="RenderTargetViewDescription"/> struct.
    /// </summary>
    /// <param name="texture"></param>
    /// <param name="viewDimension"></param>
    /// <param name="format"></param>
    /// <param name="mipSlice"></param>
    /// <param name="firstArraySlice"></param>
    /// <param name="arraySize"></param>
    /// <param name="planeSlice"></param>
    public RenderTargetViewDescription1(
        ID3D11Texture2D texture,
        RenderTargetViewDimension viewDimension,
        Format format       = Format.Unknown,
        int mipSlice        = 0,
        int firstArraySlice = 0,
        int arraySize       = -1,
        int planeSlice      = 0)
        : this()
    {
        ViewDimension = viewDimension;
        if (format == Format.Unknown ||
            (-1 == arraySize && (RenderTargetViewDimension.Texture2DArray == viewDimension || RenderTargetViewDimension.Texture2DMultisampledArray == viewDimension)))
        {
            var textureDesc = texture.Description;
            if (format == Format.Unknown)
            {
                format = textureDesc.Format;
            }
            if (-1 == arraySize)
            {
                arraySize = textureDesc.ArraySize - firstArraySlice;
            }
        }
        Format = format;
        switch (viewDimension)
        {
        case RenderTargetViewDimension.Texture2D:
            Texture2D.MipSlice   = mipSlice;
            Texture2D.PlaneSlice = planeSlice;
            break;

        case RenderTargetViewDimension.Texture2DArray:
            Texture2DArray.MipSlice        = mipSlice;
            Texture2DArray.FirstArraySlice = firstArraySlice;
            Texture2DArray.ArraySize       = arraySize;
            Texture2DArray.PlaneSlice      = planeSlice;
            break;

        case RenderTargetViewDimension.Texture2DMultisampled:
            break;

        case RenderTargetViewDimension.Texture2DMultisampledArray:
            Texture2DMSArray.FirstArraySlice = firstArraySlice;
            Texture2DMSArray.ArraySize       = arraySize;
            break;

        default:
            break;
        }
    }
Пример #6
0
    /// <summary>
    /// Initializes a new instance of the <see cref="DepthStencilViewDescription"/> struct.
    /// </summary>
    /// <param name="texture"></param>
    /// <param name="viewDimension"></param>
    /// <param name="format"></param>
    /// <param name="mipSlice"></param>
    /// <param name="firstArraySlice"></param>
    /// <param name="arraySize"></param>
    /// <param name="flags"></param>
    public DepthStencilViewDescription(
        ID3D11Texture2D texture,
        DepthStencilViewDimension viewDimension,
        Format format               = Format.Unknown,
        int mipSlice                = 0,
        int firstArraySlice         = 0,
        int arraySize               = -1,
        DepthStencilViewFlags flags = DepthStencilViewFlags.None) : this()
    {
        ViewDimension = viewDimension;
        Flags         = flags;

        if (format == Format.Unknown ||
            (-1 == arraySize && (DepthStencilViewDimension.Texture2DArray == viewDimension || DepthStencilViewDimension.Texture2DMultisampledArray == viewDimension)))
        {
            var textureDesc = texture.Description;
            if (format == Format.Unknown)
            {
                format = textureDesc.Format;
            }
            if (arraySize == -1)
            {
                arraySize = textureDesc.ArraySize - firstArraySlice;
            }
        }
        Format = format;
        switch (viewDimension)
        {
        case DepthStencilViewDimension.Texture2D:
            Texture2D.MipSlice = mipSlice;
            break;

        case DepthStencilViewDimension.Texture2DArray:
            Texture2DArray.MipSlice        = mipSlice;
            Texture2DArray.FirstArraySlice = firstArraySlice;
            Texture2DArray.ArraySize       = arraySize;
            break;

        case DepthStencilViewDimension.Texture2DMultisampled:
            break;

        case DepthStencilViewDimension.Texture2DMultisampledArray:
            Texture2DMSArray.FirstArraySlice = firstArraySlice;
            Texture2DMSArray.ArraySize       = arraySize;
            break;

        default:
            break;
        }
    }
Пример #7
0
        public void Resize(int w, int h)
        {
            // TODO:
            //DeviceContext.OMSetRenderTargets(null);
            m_RenderTargetView.Dispose();
            SwapChain.ResizeBuffers(0, w, h, Format.Unknown, SwapChainFlags.None);
            ID3D11Texture2D buffer = SwapChain.GetBuffer <ID3D11Texture2D>(0);
            //m_RenderTargetView =
            //buffer.Dispose();

            //BuildDepthStencilView(w, h);

            //DeviceContext.OMSetRenderTargets(m_RenderTargetView, m_DepthStencilView);
            //DeviceContext.RSSetViewport(0, 0, w, h, ToolkitSettings.ScreenNear, ToolkitSettings.ScreenDepth);
        }
        private void StartDesktopDuplicator(int adapterId, int outputId)
        {
            var adapter = factory.GetAdapter1(adapterId);

            D3D11.D3D11CreateDevice(adapter, DriverType.Unknown, DeviceCreationFlags.None, s_featureLevels, out device);

            var output  = adapter.GetOutput(outputId);
            var output1 = output.QueryInterface <IDXGIOutput1>();

            var bounds = output1.Description.DesktopCoordinates;
            var width  = bounds.Right - bounds.Left;
            var height = bounds.Bottom - bounds.Top;

            var textureDesc = new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = width / 2,
                Height            = height / 2,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = Usage.Staging
            };

            stagingTexture = device.CreateTexture2D(textureDesc);

            var smallerTextureDesc = new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.None,
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = width,
                Height            = height,
                OptionFlags       = ResourceOptionFlags.GenerateMips,
                MipLevels         = 4,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = Usage.Default
            };

            smallerTexture     = device.CreateTexture2D(smallerTextureDesc);
            smallerTextureView = device.CreateShaderResourceView(smallerTexture);

            duplication = output1.DuplicateOutput(device);
        }
Пример #9
0
        public ID3D11Texture2D GetBackbuffer(ID3D11Device device, IntPtr hWnd)
        {
            if (!m_swapChain)
            {
                using (var dxgiDevice = new IDXGIDevice2())
                {
                    device.QueryInterface(ref IDXGIDevice2.IID, out dxgiDevice.PtrForNew).ThrowIfFailed();

                    dxgiDevice.GetAdapter(out IDXGIAdapter dxgiAdapter).ThrowIfFailed();
                    using (dxgiAdapter)
                    {
                        using (var dxgiFactory = new IDXGIFactory2())
                        {
                            dxgiAdapter.GetParent(ref IDXGIFactory2.IID, out dxgiFactory.PtrForNew).ThrowIfFailed();

                            var desc = new DXGI_SWAP_CHAIN_DESC1
                            {
                                Format      = DXGI_FORMAT._B8G8R8A8_UNORM,
                                AlphaMode   = DXGI_ALPHA_MODE._UNSPECIFIED,
                                BufferUsage = DXGI_USAGE._RENDER_TARGET_OUTPUT,
                                Scaling     = DXGI_SCALING._NONE,
                                BufferCount = 2,
                                SwapEffect  = DXGI_SWAP_EFFECT._FLIP_SEQUENTIAL,
                                SampleDesc  = new DXGI_SAMPLE_DESC
                                {
                                    Count   = 1,
                                    Quality = 0,
                                },
                            };

                            var fs_desc = new DXGI_SWAP_CHAIN_FULLSCREEN_DESC
                            {
                                Windowed = 1,
                            };

                            var hr = dxgiFactory.CreateSwapChainForHwnd(device, hWnd, ref desc, ref fs_desc, null, out m_swapChain);
                            hr.ThrowIfFailed();
                        }
                    }
                }
            }

            var texture = new ID3D11Texture2D();

            m_swapChain.GetBuffer(0, ref ID3D11Texture2D.IID, out texture.PtrForNew).ThrowIfFailed();
            return(texture);
        }
Пример #10
0
    /// <summary>
    /// Initializes a new instance of the <see cref="UnorderedAccessViewDescription1"/> struct.
    /// </summary>
    /// <param name="texture"></param>
    /// <param name="viewDimension"></param>
    /// <param name="format"></param>
    /// <param name="mipSlice"></param>
    /// <param name="firstArraySlice"></param>
    /// <param name="arraySize"></param>
    /// <param name="planeSlice"></param>
    public UnorderedAccessViewDescription1(
        ID3D11Texture2D texture,
        UnorderedAccessViewDimension viewDimension,
        Format format       = Format.Unknown,
        int mipSlice        = 0,
        int firstArraySlice = 0,
        int arraySize       = -1,
        int planeSlice      = 0) : this()
    {
        ViewDimension = viewDimension;

        if (format == Format.Unknown ||
            (-1 == arraySize && (viewDimension == UnorderedAccessViewDimension.Texture2DArray)))
        {
            var textureDesc = texture.Description;
            if (format == Format.Unknown)
            {
                format = textureDesc.Format;
            }
            if (arraySize == -1)
            {
                arraySize = textureDesc.ArraySize - firstArraySlice;
            }
        }
        Format = format;
        switch (viewDimension)
        {
        case UnorderedAccessViewDimension.Texture2D:
            Texture2D.MipSlice   = mipSlice;
            Texture2D.PlaneSlice = planeSlice;
            break;

        case UnorderedAccessViewDimension.Texture2DArray:
            Texture2DArray.MipSlice        = mipSlice;
            Texture2DArray.FirstArraySlice = firstArraySlice;
            Texture2DArray.ArraySize       = arraySize;
            Texture2DArray.PlaneSlice      = planeSlice;
            break;
        }
    }
Пример #11
0
        public D3D11Texture(ID3D11Texture2D existingTexture, TextureType type, PixelFormat format)
        {
            _device       = existingTexture.Device;
            DeviceTexture = existingTexture;
            Width         = (uint)existingTexture.Description.Width;
            Height        = (uint)existingTexture.Description.Height;
            Depth         = 1;
            MipLevels     = (uint)existingTexture.Description.MipLevels;
            ArrayLayers   = (uint)existingTexture.Description.ArraySize;
            Format        = format;
            SampleCount   = FormatHelpers.GetSampleCount((uint)existingTexture.Description.SampleDescription.Count);
            Type          = type;
            Usage         = D3D11Formats.GetVdUsage(
                existingTexture.Description.BindFlags,
                existingTexture.Description.CpuAccessFlags,
                existingTexture.Description.OptionFlags);

            DxgiFormat = D3D11Formats.ToDxgiFormat(
                format,
                (Usage & TextureUsage.DepthStencil) == TextureUsage.DepthStencil);
            TypelessDxgiFormat = D3D11Formats.GetTypelessFormat(DxgiFormat);
        }
Пример #12
0
    /// <summary>
    /// Initializes a new instance of the <see cref="ShaderResourceViewDescription1"/> struct.
    /// </summary>
    /// <param name="texture"></param>
    /// <param name="viewDimension"></param>
    /// <param name="format"></param>
    /// <param name="mostDetailedMip"></param>
    /// <param name="mipLevels"></param>
    /// <param name="firstArraySlice"></param>
    /// <param name="arraySize"></param>
    /// <param name="planeSlice"></param>
    public ShaderResourceViewDescription1(
        ID3D11Texture2D texture,
        ShaderResourceViewDimension viewDimension,
        Format format       = Format.Unknown,
        int mostDetailedMip = 0,
        int mipLevels       = -1,
        int firstArraySlice = 0,
        int arraySize       = -1,
        int planeSlice      = 0)
        : this()
    {
        ViewDimension = viewDimension;
        if (format == Format.Unknown ||
            (mipLevels == -1 && viewDimension != ShaderResourceViewDimension.Texture2DMultisampled && viewDimension != ShaderResourceViewDimension.Texture2DMultisampledArray) ||
            (arraySize == -1 && (ShaderResourceViewDimension.Texture2DArray == viewDimension || ShaderResourceViewDimension.Texture2DMultisampledArray == viewDimension || ShaderResourceViewDimension.TextureCubeArray == viewDimension)))
        {
            var textureDesc = texture.Description;
            if (format == Format.Unknown)
            {
                format = textureDesc.Format;
            }
            if (-1 == mipLevels)
            {
                mipLevels = textureDesc.MipLevels - mostDetailedMip;
            }
            if (-1 == arraySize)
            {
                arraySize = textureDesc.ArraySize - firstArraySlice;
                if (viewDimension == ShaderResourceViewDimension.TextureCubeArray)
                {
                    arraySize /= 6;
                }
            }
        }
        Format = format;
        switch (viewDimension)
        {
        case ShaderResourceViewDimension.Texture2D:
            Texture2D.MostDetailedMip = mostDetailedMip;
            Texture2D.MipLevels       = mipLevels;
            Texture2D.PlaneSlice      = planeSlice;
            break;

        case ShaderResourceViewDimension.Texture2DArray:
            Texture2DArray.MostDetailedMip = mostDetailedMip;
            Texture2DArray.MipLevels       = mipLevels;
            Texture2DArray.FirstArraySlice = firstArraySlice;
            Texture2DArray.ArraySize       = arraySize;
            Texture2DArray.PlaneSlice      = planeSlice;
            break;

        case ShaderResourceViewDimension.Texture2DMultisampled:
            break;

        case ShaderResourceViewDimension.Texture2DMultisampledArray:
            Texture2DMSArray.FirstArraySlice = firstArraySlice;
            Texture2DMSArray.ArraySize       = arraySize;
            break;

        case ShaderResourceViewDimension.TextureCube:
            TextureCube.MostDetailedMip = mostDetailedMip;
            TextureCube.MipLevels       = mipLevels;
            break;

        case ShaderResourceViewDimension.TextureCubeArray:
            TextureCubeArray.MostDetailedMip  = mostDetailedMip;
            TextureCubeArray.MipLevels        = mipLevels;
            TextureCubeArray.First2DArrayFace = firstArraySlice;
            TextureCubeArray.NumCubes         = arraySize;
            break;

        default:
            break;
        }
    }
Пример #13
0
            private unsafe void SaveScreenshot(string path, ContainerFormat format = ContainerFormat.Jpeg)
            {
                var             d3d11GraphicsDevice = ((D3D11GraphicsDevice)_graphicsDevice !);
                ID3D11Texture2D source = Headless ? d3d11GraphicsDevice !.OffscreenTexture : d3d11GraphicsDevice !.BackBufferTexture;

                using (ID3D11Texture2D staging = d3d11GraphicsDevice !.CaptureTexture(source))
                {
                    staging.DebugName = "STAGING";

                    var textureDesc = staging !.Description;

                    // Determine source format's WIC equivalent
                    Guid pfGuid = default;
                    bool sRGB   = false;
                    switch (textureDesc.Format)
                    {
                    case Vortice.DXGI.Format.R32G32B32A32_Float:
                        pfGuid = WICPixelFormat.Format128bppRGBAFloat;
                        break;

                    //case DXGI_FORMAT_R16G16B16A16_FLOAT: pfGuid = GUID_WICPixelFormat64bppRGBAHalf; break;
                    //case DXGI_FORMAT_R16G16B16A16_UNORM: pfGuid = GUID_WICPixelFormat64bppRGBA; break;
                    //case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: pfGuid = GUID_WICPixelFormat32bppRGBA1010102XR; break; // DXGI 1.1
                    //case DXGI_FORMAT_R10G10B10A2_UNORM: pfGuid = GUID_WICPixelFormat32bppRGBA1010102; break;
                    //case DXGI_FORMAT_B5G5R5A1_UNORM: pfGuid = GUID_WICPixelFormat16bppBGRA5551; break;
                    //case DXGI_FORMAT_B5G6R5_UNORM: pfGuid = GUID_WICPixelFormat16bppBGR565; break;
                    //case DXGI_FORMAT_R32_FLOAT: pfGuid = GUID_WICPixelFormat32bppGrayFloat; break;
                    //case DXGI_FORMAT_R16_FLOAT: pfGuid = GUID_WICPixelFormat16bppGrayHalf; break;
                    //case DXGI_FORMAT_R16_UNORM: pfGuid = GUID_WICPixelFormat16bppGray; break;
                    //case DXGI_FORMAT_R8_UNORM: pfGuid = GUID_WICPixelFormat8bppGray; break;
                    //case DXGI_FORMAT_A8_UNORM: pfGuid = GUID_WICPixelFormat8bppAlpha; break;

                    case Vortice.DXGI.Format.R8G8B8A8_UNorm:
                        pfGuid = WICPixelFormat.Format32bppRGBA;
                        break;

                    case Vortice.DXGI.Format.R8G8B8A8_UNorm_SRgb:
                        pfGuid = WICPixelFormat.Format32bppRGBA;
                        sRGB   = true;
                        break;

                    case Vortice.DXGI.Format.B8G8R8A8_UNorm:     // DXGI 1.1
                        pfGuid = WICPixelFormat.Format32bppBGRA;
                        break;

                    case Vortice.DXGI.Format.B8G8R8A8_UNorm_SRgb:     // DXGI 1.1
                        pfGuid = WICPixelFormat.Format32bppBGRA;
                        sRGB   = true;
                        break;

                    case Vortice.DXGI.Format.B8G8R8X8_UNorm:     // DXGI 1.1
                        pfGuid = WICPixelFormat.Format32bppBGR;
                        break;

                    case Vortice.DXGI.Format.B8G8R8X8_UNorm_SRgb:     // DXGI 1.1
                        pfGuid = WICPixelFormat.Format32bppBGR;
                        sRGB   = true;
                        break;

                    default:
                        //Console.WriteLine("ERROR: ScreenGrab does not support all DXGI formats (%u). Consider using DirectXTex.\n", static_cast<uint32_t>(desc.Format));
                        return;
                    }

                    // Screenshots don't typically include the alpha channel of the render target
                    Guid targetGuid = default;
                    switch (textureDesc.Format)
                    {
                    case Vortice.DXGI.Format.R32G32B32A32_Float:
                    case Vortice.DXGI.Format.R16G16B16A16_Float:
                        //if (_IsWIC2())
                    {
                        targetGuid = WICPixelFormat.Format96bppRGBFloat;
                    }
                        //else
                        //{
                        //    targetGuid = WICPixelFormat.Format24bppBGR;
                        //}
                        break;

                    case Vortice.DXGI.Format.R16G16B16A16_UNorm:
                        targetGuid = WICPixelFormat.Format48bppBGR;
                        break;

                    case Vortice.DXGI.Format.B5G5R5A1_UNorm:
                        targetGuid = WICPixelFormat.Format16bppBGR555;
                        break;

                    case Vortice.DXGI.Format.B5G6R5_UNorm:
                        targetGuid = WICPixelFormat.Format16bppBGR565;
                        break;

                    case Vortice.DXGI.Format.R32_Float:
                    case Vortice.DXGI.Format.R16_Float:
                    case Vortice.DXGI.Format.R16_UNorm:
                    case Vortice.DXGI.Format.R8_UNorm:
                    case Vortice.DXGI.Format.A8_UNorm:
                        targetGuid = WICPixelFormat.Format8bppGray;
                        break;

                    default:
                        targetGuid = WICPixelFormat.Format24bppBGR;
                        break;
                    }

                    using var wicFactory            = new IWICImagingFactory();
                    using IWICBitmapDecoder decoder = wicFactory.CreateDecoderFromFileName(path);


                    using Stream stream             = File.OpenWrite(path);
                    using IWICStream wicStream      = wicFactory.CreateStream(stream);
                    using IWICBitmapEncoder encoder = wicFactory.CreateEncoder(format, wicStream);
                    // Create a Frame encoder
                    var props = new SharpGen.Runtime.Win32.PropertyBag();
                    var frame = encoder.CreateNewFrame(props);
                    frame.Initialize(props);
                    frame.SetSize(textureDesc.Width, textureDesc.Height);
                    frame.SetResolution(72, 72);
                    frame.SetPixelFormat(targetGuid);

                    var context = d3d11GraphicsDevice !.DeviceContext;
                    //var mapped = context.Map(staging, 0, MapMode.Read, MapFlags.None);
                    Span <Color> colors = context.Map <Color>(staging, 0, 0, MapMode.Read, MapFlags.None);

                    // Check conversion
                    if (targetGuid != pfGuid)
                    {
                        // Conversion required to write
                        using (IWICBitmap bitmapSource = wicFactory.CreateBitmapFromMemory(
                                   textureDesc.Width,
                                   textureDesc.Height,
                                   pfGuid,
                                   colors))
                        {
                            using (IWICFormatConverter formatConverter = wicFactory.CreateFormatConverter())
                            {
                                formatConverter.CanConvert(pfGuid, targetGuid, out RawBool canConvert);
                                if (!canConvert)
                                {
                                    context.Unmap(staging, 0);
                                    return;
                                }

                                formatConverter.Initialize(bitmapSource, targetGuid, BitmapDitherType.None, null, 0, BitmapPaletteType.MedianCut);
                                frame.WriteSource(formatConverter, new Rectangle(textureDesc.Width, textureDesc.Height));
                            }
                        }
                    }
                    else
                    {
                        // No conversion required
                        int stride = WICPixelFormat.GetStride(pfGuid, textureDesc.Width);
                        frame.WritePixels(textureDesc.Height, stride, colors);
                    }

                    context.Unmap(staging, 0);
                    frame.Commit();
                    encoder.Commit();
                }
            }
Пример #14
0
        //private readonly Dictionary<TextureViewDescriptor, TextureViewD3D11> _views = new Dictionary<TextureViewDescriptor, TextureViewD3D11>();

        public TextureD3D11(DeviceD3D11 device, ref TextureDescriptor descriptor, ID3D11Texture2D nativeTexture, Format dxgiFormat)
            : base(device, ref descriptor)
        {
            Resource   = nativeTexture;
            DXGIFormat = dxgiFormat;
        }
 internal D3D11Texture2D(ID3D11Texture2D texture2D)
 {
     this.texture2D = texture2D;
 }
Пример #16
0
    public ID3D11Texture2D CaptureTexture(ID3D11Texture2D source)
    {
        ID3D11Texture2D      stagingTexture;
        Texture2DDescription desc = source.Description;

        if (desc.ArraySize > 1 || desc.MipLevels > 1)
        {
            Console.WriteLine("WARNING: ScreenGrab does not support 2D arrays, cubemaps, or mipmaps; only the first surface is written. Consider using DirectXTex instead.");
            return(null);
        }

        if (desc.SampleDescription.Count > 1)
        {
            // MSAA content must be resolved before being copied to a staging texture
            desc.SampleDescription.Count   = 1;
            desc.SampleDescription.Quality = 0;

            ID3D11Texture2D temp   = Device.CreateTexture2D(desc);
            Format          format = desc.Format;

            FormatSupport formatSupport = Device.CheckFormatSupport(format);

            if ((formatSupport & FormatSupport.MultisampleResolve) == FormatSupport.None)
            {
                throw new NotSupportedException($"Format {format} doesn't support multisample resolve");
            }

            for (int item = 0; item < desc.ArraySize; ++item)
            {
                for (int level = 0; level < desc.MipLevels; ++level)
                {
                    int index = CalculateSubResourceIndex(level, item, desc.MipLevels);
                    DeviceContext.ResolveSubresource(temp, index, source, index, format);
                }
            }

            desc.BindFlags      = BindFlags.None;
            desc.MiscFlags     &= ResourceOptionFlags.TextureCube;
            desc.CPUAccessFlags = CpuAccessFlags.Read;
            desc.Usage          = ResourceUsage.Staging;

            stagingTexture = Device.CreateTexture2D(desc);

            DeviceContext.CopyResource(stagingTexture, temp);
        }
        else if ((desc.Usage == ResourceUsage.Staging) && ((desc.CPUAccessFlags & CpuAccessFlags.Read) != CpuAccessFlags.None))
        {
            // Handle case where the source is already a staging texture we can use directly
            stagingTexture = source;
        }
        else
        {
            // Otherwise, create a staging texture from the non-MSAA source
            desc.BindFlags      = 0;
            desc.MiscFlags     &= ResourceOptionFlags.TextureCube;
            desc.CPUAccessFlags = CpuAccessFlags.Read;
            desc.Usage          = ResourceUsage.Staging;

            stagingTexture = Device.CreateTexture2D(desc);

            DeviceContext.CopyResource(stagingTexture, source);
        }

        return(stagingTexture);
    }
Пример #17
0
 public Texture2D(ID3D11Texture2D texture, ID3D11ShaderResourceView textureView, uint width, in uint height)
Пример #18
0
        protected override Texture CreateTextureCore(ulong nativeTexture, ref TextureDescription description)
        {
            ID3D11Texture2D existingTexture = new ID3D11Texture2D((IntPtr)nativeTexture);

            return(new D3D11Texture(existingTexture, description.Type, description.Format));
        }
Пример #19
0
 internal D3D11Texture2D(ID3D11Texture2D texture2D)
 {
     this.texture2D = texture2D;
 }
Пример #20
0
        private unsafe void SaveScreenshot(string path, ContainerFormat format = ContainerFormat.Jpeg)
        {
            var             d3d11GraphicsDevice = ((D3D11GraphicsDevice)_graphicsDevice !);
            ID3D11Texture2D source = Headless ? d3d11GraphicsDevice !.OffscreenTexture : d3d11GraphicsDevice !.BackBufferTexture;

            path = Path.Combine(AppContext.BaseDirectory, path);

            using (ID3D11Texture2D staging = d3d11GraphicsDevice !.CaptureTexture(source))
            {
                staging.DebugName = "STAGING";

                var textureDesc = staging !.Description;

                // Determine source format's WIC equivalent
                Guid pfGuid = default;
                bool sRGB   = false;
                switch (textureDesc.Format)
                {
                case Format.R32G32B32A32_Float:
                    pfGuid = WICPixelFormat.Format128bppRGBAFloat;
                    break;

                case Format.R16G16B16A16_Float:
                    pfGuid = WICPixelFormat.Format64bppRGBAHalf;
                    break;

                case Format.R16G16B16A16_UNorm:
                    pfGuid = WICPixelFormat.Format64bppRGBA;
                    break;

                // DXGI 1.1
                case Format.R10G10B10_Xr_Bias_A2_UNorm:
                    pfGuid = WICPixelFormat.Format32bppRGBA1010102XR;
                    break;

                case Format.R10G10B10A2_UNorm:
                    pfGuid = WICPixelFormat.Format32bppRGBA1010102;
                    break;

                case Format.B5G5R5A1_UNorm:
                    pfGuid = WICPixelFormat.Format16bppBGRA5551;
                    break;

                case Format.B5G6R5_UNorm:
                    pfGuid = WICPixelFormat.Format16bppBGR565;
                    break;

                case Format.R32_Float:
                    pfGuid = WICPixelFormat.Format32bppGrayFloat;
                    break;

                case Format.R16_Float:
                    pfGuid = WICPixelFormat.Format16bppGrayHalf;
                    break;

                case Format.R16_UNorm:
                    pfGuid = WICPixelFormat.Format16bppGray;
                    break;

                case Format.R8_UNorm:
                    pfGuid = WICPixelFormat.Format8bppGray;
                    break;

                case Format.A8_UNorm:
                    pfGuid = WICPixelFormat.Format8bppAlpha;
                    break;

                case Format.R8G8B8A8_UNorm:
                    pfGuid = WICPixelFormat.Format32bppRGBA;
                    break;

                case Format.R8G8B8A8_UNorm_SRgb:
                    pfGuid = WICPixelFormat.Format32bppRGBA;
                    sRGB   = true;
                    break;

                case Format.B8G8R8A8_UNorm:     // DXGI 1.1
                    pfGuid = WICPixelFormat.Format32bppBGRA;
                    break;

                case Format.B8G8R8A8_UNorm_SRgb:     // DXGI 1.1
                    pfGuid = WICPixelFormat.Format32bppBGRA;
                    sRGB   = true;
                    break;

                case Format.B8G8R8X8_UNorm:     // DXGI 1.1
                    pfGuid = WICPixelFormat.Format32bppBGR;
                    break;

                case Format.B8G8R8X8_UNorm_SRgb:     // DXGI 1.1
                    pfGuid = WICPixelFormat.Format32bppBGR;
                    sRGB   = true;
                    break;

                default:
                    Console.WriteLine($"ERROR: ScreenGrab does not support all DXGI formats ({textureDesc.Format})");
                    return;
                }

                using var wicFactory = new IWICImagingFactory2();
                //using IWICBitmapDecoder decoder = wicFactory.CreateDecoderFromFileName(path);

                //using Stream stream = File.OpenWrite(path);
                //using IWICStream wicStream = wicFactory.CreateStream(stream);
                using IWICStream wicStream      = wicFactory.CreateStream(path, FileAccess.Write);
                using IWICBitmapEncoder encoder = wicFactory.CreateEncoder(format, wicStream);
                // Create a Frame encoder
                using IWICBitmapFrameEncode frame = encoder.CreateNewFrame(out SharpGen.Runtime.Win32.IPropertyBag2? props);
                frame.Initialize(props);
                frame.SetSize(textureDesc.Width, textureDesc.Height);
                frame.SetResolution(72, 72);

                // Screenshots don't typically include the alpha channel of the render target
                Guid targetGuid;
                switch (textureDesc.Format)
                {
                case Format.R32G32B32A32_Float:
                case Format.R16G16B16A16_Float:
                    //if (IsWIC2())
                {
                    targetGuid = WICPixelFormat.Format96bppRGBFloat;
                }
                    //else
                    //{
                    //    targetGuid = WICPixelFormat.Format24bppBGR;
                    //}
                    break;

                case Format.R16G16B16A16_UNorm:
                    targetGuid = WICPixelFormat.Format48bppBGR;
                    break;

                case Format.B5G5R5A1_UNorm:
                    targetGuid = WICPixelFormat.Format16bppBGR555;
                    break;

                case Format.B5G6R5_UNorm:
                    targetGuid = WICPixelFormat.Format16bppBGR565;
                    break;

                case Format.R32_Float:
                case Format.R16_Float:
                case Format.R16_UNorm:
                case Format.R8_UNorm:
                case Format.A8_UNorm:
                    targetGuid = WICPixelFormat.Format8bppGray;
                    break;

                default:
                    targetGuid = WICPixelFormat.Format24bppBGR;
                    break;
                }
                frame.SetPixelFormat(targetGuid);

                ID3D11DeviceContext1 context = d3d11GraphicsDevice !.DeviceContext;

                const bool native = false;
                if (native)
                {
                    MappedSubresource mappedSubresource = context.Map(staging, 0, MapMode.Read);
                    int imageSize = mappedSubresource.RowPitch * textureDesc.Height;
                    if (targetGuid != pfGuid)
                    {
                        // Conversion required to write
                        using (IWICBitmap bitmapSource = wicFactory.CreateBitmapFromMemory(
                                   textureDesc.Width,
                                   textureDesc.Height,
                                   pfGuid,
                                   mappedSubresource.RowPitch,
                                   imageSize,
                                   mappedSubresource.DataPointer))
                        {
                            using (IWICFormatConverter formatConverter = wicFactory.CreateFormatConverter())
                            {
                                if (!formatConverter.CanConvert(pfGuid, targetGuid))
                                {
                                    context.Unmap(staging, 0);
                                    return;
                                }

                                formatConverter.Initialize(bitmapSource, targetGuid, BitmapDitherType.None, null, 0, BitmapPaletteType.MedianCut);
                                frame.WriteSource(formatConverter, new RectI(textureDesc.Width, textureDesc.Height));
                            }
                        }
                    }
                    else
                    {
                        // No conversion required
                        frame.WritePixels(textureDesc.Height, mappedSubresource.RowPitch, imageSize, mappedSubresource.DataPointer);
                    }
                }
                else
                {
                    int stride = WICPixelFormat.GetStride(pfGuid, textureDesc.Width);
                    ReadOnlySpan <Color> colors = context.MapReadOnly <Color>(staging);

                    if (targetGuid != pfGuid)
                    {
                        // Conversion required to write
                        using (IWICBitmap bitmapSource = wicFactory.CreateBitmapFromMemory(
                                   textureDesc.Width,
                                   textureDesc.Height,
                                   pfGuid,
                                   colors,
                                   stride))
                        {
                            using (IWICFormatConverter formatConverter = wicFactory.CreateFormatConverter())
                            {
                                if (!formatConverter.CanConvert(pfGuid, targetGuid))
                                {
                                    context.Unmap(staging, 0);
                                    return;
                                }

                                formatConverter.Initialize(bitmapSource, targetGuid, BitmapDitherType.None, null, 0, BitmapPaletteType.MedianCut);
                                frame.WriteSource(formatConverter, new RectI(textureDesc.Width, textureDesc.Height));
                            }
                        }
                    }
                    else
                    {
                        // No conversion required
                        frame.WritePixels(textureDesc.Height, stride, colors);
                    }
                }

                context.Unmap(staging, 0);
                frame.Commit();
                encoder.Commit();
            }
        }
        public D3D11GraphicsDevice(bool validation, Window window)
        {
            Window = window;
            if (CreateDXGIFactory1(out Factory).Failure)
            {
                throw new InvalidOperationException("Cannot create IDXGIFactory1");
            }

            using (IDXGIAdapter1 adapter = GetHardwareAdapter())
            {
                DeviceCreationFlags creationFlags = DeviceCreationFlags.BgraSupport;
                if (validation && SdkLayersAvailable())
                {
                    creationFlags |= DeviceCreationFlags.Debug;
                }

                if (D3D11CreateDevice(
                        adapter,
                        DriverType.Unknown,
                        creationFlags,
                        s_featureLevels,
                        out ID3D11Device tempDevice, out FeatureLevel, out ID3D11DeviceContext tempContext).Failure)
                {
                    // If the initialization fails, fall back to the WARP device.
                    // For more information on WARP, see:
                    // http://go.microsoft.com/fwlink/?LinkId=286690
                    D3D11CreateDevice(
                        null,
                        DriverType.Warp,
                        creationFlags,
                        s_featureLevels,
                        out tempDevice, out FeatureLevel, out tempContext).CheckError();
                }

                Device        = tempDevice.QueryInterface <ID3D11Device1>();
                DeviceContext = tempContext.QueryInterface <ID3D11DeviceContext1>();
                tempContext.Dispose();
                tempDevice.Dispose();
            }

            IntPtr hwnd = window.Handle;

            SwapChainDescription1 swapChainDescription = new SwapChainDescription1()
            {
                Width             = window.Width,
                Height            = window.Height,
                Format            = Format.B8G8R8A8_UNorm,
                BufferCount       = FrameCount,
                Usage             = DXGI.Usage.RenderTargetOutput,
                SampleDescription = new SampleDescription(1, 0),
                Scaling           = Scaling.Stretch,
                SwapEffect        = SwapEffect.FlipDiscard,
                AlphaMode         = AlphaMode.Ignore
            };

            SwapChainFullscreenDescription fullscreenDescription = new SwapChainFullscreenDescription
            {
                Windowed = true
            };


            SwapChain = Factory.CreateSwapChainForHwnd(Device, hwnd, swapChainDescription, fullscreenDescription);
            Factory.MakeWindowAssociation(hwnd, WindowAssociationFlags.IgnoreAltEnter);

            BackBuffer       = SwapChain.GetBuffer <ID3D11Texture2D>(0);
            RenderTargetView = Device.CreateRenderTargetView(BackBuffer);
        }
Пример #22
0
        static void Main()
        {
            ReferenceTracker.TrackReferences = true;
            Form form = new Form();

            IDXGIFactory factory = DXGI.CreateFactory();
            IDXGIAdapter adapter = null;

            factory.EnumAdapters(0, out adapter);

            DXGI_SWAP_CHAIN_DESC swapChainDescription = new DXGI_SWAP_CHAIN_DESC
            {
                BufferCount = 1,
                BufferDesc  = new DXGI_MODE_DESC
                {
                    Format      = DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_UNORM,
                    Height      = form.ClientSize.Height,
                    RefreshRate = new DXGI_RATIONAL
                    {
                        Denominator = 1,
                        Numerator   = 60
                    },

                    Scaling          = DXGI_MODE_SCALING.DXGI_MODE_SCALING_UNSPECIFIED,
                    ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER.DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED,
                    Width            = form.ClientSize.Width
                },
                BufferUsage  = (int)DXGI_USAGE.DXGI_USAGE_RENDER_TARGET_OUTPUT,
                Flags        = 0,
                OutputWindow = form.Handle,
                SampleDesc   = new DXGI_SAMPLE_DESC
                {
                    Count   = 1,
                    Quality = 0
                },
                SwapEffect = DXGI_SWAP_EFFECT.DXGI_SWAP_EFFECT_DISCARD,
                Windowed   = true
            };

            ID3D11Device   device    = SlimDX.Direct3D11.Direct3D11.CreateDevice(adapter);
            IDXGISwapChain swapChain = null;

            factory.CreateSwapChain(device, swapChainDescription, out swapChain);

            ID3D11Texture2D        backbuffer = swapChain.GetBuffer <ID3D11Texture2D>(0);
            ID3D11RenderTargetView view       = null;

            device.CreateRenderTargetView(backbuffer, null, out view);

            ID3DBlob vertexShaderBytecode = ShaderCompiler.CompileFromString(File.ReadAllText("MiniTri11.fx"), "MiniTri11.fx", "VS", "vs_4_0");
            ID3DBlob pixelShaderBytecode  = ShaderCompiler.CompileFromString(File.ReadAllText("MiniTri11.fx"), "MiniTri11.fx", "PS", "ps_4_0");

            D3D11_INPUT_ELEMENT_DESC[] inputElements = new[] {
                new D3D11_INPUT_ELEMENT_DESC {
                    SemanticName = "POSITION", AlignedByteOffset = 0, SemanticIndex = 0, Format = DXGI_FORMAT.DXGI_FORMAT_R32G32B32A32_FLOAT, InstanceDataStepRate = 0, InputSlot = 0, InputSlotClass = D3D11_INPUT_CLASSIFICATION.D3D11_INPUT_PER_VERTEX_DATA
                },
                new D3D11_INPUT_ELEMENT_DESC {
                    SemanticName = "COLOR", AlignedByteOffset = 16, SemanticIndex = 0, Format = DXGI_FORMAT.DXGI_FORMAT_R32G32B32A32_FLOAT, InstanceDataStepRate = 0, InputSlot = 0, InputSlotClass = D3D11_INPUT_CLASSIFICATION.D3D11_INPUT_PER_VERTEX_DATA
                }
            };

            ID3DBlob inputSignature;

            ShaderCompiler.D3DGetInputSignatureBlob(vertexShaderBytecode.GetBufferPointer(), vertexShaderBytecode.GetBufferSize(), out inputSignature);
            ID3D11InputLayout inputLayout;

            device.CreateInputLayout(inputElements, inputElements.Length, inputSignature.GetBufferPointer(), inputSignature.GetBufferSize(), out inputLayout);

            ByteBuffer vertexData = new ByteBuffer(3 * 32);

            vertexData.Write(0 * Vector4.SizeInBytes, new Vector4(0.0f, 0.5f, 0.5f, 1.0f));
            vertexData.Write(1 * Vector4.SizeInBytes, new Vector4(1.0f, 0.0f, 0.0f, 1.0f));
            vertexData.Write(2 * Vector4.SizeInBytes, new Vector4(0.5f, -0.5f, 0.5f, 1.0f));
            vertexData.Write(3 * Vector4.SizeInBytes, new Vector4(0.0f, 1.0f, 0.0f, 1.0f));
            vertexData.Write(4 * Vector4.SizeInBytes, new Vector4(-0.5f, -0.5f, 0.5f, 1.0f));
            vertexData.Write(5 * Vector4.SizeInBytes, new Vector4(0.0f, 0.0f, 1.0f, 1.0f));

            D3D11_BUFFER_DESC vertexBufferDescription = new D3D11_BUFFER_DESC
            {
                BindFlags           = 1,      //vertex buffer
                ByteWidth           = 3 * 32,
                CPUAccessFlags      = 0,
                MiscFlags           = 0,
                Usage               = D3D11_USAGE.D3D11_USAGE_DEFAULT,
                StructureByteStride = 0
            };
            ID3D11Buffer           vertexBuffer;
            D3D11_SUBRESOURCE_DATA srd = new D3D11_SUBRESOURCE_DATA
            {
                pSysMem          = vertexData.Pin(),
                SysMemPitch      = 0,
                SysMemSlicePitch = 0
            };

            device.CreateBuffer(vertexBufferDescription, srd, out vertexBuffer);
            vertexData.Unpin();

            RenderLoop          loop    = new RenderLoop();
            ID3D11DeviceContext context = null;

            device.GetImmediateContext(out context);

            ID3D11VertexShader vertexShader;
            ID3D11PixelShader  pixelShader;

            device.CreateVertexShader(vertexShaderBytecode.GetBufferPointer(), vertexShaderBytecode.GetBufferSize(), null, out vertexShader);
            device.CreatePixelShader(pixelShaderBytecode.GetBufferPointer(), pixelShaderBytecode.GetBufferSize(), null, out pixelShader);
            context.IASetInputLayout(inputLayout);
            context.VSSetShader(vertexShader, null, 0);
            context.PSSetShader(pixelShader, null, 0);
            context.IASetPrimitiveTopology(4);            //triangle list
            context.IASetVertexBuffers(0, 1, new ID3D11Buffer[] { vertexBuffer }, new int[] { 32 }, new int[] { 0 });
            context.OMSetRenderTargets(1, new ID3D11RenderTargetView[] { view }, IntPtr.Zero);

            D3D11_VIEWPORT vp = new D3D11_VIEWPORT {
                Height   = form.ClientSize.Height,
                Width    = form.ClientSize.Width,
                TopLeftX = 0,
                TopLeftY = 0,
                MinDepth = 0.0f,
                MaxDepth = 1.0f
            };

            context.RSSetViewports(1, new D3D11_VIEWPORT [] { vp });

            loop.Run(form, () =>
            {
                var clearColor = new SlimDX.Color4 {
                    R = 0.0f, G = 0.0f, B = 0.0f, A = 1.0f
                };
                context.ClearRenderTargetView(view, clearColor);
                context.Draw(3, 0);
                swapChain.Present(0, 0);
            });

            view.ReleaseReference();
            backbuffer.ReleaseReference();
            swapChain.ReleaseReference();
            device.ReleaseReference();
            adapter.ReleaseReference();
            factory.ReleaseReference();
        }