public override void EnableLayerBrush()
        {
            factory = DXGI.CreateDXGIFactory1 <IDXGIFactory1>();

            StartDesktopDuplicator(0, 0);
            Thread.Sleep(100);
        }
Example #2
0
        public void ValidateDevice()
        {
            DXGI_ADAPTER_DESC previousDesc;
            {
                using ComPtr <IDXGIAdapter1> previousDefaultAdapter = null;
                DirectXHelper.ThrowIfFailed(_dxgiFactory.Ptr->EnumAdapters1(0, previousDefaultAdapter.GetAddressOf()));
                DirectXHelper.ThrowIfFailed(previousDefaultAdapter.Ptr->GetDesc(&previousDesc));
            }

            {
                using ComPtr <IDXGIFactory4> currrentDxgiFactory   = null;
                using ComPtr <IDXGIAdapter1> currentDefaultAdapter = null;

                Guid iid = DXGI.IID_IDXGIFactory4;
                DirectXHelper.ThrowIfFailed(DXGI.CreateDXGIFactory1(&iid, (void **)currrentDxgiFactory.GetAddressOf()));


                DirectXHelper.ThrowIfFailed(currrentDxgiFactory.Ptr->EnumAdapters1(0, currentDefaultAdapter.GetAddressOf()));

                DXGI_ADAPTER_DESC currentDesc;
                DirectXHelper.ThrowIfFailed(currentDefaultAdapter.Ptr->GetDesc(&currentDesc));

                if (previousDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart ||
                    previousDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart ||
                    FAILED(_d3dDevice.Ptr->GetDeviceRemovedReason()))
                {
                    _deviceRemoved = true;
                }
            }
        }
Example #3
0
        private DeviceResources GetDeviceResources()
        {
            if (_deviceResources != null && _deviceResources.IsDeviceRemoved)
            {
                // All references to the existing D3D device must be released before a new device
                // can be created.

                _deviceResources = null;
                _main.OnDeviceRemoved();

#if DEBUG
                ComPtr <IDXGIDebug1> dxgiDebug = default;
                Guid iid = DXGIDebug.IID_IDXGIDebug1;
                if (TerraFX.Interop.Windows.SUCCEEDED(DXGI.DXGIGetDebugInterface1(0, &iid, (void **)dxgiDebug.GetAddressOf())))
                {
                    dxgiDebug.Ptr->ReportLiveObjects(new Guid(0xe48ae283, 0xda80, 0x490b, 0x87, 0xe6, 0x43, 0xe9, 0xa9, 0xcf, 0xda, 0x8),
                                                     DXGI_DEBUG_RLO_FLAGS.DXGI_DEBUG_RLO_SUMMARY | DXGI_DEBUG_RLO_FLAGS.DXGI_DEBUG_RLO_IGNORE_INTERNAL);
                }
#endif
            }

            if (_deviceResources == null)
            {
                _deviceResources = new DeviceResources();
                _deviceResources.SetWindow(CoreWindow.GetForCurrentThread());
                _main.CreateRenderers(_deviceResources);
            }
            return(_deviceResources);
        }
Example #4
0
 protected DX12Sample(string name) : base(name)
 {
     _renderTargets        = new ID3D12Resource *[2];
     _commandAllocators    = new ID3D12CommandAllocator *[2];
     _fenceValues          = new ulong[2];
     _graphicsCommandLists = new ID3D12GraphicsCommandList *[2];
     _d3d12 = Silk.NET.Direct3D12.D3D12.GetApi();
     _dxgi  = DXGI.GetApi();
 }
Example #5
0
        public void Initialize()
        {
#if DEBUG
            if (D3D12.D3D12GetDebugInterface <ID3D12Debug>(out var pDx12Debug).Success)
            {
                pDx12Debug.EnableDebugLayer();
            }
#endif
            ThrowIfFailed(DXGI.CreateDXGIFactory1(out dxgiFactory));
            int index1 = 0;
            while (true)
            {
                var hr = dxgiFactory.EnumAdapterByGpuPreference(index1, GpuPreference.HighPerformance, out adapter);
                if (hr == SharpGen.Runtime.Result.Ok)
                {
                    break;
                }
                index1++;
            }
            ThrowIfFailed(D3D12.D3D12CreateDevice(this.adapter, out device));
            CommandQueueDescription description;
            description.Flags    = CommandQueueFlags.None;
            description.Type     = CommandListType.Direct;
            description.NodeMask = 0;
            description.Priority = 0;
            ThrowIfFailed(device.CreateCommandQueue(description, out commandQueue));
            DescriptorHeapDescription descriptorHeapDescription;
            descriptorHeapDescription.DescriptorCount = CBVSRVUAVDescriptorCount;
            descriptorHeapDescription.Type            = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView;
            descriptorHeapDescription.Flags           = DescriptorHeapFlags.ShaderVisible;
            descriptorHeapDescription.NodeMask        = 0;
            ThrowIfFailed(device.CreateDescriptorHeap(descriptorHeapDescription, out cbvsrvuavHeap));

            descriptorHeapDescription.DescriptorCount = 16;
            descriptorHeapDescription.Type            = DescriptorHeapType.DepthStencilView;
            descriptorHeapDescription.Flags           = DescriptorHeapFlags.None;
            ThrowIfFailed(device.CreateDescriptorHeap(descriptorHeapDescription, out dsvHeap));

            descriptorHeapDescription.DescriptorCount = 16;
            descriptorHeapDescription.Type            = DescriptorHeapType.RenderTargetView;
            descriptorHeapDescription.Flags           = DescriptorHeapFlags.None;
            ThrowIfFailed(device.CreateDescriptorHeap(descriptorHeapDescription, out rtvHeap));
            waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);

            cbvsrvuavHeapIncrementSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
            dsvHeapIncrementSize       = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.DepthStencilView);
            rtvHeapIncrementSize       = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);
            commandAllocators          = new List <ID3D12CommandAllocator>();
            for (int i = 0; i < bufferCount; i++)
            {
                ThrowIfFailed(device.CreateCommandAllocator(CommandListType.Direct, out ID3D12CommandAllocator commandAllocator));
                commandAllocators.Add(commandAllocator);
            }
            ThrowIfFailed(device.CreateFence(executeCount, FenceFlags.None, out fence));
            executeCount++;
        }
 public static ResourceDescription Texture1D(DXGI.Format format,
     long width,
     short arraySize = 1,
     short mipLevels = 0,
     ResourceFlags flags = ResourceFlags.None,
     TextureLayout layout = TextureLayout.Unknown,
     long alignment = 0)
 {
     return new ResourceDescription(ResourceDimension.Texture1D, alignment, width, 1, arraySize, mipLevels, format, 1, 0, layout, flags);
 }
 public static ResourceDescription Texture3D(DXGI.Format format,
     long width,
     int height,
     short depth,
     short mipLevels = 0,
     ResourceFlags flags = ResourceFlags.None,
     TextureLayout layout = TextureLayout.Unknown,
     long alignment = 0)
 {
     return new ResourceDescription(ResourceDimension.Texture3D, alignment, width, height, depth, mipLevels, format, 1, 0, layout, flags);
 }
 public static ResourceDescription Texture2D(DXGI.Format format,
     long width,
     int height,
     short arraySize = 1,
     short mipLevels = 0,
     int sampleCount = 1,
     int sampleQuality = 0,
     ResourceFlags flags = ResourceFlags.None,
     TextureLayout layout = TextureLayout.Unknown,
     long alignment = 0)
 {
     return new ResourceDescription(ResourceDimension.Texture2D, alignment, width, height, arraySize, mipLevels, format, sampleCount, sampleQuality, layout, flags);
 }
        public static Bitmap CaptureScreenFrames(int screenId)
        {
            var factory = DXGI.CreateDXGIFactory1 <IDXGIFactory1>();
            var adapter = factory.GetAdapter(0);
            var output  = adapter.GetOutput(screenId);
            var output1 = output.QueryInterface <IDXGIOutput1>();

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

            var bounds      = output1.Description.DesktopCoordinates;
            var textureDesc = new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = bounds.Right - bounds.Left,
                Height            = bounds.Bottom - bounds.Top,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = Vortice.Direct3D11.Usage.Staging
            };

            var duplication  = output1.DuplicateOutput(device);
            var currentFrame = device.CreateTexture2D(textureDesc);

            Thread.Sleep(100);

            duplication.AcquireNextFrame(500, out var frameInfo, out var desktopResource);

            var tempTexture = desktopResource.QueryInterface <ID3D11Texture2D>();

            device.ImmediateContext.CopyResource(currentFrame, tempTexture);

            var dataBox = device.ImmediateContext.Map(currentFrame, 0, MapMode.Read, Vortice.Direct3D11.MapFlags.None);

            var frame   = new Bitmap(1920, 1080, PixelFormat.Format32bppRgb);
            var mapDest = frame.LockBits(new Rectangle(0, 0, 1920, 1080), ImageLockMode.WriteOnly, frame.PixelFormat);

            for (int y = 0, sizeInBytesToCopy = 1920 * 4; y < 1080; y++)
            {
                MemoryHelpers.CopyMemory(mapDest.Scan0 + y * mapDest.Stride, dataBox.DataPointer + y * dataBox.RowPitch, sizeInBytesToCopy);
            }
            frame.UnlockBits(mapDest);

            return(frame);
        }
Example #10
0
        private void InitDXR(IntPtr winHandle, int winWidth, int winHeight)
        {
            mHwnd = winHandle;
            this.mSwapChainRect = new Rect(0, 0, winWidth, winHeight);

            // Initialize the debug layer for debug builds
#if DEBUG
            if (D3D12.D3D12GetDebugInterface <ID3D12Debug>(out var pDx12Debug).Success)
            {
                pDx12Debug.EnableDebugLayer();
            }
#endif
            // Create the DXGI factory
            IDXGIFactory4 pDXGIFactory;
            DXGI.CreateDXGIFactory1 <IDXGIFactory4>(out pDXGIFactory);
            mpDevice    = this.context.CreateDevice(pDXGIFactory);
            mpCmdQueue  = this.context.CreateCommandQueue(mpDevice);
            mpSwapChain = this.context.CreateDXGISwapChain(pDXGIFactory, mHwnd, winWidth, winHeight, Format.R8G8B8A8_UNorm, mpCmdQueue);

            // Create a RTV descriptor heap
            mRtvHeap.Heap = this.context.CreateDescriptorHeap(mpDevice, kRtvHeapSize, DescriptorHeapType.RenderTargetView, false);

            // Create the per-frame objects
            this.mFrameObjects = new FrameObject[this.context.kDefaultSwapChainBuffers];
            for (int i = 0; i < this.context.kDefaultSwapChainBuffers; i++)
            {
                mFrameObjects[i].pCmdAllocator    = mpDevice.CreateCommandAllocator(CommandListType.Direct);
                mFrameObjects[i].pSwapChainBuffer = mpSwapChain.GetBuffer <ID3D12Resource>(i);
                mFrameObjects[i].rtvHandle        = context.CreateRTV(mpDevice, mFrameObjects[i].pSwapChainBuffer, mRtvHeap.Heap, ref mRtvHeap.usedEntries, Format.R8G8B8A8_UNorm_SRgb);
            }

            // Create the command-list
            var cmdList = mpDevice.CreateCommandList(0, CommandListType.Direct, mFrameObjects[0].pCmdAllocator, null);
            this.mpCmdList = cmdList.QueryInterface <ID3D12GraphicsCommandList4>();

            // Create a fence and the event
            this.mpFence     = mpDevice.CreateFence(0, FenceFlags.None);
            this.mFenceEvent = new EventWaitHandle(false, EventResetMode.AutoReset);
        }
        private static IDXGISwapChain3 CreateSwapChain(GraphicsDevice device, PresentationParameters presentationParameters, IntPtr windowHandle)
        {
            SwapChainDescription1 swapChainDescription = new SwapChainDescription1
            {
                Width             = presentationParameters.BackBufferWidth,
                Height            = presentationParameters.BackBufferHeight,
                SampleDescription = new SampleDescription(1, 0),
                Stereo            = presentationParameters.Stereo,
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = BufferCount,
                Scaling           = Scaling.Stretch,
                SwapEffect        = SwapEffect.FlipSequential,
                Format            = (Format)presentationParameters.BackBufferFormat,
                Flags             = SwapChainFlags.None,
                AlphaMode         = AlphaMode.Unspecified
            };

            DXGI.CreateDXGIFactory2(false, out IDXGIFactory2 factory);
            using IDXGISwapChain1 tempSwapChain = factory.CreateSwapChainForHwnd(device.NativeDirectCommandQueue, windowHandle, swapChainDescription);
            factory.Dispose();

            return(tempSwapChain.QueryInterface <IDXGISwapChain3>());
        }
Example #12
0
        private static IDXGISwapChain3 CreateSwapChain(GraphicsDevice device, PresentationParameters presentationParameters, SwapChainPanel swapChainPanel)
        {
            SwapChainDescription1 swapChainDescription = new SwapChainDescription1
            {
                Width             = presentationParameters.BackBufferWidth,
                Height            = presentationParameters.BackBufferHeight,
                SampleDescription = new Vortice.DXGI.SampleDescription(1, 0),
                Stereo            = presentationParameters.Stereo,
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = BufferCount,
                Scaling           = Scaling.Stretch,
                SwapEffect        = SwapEffect.FlipSequential,
                Format            = (Format)presentationParameters.BackBufferFormat.ToNonSRgb(),
                Flags             = SwapChainFlags.None,
                AlphaMode         = AlphaMode.Unspecified
            };

            swapChainDescription.AlphaMode = AlphaMode.Premultiplied;

            DXGI.CreateDXGIFactory2(false, out IDXGIFactory2 factory);
            Direct3DInterop.ISwapChainPanelNative nativePanel = (Direct3DInterop.ISwapChainPanelNative)swapChainPanel;
            using IDXGISwapChain1 tempSwapChain = factory.CreateSwapChainForComposition(device.DirectCommandQueue.NativeCommandQueue, swapChainDescription);
            factory.Dispose();

            IDXGISwapChain3 swapChain = tempSwapChain.QueryInterface <IDXGISwapChain3>();

            nativePanel.SetSwapChain(swapChain.NativePointer);

            swapChain.MatrixTransform = new Matrix3x2
            {
                M11 = 1.0f / swapChainPanel.CompositionScaleX,
                M22 = 1.0f / swapChainPanel.CompositionScaleY
            };

            return(swapChain);
        }
Example #13
0
        /// <summary>
        /// Hooked to allow resizing a texture/surface that is reused. Currently not in use as we create the texture for each request
        /// to support different sizes each time (as we use DirectX to copy only the region we are after rather than the entire backbuffer)
        /// </summary>
        /// <param name="swapChainPtr"></param>
        /// <param name="newTargetParameters"></param>
        /// <returns></returns>
        int ResizeTargetHook(IntPtr swapChainPtr, ref DXGI.DXGI_MODE_DESC newTargetParameters)
        {
            if (swapChainPtr != _swapChainPointer)
            {
                _swapChain = SlimDX.DXGI.SwapChain.FromPointer(swapChainPtr);
            }
            SwapChain swapChain = _swapChain;
			//using (SlimDX.DXGI.SwapChain swapChain = SlimDX.DXGI.SwapChain.FromPointer(swapChainPtr))
            {
                // This version creates a new texture for each request so there is nothing to resize.
                // IF the size of the texture is known each time, we could create it once, and then possibly need to resize it here

                return swapChain.ResizeTarget(
                    new SlimDX.DXGI.ModeDescription()
                    {
                        Format = newTargetParameters.Format,
                        Height = newTargetParameters.Height,
                        RefreshRate = newTargetParameters.RefreshRate,
                        Scaling = newTargetParameters.Scaling,
                        ScanlineOrdering = newTargetParameters.ScanlineOrdering,
                        Width = newTargetParameters.Width
                    }
                ).Code;
            }
        }
Example #14
0
        private static DepthFormat ComputeViewFormat(DXGI.Format format)
        {
            switch (format)
            {
                case SharpDX.DXGI.Format.D16_UNorm:
                case DXGI.Format.R16_Float:
                case DXGI.Format.R16_Typeless:
                    return DepthFormat.Depth16;

                case SharpDX.DXGI.Format.D32_Float:
                case DXGI.Format.R32_Float:
                case DXGI.Format.R32_Typeless:
                    return DepthFormat.Depth32;

                case SharpDX.DXGI.Format.D24_UNorm_S8_UInt:
                case SharpDX.DXGI.Format.R24_UNorm_X8_Typeless:
                    return DepthFormat.Depth24Stencil8;

                case SharpDX.DXGI.Format.D32_Float_S8X24_UInt:
                case SharpDX.DXGI.Format.R32_Float_X8X24_Typeless:
                    return DepthFormat.Depth32Stencil8X24;
            }
            throw new InvalidOperationException(string.Format("Unsupported DXGI.FORMAT [{0}] for depth buffer", format));
        }
Example #15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ImageSource"/>.
 /// </summary>
 public ImageSource(DeviceContext2 context2, DXGI.Surface[] surfaces, int surfaceCount, DXGI.ColorSpaceType colorSpace, ImageSourceFromDxgiOptions options)
     : this(IntPtr.Zero)
 {
     context2.CreateImageSourceFromDxgi(surfaces, surfaceCount, colorSpace, options, this);
 }
Example #16
0
		/// <summary>	
		/// Creates a new device object that can be used to create other Microsoft DirectComposition objects.
		/// </summary>	
		/// <param name="device">The DXGI device to use to create DirectComposition surface objects.</param>
		public Device(DXGI.Device device)
		{
			IntPtr temp;
			DComp.CreateDevice(device, Utilities.GetGuidFromType(typeof(Device)), out temp);
			NativePointer = temp;
		}
        public static SystemParameters Create()
        {
            var(width, height, _) = GetDisplays().First(d => d.IsPrimary);

            /*using var f = new SharpDX.DXGI.Factory1();
             * var video_memory = f.Adapters1.Select(a =>
             *  Math.Max(a.Description.DedicatedSystemMemory, (long)a.Description.DedicatedVideoMemory)).Max();*/

            var dxgiMemory = 0UL;

            unsafe
            {
                using var api = DXGI.GetApi();

                IDXGIFactory1 *factory1 = default;

                try
                {
                    //https://docs.microsoft.com/en-us/windows/win32/api/dxgi/nf-dxgi-createdxgifactory1
                    SilkMarshal.ThrowHResult(api.CreateDXGIFactory1(SilkMarshal.GuidPtrOf <IDXGIFactory1>(), (void **)&factory1));

                    uint i = 0u;
                    while (true)
                    {
                        IDXGIAdapter1 *adapter1 = default;

                        //https://docs.microsoft.com/en-us/windows/win32/api/dxgi/nf-dxgi-idxgifactory1-enumadapters1
                        var res = factory1->EnumAdapters1(i, &adapter1);

                        var exception = Marshal.GetExceptionForHR(res);
                        if (exception != null)
                        {
                            break;
                        }

                        AdapterDesc1 adapterDesc = default;

                        //https://docs.microsoft.com/en-us/windows/win32/api/dxgi/nf-dxgi-idxgiadapter1-getdesc1
                        SilkMarshal.ThrowHResult(adapter1->GetDesc1(&adapterDesc));

                        var systemMemory = (ulong)adapterDesc.DedicatedSystemMemory;
                        var videoMemory  = (ulong)adapterDesc.DedicatedVideoMemory;

                        var maxMemory = Math.Max(systemMemory, videoMemory);
                        if (maxMemory > dxgiMemory)
                        {
                            dxgiMemory = maxMemory;
                        }

                        adapter1->Release();
                        i++;
                    }
                }
                catch (Exception e)
                {
                    Utils.ErrorThrow(e);
                }
                finally
                {
                    if (factory1->LpVtbl != (void **)IntPtr.Zero)
                    {
                        factory1->Release();
                    }
                }
            }

            var memory = Utils.GetMemoryStatus();

            return(new SystemParameters
            {
                ScreenWidth = width,
                ScreenHeight = height,
                VideoMemorySize = (long)dxgiMemory,
                SystemMemorySize = (long)memory.ullTotalPhys,
                SystemPageSize = (long)memory.ullTotalPageFile - (long)memory.ullTotalPhys
            });
        }
Example #18
0
        /// <summary>
        /// Hooked to allow resizing a texture/surface that is reused. Currently not in use as we create the texture for each request
        /// to support different sizes each time (as we use DirectX to copy only the region we are after rather than the entire backbuffer)
        /// </summary>
        /// <param name="swapChainPtr"></param>
        /// <param name="newTargetParameters"></param>
        /// <returns></returns>
        int ResizeTargetHook(IntPtr swapChainPtr, ref DXGI.DXGI_MODE_DESC newTargetParameters)
        {
            DebugMessage("ResizeTarget");
            try
            {
                if (_swapChain == null)
                {
                    _swapChain = SlimDX.DXGI.SwapChain.FromPointer(swapChainPtr);
                }
                SwapChain swapChain = _swapChain;
                //using (SlimDX.DXGI.SwapChain swapChain = SlimDX.DXGI.SwapChain.FromPointer(swapChainPtr))
                {
                    // This version creates a new texture for each request so there is nothing to resize.
                    // IF the size of the texture is known each time, we could create it once, and then possibly need to resize it here

                    return swapChain.ResizeTarget(
                        new SlimDX.DXGI.ModeDescription()
                        {
                            Format = newTargetParameters.Format,
                            Height = newTargetParameters.Height,
                            RefreshRate = newTargetParameters.RefreshRate,
                            Scaling = newTargetParameters.Scaling,
                            ScanlineOrdering = newTargetParameters.ScanlineOrdering,
                            Width = newTargetParameters.Width
                        }
                    ).Code;
                }
            }
            catch (Exception ex)
            {
                DebugMessage(ex.ToString());
                return System.Runtime.InteropServices.Marshal.GetHRForException(ex);
            }
            
        }
Example #19
0
        /// <summary>
        /// Converts an image row with optional clearing of alpha value to 1.0
        /// </summary>
        /// <param name="pDestination"></param>
        /// <param name="outSize"></param>
        /// <param name="pSource"></param>
        /// <param name="inSize"></param>
        /// <param name="inFormat"></param>
        /// <param name="flags"></param>
        private unsafe static void ExpandScanline(IntPtr pDestination, int outSize, IntPtr pSource, int inSize, DXGI.Format inFormat, ScanlineFlags flags)
        {
            switch (inFormat)
            {
                case DXGI.Format.B5G6R5_UNorm:
                    // DXGI.Format.B5G6R5_UNorm -> DXGI.Format.R8G8B8A8_UNorm
                    {
                        var sPtr = (ushort*) (pSource);
                        var dPtr = (uint*) (pDestination);

                        for (uint ocount = 0, icount = 0; ((icount < inSize) && (ocount < outSize)); icount += 2, ocount += 4)
                        {
                            ushort t = *(sPtr++);

                            uint t1 = (uint) (((t & 0xf800) >> 8) | ((t & 0xe000) >> 13));
                            uint t2 = (uint) (((t & 0x07e0) << 5) | ((t & 0x0600) >> 5));
                            uint t3 = (uint) (((t & 0x001f) << 19) | ((t & 0x001c) << 14));

                            *(dPtr++) = t1 | t2 | t3 | 0xff000000;
                        }
                    }
                    break;

                case DXGI.Format.B5G5R5A1_UNorm:
                    // DXGI.Format.B5G5R5A1_UNorm -> DXGI.Format.R8G8B8A8_UNorm
                    {
                        var sPtr = (ushort*) (pSource);
                        var dPtr = (uint*) (pDestination);

                        for (uint ocount = 0, icount = 0; ((icount < inSize) && (ocount < outSize)); icount += 2, ocount += 4)
                        {
                            ushort t = *(sPtr++);

                            uint t1 = (uint) (((t & 0x7c00) >> 7) | ((t & 0x7000) >> 12));
                            uint t2 = (uint) (((t & 0x03e0) << 6) | ((t & 0x0380) << 1));
                            uint t3 = (uint) (((t & 0x001f) << 19) | ((t & 0x001c) << 14));
                            uint ta = (uint) ((flags & ScanlineFlags.SetAlpha) != 0 ? 0xff000000 : (((t & 0x8000) != 0 ? 0xff000000 : 0)));

                            *(dPtr++) = t1 | t2 | t3 | ta;
                        }
                    }
                    break;

#if DIRECTX11_1
                case DXGI.Format.B4G4R4A4_UNorm:
                    // DXGI.Format.B4G4R4A4_UNorm -> DXGI.Format.R8G8B8A8_UNorm
                    {
                        var sPtr = (ushort*) (pSource);
                        var dPtr = (uint*) (pDestination);

                        for (uint ocount = 0, icount = 0; ((icount < inSize) && (ocount < outSize)); icount += 2, ocount += 4)
                        {
                            ushort t = *(sPtr++);

                            uint t1 = (uint) (((t & 0x0f00) >> 4) | ((t & 0x0f00) >> 8));
                            uint t2 = (uint) (((t & 0x00f0) << 8) | ((t & 0x00f0) << 4));
                            uint t3 = (uint) (((t & 0x000f) << 20) | ((t & 0x000f) << 16));
                            uint ta = (flags & ScanlineFlags.SetAlpha) != 0 ? 0xff000000 : (uint) ((((t & 0xf000) << 16) | ((t & 0xf000) << 12)));

                            *(dPtr++) = t1 | t2 | t3 | ta;
                        }
                    }
                    break;
#endif
// DXGI_1_2_FORMATS
            }
        }
Example #20
0
        /// <summary>
        // Converts an image row with optional clearing of alpha value to 1.0
        /// </summary>
        /// <param name="pDestination"></param>
        /// <param name="outSize"></param>
        /// <param name="outFormat"></param>
        /// <param name="pSource"></param>
        /// <param name="inSize"></param>
        /// <param name="inFormat"></param>
        /// <param name="pal8"></param>
        /// <param name="flags"></param>
        /// <returns></returns>
        static unsafe bool LegacyExpandScanline( IntPtr pDestination, int outSize, DXGI.Format outFormat, 
                                            IntPtr pSource, int inSize, TEXP_LEGACY_FORMAT inFormat,
                                            int* pal8, ScanlineFlags flags )
        {
            switch (inFormat)
            {
                case TEXP_LEGACY_FORMAT.R8G8B8:
                    if (outFormat != Format.R8G8B8A8_UNorm)
                        return false;

                    // D3DFMT_R8G8B8 -> Format.R8G8B8A8_UNorm
                    {
                        var sPtr = (byte*) (pSource);
                        var dPtr = (int*) (pDestination);

                        for (int ocount = 0, icount = 0; ((icount < inSize) && (ocount < outSize)); icount += 3, ocount += 4)
                        {
                            // 24bpp Direct3D 9 files are actually BGR, so need to swizzle as well
                            int t1 = (*(sPtr) << 16);
                            int t2 = (*(sPtr + 1) << 8);
                            int t3 = *(sPtr + 2);

                            *(dPtr++) = (int) (t1 | t2 | t3 | 0xff000000);
                            sPtr += 3;
                        }
                    }
                    return true;

                case TEXP_LEGACY_FORMAT.R3G3B2:
                    switch (outFormat)
                    {
                        case Format.R8G8B8A8_UNorm:
                            // D3DFMT_R3G3B2 -> Format.R8G8B8A8_UNorm
                            {
                                var sPtr = (byte*) (pSource);
                                var dPtr = (int*) (pDestination);

                                for (int ocount = 0, icount = 0; ((icount < inSize) && (ocount < outSize)); ++icount, ocount += 4)
                                {
                                    byte t = *(sPtr++);

                                    int t1 = (t & 0xe0) | ((t & 0xe0) >> 3) | ((t & 0xc0) >> 6);
                                    int t2 = ((t & 0x1c) << 11) | ((t & 0x1c) << 8) | ((t & 0x18) << 5);
                                    int t3 = ((t & 0x03) << 22) | ((t & 0x03) << 20) | ((t & 0x03) << 18) | ((t & 0x03) << 16);

                                    *(dPtr++) = (int) (t1 | t2 | t3 | 0xff000000);
                                }
                            }
                            return true;

                        case Format.B5G6R5_UNorm:
                            // D3DFMT_R3G3B2 -> Format.B5G6R5_UNorm
                            {
                                var sPtr = (byte*) (pSource);
                                var dPtr = (short*) (pDestination);

                                for (int ocount = 0, icount = 0; ((icount < inSize) && (ocount < outSize)); ++icount, ocount += 2)
                                {
                                    byte t = *(sPtr++);

                                    var t1 = (short) (((t & 0xe0) << 8) | ((t & 0xc0) << 5));
                                    var t2 = (short) (((t & 0x1c) << 6) | ((t & 0x1c) << 3));
                                    var t3 = (short) (((t & 0x03) << 3) | ((t & 0x03) << 1) | ((t & 0x02) >> 1));

                                    *(dPtr++) = (short) (t1 | t2 | t3);
                                }
                            }
                            return true;
                    }
                    break;

                case TEXP_LEGACY_FORMAT.A8R3G3B2:
                    if (outFormat != Format.R8G8B8A8_UNorm)
                        return false;

                    // D3DFMT_A8R3G3B2 -> Format.R8G8B8A8_UNorm
                    {
                        var sPtr = (short*) (pSource);
                        var dPtr = (int*) (pDestination);

                        for (int ocount = 0, icount = 0; ((icount < inSize) && (ocount < outSize)); icount += 2, ocount += 4)
                        {
                            short t = *(sPtr++);

                            int t1 = (t & 0x00e0) | ((t & 0x00e0) >> 3) | ((t & 0x00c0) >> 6);
                            int t2 = ((t & 0x001c) << 11) | ((t & 0x001c) << 8) | ((t & 0x0018) << 5);
                            int t3 = ((t & 0x0003) << 22) | ((t & 0x0003) << 20) | ((t & 0x0003) << 18) | ((t & 0x0003) << 16);
                            uint ta = ((flags & ScanlineFlags.SetAlpha) != 0 ? 0xff000000 : (uint) ((t & 0xff00) << 16));

                            *(dPtr++) = (int) (t1 | t2 | t3 | ta);
                        }
                    }
                    return true;

                case TEXP_LEGACY_FORMAT.P8:
                    if ((outFormat != Format.R8G8B8A8_UNorm) || pal8 == null)
                        return false;

                    // D3DFMT_P8 -> Format.R8G8B8A8_UNorm
                    {
                        byte* sPtr = (byte*) (pSource);
                        int* dPtr = (int*) (pDestination);

                        for (int ocount = 0, icount = 0; ((icount < inSize) && (ocount < outSize)); ++icount, ocount += 4)
                        {
                            byte t = *(sPtr++);

                            *(dPtr++) = pal8[t];
                        }
                    }
                    return true;

                case TEXP_LEGACY_FORMAT.A8P8:
                    if ((outFormat != Format.R8G8B8A8_UNorm) || pal8 == null)
                        return false;

                    // D3DFMT_A8P8 -> Format.R8G8B8A8_UNorm
                    {
                        short* sPtr = (short*) (pSource);
                        int* dPtr = (int*) (pDestination);

                        for (int ocount = 0, icount = 0; ((icount < inSize) && (ocount < outSize)); icount += 2, ocount += 4)
                        {
                            short t = *(sPtr++);

                            int t1 = pal8[t & 0xff];
                            uint ta = ((flags & ScanlineFlags.SetAlpha) != 0 ? 0xff000000 : (uint) ((t & 0xff00) << 16));

                            *(dPtr++) = (int) (t1 | ta);
                        }
                    }
                    return true;

                case TEXP_LEGACY_FORMAT.A4L4:
                    switch (outFormat)
                    {
#if DIRECTX11_1
                case Format.B4G4R4A4_UNorm :
                    // D3DFMT_A4L4 -> Format.B4G4R4A4_UNorm 
                    {
                        byte * sPtr = (byte*)(pSource);
                        short * dPtr = (short*)(pDestination);

                        for( int ocount = 0, icount = 0; ((icount < inSize) && (ocount < outSize)); ++icount, ocount += 2 )
                        {
                            byte t = *(sPtr++);

                            short t1 = (short)(t & 0x0f);
                            ushort ta = (flags & ScanlineFlags.SetAlpha ) != 0 ?  (ushort)0xf000 : (ushort)((t & 0xf0) << 8);

                            *(dPtr++) = (short)(t1 | (t1 << 4) | (t1 << 8) | ta);
                        }
                    }
                    return true;
#endif
                            // DXGI_1_2_FORMATS

                        case Format.R8G8B8A8_UNorm:
                            // D3DFMT_A4L4 -> Format.R8G8B8A8_UNorm
                            {
                                byte* sPtr = (byte*) (pSource);
                                int* dPtr = (int*) (pDestination);

                                for (int ocount = 0, icount = 0; ((icount < inSize) && (ocount < outSize)); ++icount, ocount += 4)
                                {
                                    byte t = *(sPtr++);

                                    int t1 = ((t & 0x0f) << 4) | (t & 0x0f);
                                    uint ta = ((flags & ScanlineFlags.SetAlpha) != 0 ? 0xff000000 : (uint) (((t & 0xf0) << 24) | ((t & 0xf0) << 20)));

                                    *(dPtr++) = (int) (t1 | (t1 << 8) | (t1 << 16) | ta);
                                }
                            }
                            return true;
                    }
                    break;

#if !DIRECTX11_1
                case TEXP_LEGACY_FORMAT.B4G4R4A4:
                    if (outFormat != Format.R8G8B8A8_UNorm)
                        return false;

                    // D3DFMT_A4R4G4B4 -> Format.R8G8B8A8_UNorm
                    {
                        short* sPtr = (short*) (pSource);
                        int* dPtr = (int*) (pDestination);

                        for (int ocount = 0, icount = 0; ((icount < inSize) && (ocount < outSize)); icount += 2, ocount += 4)
                        {
                            short t = *(sPtr++);

                            int t1 = ((t & 0x0f00) >> 4) | ((t & 0x0f00) >> 8);
                            int t2 = ((t & 0x00f0) << 8) | ((t & 0x00f0) << 4);
                            int t3 = ((t & 0x000f) << 20) | ((t & 0x000f) << 16);
                            uint ta = ((flags & ScanlineFlags.SetAlpha) != 0 ? 0xff000000 : (uint) (((t & 0xf000) << 16) | ((t & 0xf000) << 12)));

                            *(dPtr++) = (int) (t1 | t2 | t3 | ta);
                        }
                    }
                    return true;
#endif
            }
            return false;
        }
Example #21
0
        private void CreateDeviceResources()
        {
            Guid iid;

#if DEBUG
            {
                using ComPtr <ID3D12Debug> debugController = null;

                iid = D3D12.IID_ID3D12Debug;
                if (SUCCEEDED(D3D12.D3D12GetDebugInterface(&iid, (void **)debugController.GetAddressOf())))
                {
                    debugController.Ptr->EnableDebugLayer();
                }
            }
#endif
            iid = DXGI.IID_IDXGIFactory4;
            IDXGIFactory4 *dxgiFactory;
            DirectXHelper.ThrowIfFailed(DXGI.CreateDXGIFactory1(&iid, (void **)&dxgiFactory));
            _dxgiFactory = dxgiFactory;

            using ComPtr <IDXGIAdapter1> adapter = null;
            GetHardwareAdapter(adapter.ReleaseGetAddressOf());

            ID3D12Device *d3dDevice;
            iid = D3D12.IID_ID3D12Device;
            HRESULT hr;
            {
                hr = D3D12.D3D12CreateDevice(
                    adapter,
                    D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_11_0,
                    &iid,
                    (void **)&d3dDevice
                    );

#if DEBUG
                if (FAILED(hr))
                {
                    using ComPtr <IDXGIAdapter> warpAdapter = null;

                    iid = DXGI.IID_IDXGIAdapter;
                    DirectXHelper.ThrowIfFailed(_dxgiFactory.Ptr->EnumWarpAdapter(&iid, (void **)warpAdapter.GetAddressOf()));

                    iid = D3D12.IID_ID3D12Device1;
                    hr  = D3D12.D3D12CreateDevice(
                        warpAdapter,
                        D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_11_0,
                        &iid,
                        (void **)&d3dDevice
                        );
                }
#endif
            }
            _d3dDevice = d3dDevice;

            DirectXHelper.ThrowIfFailed(hr);

            D3D12_COMMAND_QUEUE_DESC queueDesc;
            queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAGS.D3D12_COMMAND_QUEUE_FLAG_NONE;
            queueDesc.Type  = D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT;

            ID3D12CommandQueue *commandQueue;
            {
                iid = D3D12.IID_ID3D12CommandQueue;
                DirectXHelper.ThrowIfFailed(_d3dDevice.Ptr->CreateCommandQueue(&queueDesc, &iid, (void **)&commandQueue));
            }
            _commandQueue = commandQueue;
            DirectXHelper.NameObject(_commandQueue, nameof(_commandQueue));

            D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc;
            rtvHeapDesc.NumDescriptors = FrameCount;
            rtvHeapDesc.Type           = D3D12_DESCRIPTOR_HEAP_TYPE.D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
            rtvHeapDesc.Flags          = D3D12_DESCRIPTOR_HEAP_FLAGS.D3D12_DESCRIPTOR_HEAP_FLAG_NONE;

            ID3D12DescriptorHeap *rtvHeap;
            {
                iid = D3D12.IID_ID3D12DescriptorHeap;
                DirectXHelper.ThrowIfFailed(_d3dDevice.Ptr->CreateDescriptorHeap(&rtvHeapDesc, &iid, (void **)&rtvHeap));
            }
            _rtvHeap = rtvHeap;
            DirectXHelper.NameObject(_rtvHeap, nameof(_rtvHeap));

            _rtvDescriptorSize =
                _d3dDevice.Ptr->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE
                                                                 .D3D12_DESCRIPTOR_HEAP_TYPE_RTV);



            D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc;
            dsvHeapDesc.NumDescriptors = 1;
            dsvHeapDesc.Type           = D3D12_DESCRIPTOR_HEAP_TYPE.D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
            dsvHeapDesc.Flags          = D3D12_DESCRIPTOR_HEAP_FLAGS.D3D12_DESCRIPTOR_HEAP_FLAG_NONE;

            ID3D12DescriptorHeap *dsvHeap;
            {
                iid = D3D12.IID_ID3D12DescriptorHeap;
                DirectXHelper.ThrowIfFailed(_d3dDevice.Ptr->CreateDescriptorHeap(&dsvHeapDesc, &iid, (void **)&dsvHeap));
            }

            _dsvHeap = dsvHeap;
            DirectXHelper.NameObject(_dsvHeap, nameof(_dsvHeap));

            fixed(CommandAllocators_e__FixedBuffer *pBuffer = &_commandAllocators)
            {
                var p = (ID3D12CommandAllocator **)pBuffer;

                iid = D3D12.IID_ID3D12CommandAllocator;
                for (var n = 0; n < FrameCount; n++)
                {
                    DirectXHelper.ThrowIfFailed(_d3dDevice.Ptr->CreateCommandAllocator(
                                                    D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT,
                                                    &iid,
                                                    (void **)(p + n)));
                }
            }

            ID3D12Fence *fence;
            {
                iid = D3D12.IID_ID3D12Fence;
                DirectXHelper.ThrowIfFailed(
                    _d3dDevice.Ptr->CreateFence(_fenceValues[_currentFrame],
                                                D3D12_FENCE_FLAGS.D3D12_FENCE_FLAG_NONE,
                                                &iid,
                                                (void **)&fence));
                _fenceValues[_currentFrame]++;
            }
            _fence = fence;
            DirectXHelper.NameObject(_fence, nameof(_fence));

            _fenceEvent = Kernel32.CreateEvent(null, FALSE, FALSE, null);
            if (_fenceEvent == IntPtr.Zero)
            {
                DirectXHelper.ThrowIfFailed(Marshal.GetLastWin32Error());
            }
        }
Example #22
0
        private int CalculateRankForFormat(DXGI.Format format)
        {
            if (format == PreferredBackBufferFormat)
            {
                return 0;
            }

            if (CalculateFormatSize(format) == CalculateFormatSize(PreferredBackBufferFormat))
            {
                return 1;
            }

            return int.MaxValue;
        }
 /// <summary>
 /// Gets a specific <see cref="ShaderResourceView" /> from this texture.
 /// </summary>
 /// <param name="viewFormat">The view format.</param>
 /// <param name="viewType">Type of the view.</param>
 /// <param name="arrayOrDepthSlice">The array or depth slice.</param>
 /// <param name="mipIndex">Index of the mip.</param>
 /// <returns>An <see cref="ShaderResourceView" /></returns>
 public TextureView this[DXGI.Format viewFormat, ViewType viewType, int arrayOrDepthSlice, int mipIndex] { get { return this.texture.GetShaderResourceView(viewFormat, viewType, arrayOrDepthSlice, mipIndex); } }
Example #24
0
        /// <summary>
        /// Resizes the current presenter, by resizing the back buffer and the depth stencil buffer.
        /// </summary>
        /// <param name="width"></param>
        /// <param name="height"></param>
        public virtual void Resize(int width, int height, DXGI.Format format)
        {
            if (DepthStencilBuffer != null)
            {
                RemoveAndDispose(ref depthStencilBuffer);
            }

            Description.BackBufferWidth = width;
            Description.BackBufferHeight = height;
            Description.BackBufferFormat = format;

            DefaultViewport = new ViewportF(0, 0, Description.BackBufferWidth, Description.BackBufferHeight);

            CreateDepthStencilBuffer();
        }
Example #25
0
    public HelloDml()
    {
        if (!IsSupported())
        {
            throw new InvalidOperationException("Direct3D12 is not supported on current OS");
        }

        bool validation = false;

#if DEBUG
        if (D3D12.D3D12GetDebugInterface(out ID3D12Debug? debug).Success)
        {
            debug !.EnableDebugLayer();
            debug !.Dispose();
            validation = true;
        }
#endif

        DXGIFactory = DXGI.CreateDXGIFactory2 <IDXGIFactory4>(validation);

        ID3D12Device2?device = default;

        for (int adapterIndex = 0; DXGIFactory.EnumAdapters1(adapterIndex, out IDXGIAdapter1 adapter).Success; adapterIndex++)
        {
            AdapterDescription1 desc = adapter.Description1;

            // Don't select the Basic Render Driver adapter.
            if ((desc.Flags & AdapterFlags.Software) != AdapterFlags.None)
            {
                adapter.Dispose();

                continue;
            }

            if (D3D12.D3D12CreateDevice(adapter, Vortice.Direct3D.FeatureLevel.Level_11_0, out device).Success)
            {
                adapter.Dispose();

                break;
            }
        }

        if (device == null)
        {
            throw new InvalidOperationException("Direct3D12 device could not be created");
        }

        D3D12Device = device !;

        CommandQueueDescription commandQueueDesc = new()
        {
            Type  = CommandListType.Direct,
            Flags = CommandQueueFlags.None,
        };

        D3D12CommandQueue     = D3D12Device.CreateCommandQueue(commandQueueDesc);
        D3D12CommandAllocator = D3D12Device.CreateCommandAllocator(CommandListType.Direct);
        D3D12CommandList      = D3D12Device.CreateCommandList <ID3D12GraphicsCommandList4>(CommandListType.Direct, D3D12CommandAllocator);

        var createFlags = CreateDeviceFlags.None;

#if DEBUG
        createFlags |= CreateDeviceFlags.Debug;
#endif
        DMLDevice = DMLCreateDevice(D3D12Device, createFlags);

        Console.WriteLine($"Highest supported feature level: {DMLDevice.HighestFeatureLevel}");
    }
Example #26
0
        /// <summary>
        /// Converts a <see cref="SharpDX.DXGI.Format"/> to a a WIC <see cref="WIC.PixelFormat"/>.
        /// </summary>
        /// <param name="format">A <see cref="SharpDX.DXGI.Format"/></param>
        /// <param name="guid">A WIC <see cref="WIC.PixelFormat"/> Guid.</param>
        /// <returns>True if conversion succeed, false otherwise.</returns>
        private static bool ToWIC(DXGI.Format format, out Guid guid)
        {
            for (int i = 0; i < WICToDXGIFormats.Length; ++i)
            {
                if (WICToDXGIFormats[i].Format == format)
                {
                    guid = WICToDXGIFormats[i].WIC;
                    return true;
                }
            }

            // Special cases
            switch (format)
            {
                case SharpDX.DXGI.Format.R8G8B8A8_UNorm_SRgb:
                    guid = SharpDX.WIC.PixelFormat.Format32bppRGBA;
                    return true;

                case SharpDX.DXGI.Format.D32_Float:
                    guid = SharpDX.WIC.PixelFormat.Format32bppGrayFloat;
                    return true;

                case SharpDX.DXGI.Format.D16_UNorm:
                    guid = SharpDX.WIC.PixelFormat.Format16bppGray;
                    return true;

                case SharpDX.DXGI.Format.B8G8R8A8_UNorm_SRgb:
                    guid = SharpDX.WIC.PixelFormat.Format32bppBGRA;
                    return true;

                case SharpDX.DXGI.Format.B8G8R8X8_UNorm_SRgb:
                    guid = SharpDX.WIC.PixelFormat.Format32bppBGR;
                    return true;
            }

            guid = Guid.Empty;
            return false;
        }
Example #27
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();
        }
Example #28
0
		public VirtualSurface(SurfaceFactory factory, int initialWidth, int initialHeight, DXGI.Format format, DXGI.AlphaMode alphaMode)
			: base(IntPtr.Zero)
		{
			factory.CreateVirtualSurface(initialWidth, initialHeight, format, alphaMode, this);
		}
Example #29
0
		public VirtualSurface(Device device, int initialWidth, int initialHeight, DXGI.Format format, DXGI.AlphaMode alphaMode) : base(IntPtr.Zero)
		{
			device.CreateVirtualSurface(initialWidth, initialHeight, format, alphaMode, this);
		}
Example #30
0
        private int CalculateFormatSize(DXGI.Format format)
        {
            switch (format)
            {
                case DXGI.Format.R8G8B8A8_UNorm:
                case DXGI.Format.R8G8B8A8_UNorm_SRgb:
                case DXGI.Format.B8G8R8A8_UNorm:
                case DXGI.Format.B8G8R8A8_UNorm_SRgb:
                case DXGI.Format.R10G10B10A2_UNorm:
                    return 32;

                case DXGI.Format.B5G6R5_UNorm:
                case DXGI.Format.B5G5R5A1_UNorm:
                    return 16;
            }

            return 0;
        }
Example #31
0
        public bool Init(IntPtr WindowHandle)
        {
            var factory            = DXGI.CreateDXGIFactory1 <IDXGIFactory1>();
            var adapter            = factory.GetAdapter1(0);
            var monitor            = adapter.GetOutput(0);
            var modes              = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced);
            var rational           = new Rational(0, 1);
            var adapterDescription = adapter.Description;

            //VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10;
            //VideoCardDescription = adapterDescription.Description.Trim('\0');
            monitor.Dispose();
            adapter.Dispose();

            var swapChainDesc = new SwapChainDescription()
            {
                BufferCount       = 2,
                BufferDescription = new ModeDescription(1920, 1080, rational, Format.R8G8B8A8_UNorm),
                Usage             = Usage.RenderTargetOutput,
                OutputWindow      = WindowHandle,
                SampleDescription = new SampleDescription(1, 0),
                IsWindowed        = true,
                Flags             = SwapChainFlags.None,
                SwapEffect        = SwapEffect.Discard
            };

            // Create Device and DeviceContext
            ID3D11Device        TempDevice        = null;
            ID3D11DeviceContext TempDeviceContext = null;

            D3D11.D3D11CreateDevice(adapter, DriverType.Hardware, DeviceCreationFlags.None, null, out TempDevice, out TempDeviceContext);

            Device        = TempDevice.QueryInterface <ID3D11Device1>();
            DeviceContext = TempDeviceContext.QueryInterface <ID3D11DeviceContext1>();
            TempDevice.Dispose();
            TempDeviceContext.Dispose();

            // Create SwapChain
            SwapChain = factory.CreateSwapChain(Device, swapChainDesc);
            factory.MakeWindowAssociation(WindowHandle, WindowAssociationFlags.IgnoreAltEnter);

            var backBuffer = SwapChain.GetBuffer <ID3D11Texture2D>(0);

            m_RenderTargetView = Device.CreateRenderTargetView(backBuffer);
            backBuffer.Dispose();

            // Create blend state
            BlendDescription bsd = new BlendDescription()
            {
                AlphaToCoverageEnable  = false,//true,
                IndependentBlendEnable = false,
            };

            bsd.RenderTarget[0].BlendOperationAlpha   = BlendOperation.Add;
            bsd.RenderTarget[0].BlendOperation        = BlendOperation.Add;
            bsd.RenderTarget[0].DestinationBlendAlpha = Blend.One;
            bsd.RenderTarget[0].DestinationBlend      = Blend.InverseSourceAlpha;
            bsd.RenderTarget[0].IsBlendEnabled        = true;
            bsd.RenderTarget[0].RenderTargetWriteMask = ColorWriteEnable.All;
            bsd.RenderTarget[0].SourceBlendAlpha      = Blend.Zero;
            bsd.RenderTarget[0].SourceBlend           = Blend.SourceAlpha;
            bsd.AlphaToCoverageEnable = true;

            ID3D11BlendState bsAlpha = Device.CreateBlendState(bsd);

            // Set Blend State
            DeviceContext.OMSetBlendState(bsAlpha);
            BuildDepthStencilView(1920, 1080);

            // Create rasterizers
            m_RSDesc = new RasterizerDescription()
            {
                AntialiasedLineEnable = false,
                CullMode              = CullMode.Back,
                DepthBias             = 0,
                DepthBiasClamp        = .0f,
                DepthClipEnable       = false,
                FillMode              = FillMode.Solid,
                FrontCounterClockwise = true,
                MultisampleEnable     = true,
                ScissorEnable         = false,
                SlopeScaledDepthBias  = .0f
            };

            m_RSCullSolid     = Device.CreateRasterizerState(m_RSDesc);
            m_RSDesc.CullMode = CullMode.None;
            m_RSSolid         = Device.CreateRasterizerState(m_RSDesc);
            m_RSDesc.FillMode = FillMode.Wireframe;
            m_RSWireFrame     = Device.CreateRasterizerState(m_RSDesc);
            m_RSDesc.CullMode = CullMode.Back;
            m_RSCullWireFrame = Device.CreateRasterizerState(m_RSDesc);

            UpdateRasterizer();
            return(true);
        }