Exemplo n.º 1
0
        void CollisionWithTheFence(double nextX, double nextY, Fence fence)
        {
            // Отскок сбоку
            if (this.Bottom() >= fence.Top()
                && (this.Right() > fence.Left() && this.Left() < fence.Right()
                || nextX + this.RealWidth() > fence.Left() && nextX < fence.Right()))
                Velocity.X = -Velocity.X;

            // Отскок сверху
            double radius2 = Math.Pow(this.RealWidth() / 2.0, 2);
            Vector center = new Vector(nextX + this.RealWidth() / 2.0, nextY + this.RealHeight() / 2.0);
            if (center.DistanceTo(new Vector(fence.Left(), fence.Top())) <= radius2
            || center.DistanceTo(new Vector(fence.Right(), fence.Top())) <= radius2)
                Velocity.Y = -Velocity.Y;
        }
Exemplo n.º 2
0
        public void Move(double width, double height, Score score, Fence fence, Player[] players)
        {
            Velocity.Y = PowerOfAttraction();

            double x = this.Left() + Speed * Velocity.X, y = this.Top() + Speed * Velocity.Y;
            ImpactOnTheBorder(x, y, width, height);
            HitTheGround(x, y, width, height, score);

            this.SetLeft(x);
            this.SetTop(y);

            double nextX = this.Left() + Speed * Velocity.X, nextY = this.Top() + Speed * PowerOfAttraction();
            CollisionWithTheFence(nextX, nextY, fence);
            for (int i = 0; i < players.Length; ++i)
                CollisionWithThePlayer(nextX, nextY, players[i]);
        }
Exemplo n.º 3
0
        public Game(Canvas canvas, Fence fence, Ball ball, Player[] players, TextBlock result)
        {
            this.canvas = canvas;
            this.fence = fence;
            this.ball = ball;
            this.players = players;
            this.result = result;

            timer = new DispatcherTimer();
            timer.Interval = new System.TimeSpan(speed);
            timer.Tick += new System.EventHandler(timer_Tick);

            wait = new DispatcherTimer();
            wait.Tick += new System.EventHandler(wait_Tick);
            wait.Interval = new TimeSpan(0, 0, 0, 0, timeWait);

            fence.SetLeft((canvas.RealWidth() - fence.Width) / 2.0);
            fence.SetTop(canvas.RealHeight() - fence.Height);

            Reset();
        }
Exemplo n.º 4
0
        public unsafe void Run(int currentFrameIndex, int imageIndex, Semaphore waitSemaphore, Semaphore signalSemaphore, Fence signal)
        {
            var bufferInfo = new DescriptorBufferInfo(_commandBuffers[currentFrameIndex], 0,
                                                      (ulong)(sizeof(uint) * _commandBufferCapacities[currentFrameIndex]));

            _vk.UpdateDescriptorSets(_device, 1,
                                     new WriteDescriptorSet(dstSet: _targetDescriptorSets[currentFrameIndex], dstBinding: 1, dstArrayElement: 0,
                                                            descriptorCount: 1, descriptorType: DescriptorType.StorageBuffer, pBufferInfo: &bufferInfo), 0,
                                     null);


            var currentFrame = _frames[currentFrameIndex];

            _vk.ResetCommandPool(_device, currentFrame.CommandPool, 0).ThrowCode();
            _vk.AllocateCommandBuffers(_device,
                                       new CommandBufferAllocateInfo(commandPool: currentFrame.CommandPool, level: CommandBufferLevel.Primary,
                                                                     commandBufferCount: 1), out var commandBuffer).ThrowCode();

            Name(ObjectType.CommandBuffer, (ulong)commandBuffer.Handle, $"Command Buffer Frame {currentFrameIndex}");

            var renderContext = new RenderContext(_targetImageViews[imageIndex],
                                                  _targetSize, currentFrameIndex);

            _vk.BeginCommandBuffer(commandBuffer,
                                   new CommandBufferBeginInfo(flags: CommandBufferUsageFlags.CommandBufferUsageOneTimeSubmitBit))
            .ThrowCode();

            // var memoryBarrier = new ImageMemoryBarrier2KHR(srcStageMask: PipelineStageFlags2KHR.PipelineStage2TopOfPipeBitKhr,
            //     srcAccessMask: AccessFlags2KHR.Access2NoneKhr, dstStageMask: PipelineStageFlags2KHR.PipelineStage2TransferBitKhr,
            //     dstAccessMask: AccessFlags2KHR.Access2TransferWriteBitKhr,
            //     oldLayout: ImageLayout.Undefined, newLayout: ImageLayout.TransferDstOptimal,
            //     srcQueueFamilyIndex: Vk.QueueFamilyIgnored, dstQueueFamilyIndex: Vk.QueueFamilyIgnored,
            //     image: _targetImages.Span[imageIndex], subresourceRange: new ImageSubresourceRange(ImageAspectFlags.ImageAspectColorBit, 0, 1, 0, 1),
            //     sType: StructureType.ImageMemoryBarrier2Khr, pNext: null);
            // _khrSynchronization2.CmdPipelineBarrier2(commandBuffer, new DependencyInfoKHR(imageMemoryBarrierCount: 1,
            //     pImageMemoryBarriers: &memoryBarrier, dependencyFlags: 0, memoryBarrierCount: 0, pMemoryBarriers: null, bufferMemoryBarrierCount: 0, pBufferMemoryBarriers: null));

            _vk.CmdPipelineBarrier(commandBuffer, PipelineStageFlags.PipelineStageTopOfPipeBit,
                                   PipelineStageFlags.PipelineStageTransferBit, 0, 0, null, 0, null, 1,
                                   new ImageMemoryBarrier(srcAccessMask: AccessFlags.AccessNoneKhr,
                                                          dstAccessMask: AccessFlags.AccessTransferWriteBit, oldLayout: ImageLayout.Undefined,
                                                          newLayout: ImageLayout.TransferDstOptimal, srcQueueFamilyIndex: Vk.QueueFamilyIgnored,
                                                          dstQueueFamilyIndex: Vk.QueueFamilyIgnored, image: _targetImages.Span[imageIndex],
                                                          subresourceRange: new ImageSubresourceRange(ImageAspectFlags.ImageAspectColorBit, 0, 1, 0, 1)));

            _vk.CmdClearColorImage(commandBuffer, _targetImages.Span[imageIndex], ImageLayout.TransferDstOptimal,
                                   new ClearColorValue(0f, 0f, 0f, 1f), 1,
                                   new ImageSubresourceRange(ImageAspectFlags.ImageAspectColorBit, 0, 1, 0, 1));

            // var memoryBarrier2 = new ImageMemoryBarrier2KHR(srcStageMask: PipelineStageFlags2KHR.PipelineStage2TransferBitKhr,
            //     srcAccessMask: AccessFlags2KHR.Access2TransferWriteBitKhr, dstStageMask: PipelineStageFlags2KHR.PipelineStage2ComputeShaderBitKhr,
            //     dstAccessMask: AccessFlags2KHR.Access2ShaderReadBitKhr | AccessFlags2KHR.Access2ShaderWriteBitKhr,
            //     oldLayout: ImageLayout.TransferDstOptimal, newLayout: ImageLayout.General,
            //     srcQueueFamilyIndex: Vk.QueueFamilyIgnored, dstQueueFamilyIndex: Vk.QueueFamilyIgnored,
            //     image: _targetImages.Span[imageIndex], subresourceRange: new ImageSubresourceRange(ImageAspectFlags.ImageAspectColorBit, 0, 1, 0, 1));
            // _khrSynchronization2.CmdPipelineBarrier2(commandBuffer, new DependencyInfoKHR(imageMemoryBarrierCount: 1,
            //     pImageMemoryBarriers: &memoryBarrier2));

            _vk.CmdPipelineBarrier(commandBuffer, PipelineStageFlags.PipelineStageTransferBit,
                                   PipelineStageFlags.PipelineStageComputeShaderBit, 0, 0, null, 0, null, 1,
                                   new ImageMemoryBarrier(srcAccessMask: AccessFlags.AccessTransferWriteBit,
                                                          dstAccessMask: AccessFlags.AccessShaderReadBit | AccessFlags.AccessShaderWriteBit, oldLayout: ImageLayout.TransferDstOptimal,
                                                          newLayout: ImageLayout.General, srcQueueFamilyIndex: Vk.QueueFamilyIgnored,
                                                          dstQueueFamilyIndex: Vk.QueueFamilyIgnored, image: _targetImages.Span[imageIndex],
                                                          subresourceRange: new ImageSubresourceRange(ImageAspectFlags.ImageAspectColorBit, 0, 1, 0, 1)));

            Span <uint> pValues = stackalloc uint[]
            {
                _targetSize.X, _targetSize.Y
            };

            _vk.CmdPushConstants(commandBuffer, _pipelineLayout, ShaderStageFlags.ShaderStageComputeBit, 0, (uint)pValues.Length * sizeof(uint), pValues);
            _vk.CmdBindDescriptorSets(commandBuffer, PipelineBindPoint.Compute, _pipelineLayout, 0, 1,
                                      _targetDescriptorSets[imageIndex], 0, null);
            _computeShader.Record(renderContext, commandBuffer);

            // var memoryBarrier3 = new ImageMemoryBarrier2KHR(srcStageMask: PipelineStageFlags2KHR.PipelineStage2ComputeShaderBitKhr,
            //      srcAccessMask: AccessFlags2KHR.Access2ShaderReadBitKhr | AccessFlags2KHR.Access2ShaderWriteBitKhr, dstStageMask: PipelineStageFlags2KHR.PipelineStage2BottomOfPipeBitKhr,
            //      dstAccessMask: AccessFlags2KHR.Access2NoneKhr,
            //      oldLayout: ImageLayout.General, newLayout: ImageLayout.PresentSrcKhr,
            //      srcQueueFamilyIndex: Vk.QueueFamilyIgnored, dstQueueFamilyIndex: Vk.QueueFamilyIgnored,
            //      image: _targetImages.Span[imageIndex], subresourceRange: new ImageSubresourceRange(ImageAspectFlags.ImageAspectColorBit, 0, 1, 0, 1));
            //  _khrSynchronization2.CmdPipelineBarrier2(commandBuffer, new DependencyInfoKHR(imageMemoryBarrierCount: 1,
            //      pImageMemoryBarriers: &memoryBarrier3));

            _vk.CmdPipelineBarrier(commandBuffer, PipelineStageFlags.PipelineStageComputeShaderBit,
                                   PipelineStageFlags.PipelineStageBottomOfPipeBit, 0, 0, null, 0, null, 1,
                                   new ImageMemoryBarrier(srcAccessMask: AccessFlags.AccessShaderReadBit | AccessFlags.AccessShaderWriteBit,
                                                          dstAccessMask: AccessFlags.AccessNoneKhr, oldLayout: ImageLayout.General,
                                                          newLayout: ImageLayout.PresentSrcKhr, srcQueueFamilyIndex: Vk.QueueFamilyIgnored,
                                                          dstQueueFamilyIndex: Vk.QueueFamilyIgnored, image: _targetImages.Span[imageIndex],
                                                          subresourceRange: new ImageSubresourceRange(ImageAspectFlags.ImageAspectColorBit, 0, 1, 0, 1)));

            _vk.EndCommandBuffer(commandBuffer);

            var waitDstStageMask = PipelineStageFlags.PipelineStageTransferBit;

            _vk.QueueSubmit(Queue, 1,
                            new SubmitInfo(waitSemaphoreCount: 1, pWaitSemaphores: &waitSemaphore, commandBufferCount: 1,
                                           pCommandBuffers: &commandBuffer, signalSemaphoreCount: 1, pSignalSemaphores: &signalSemaphore,
                                           pWaitDstStageMask: &waitDstStageMask), signal).ThrowCode();
        }
 /// <summary>To be documented.</summary>
 public static unsafe Result QueueSubmit2(this KhrSynchronization2 thisApi, [Count(Count = 0)] Queue queue, [Count(Count = 0)] uint submitCount, [Count(Computed = "submitCount"), Flow(FlowDirection.In)] ReadOnlySpan <SubmitInfo2KHR> pSubmits, [Count(Count = 0)] Fence fence)
 {
     // SpanOverloader
     return(thisApi.QueueSubmit2(queue, submitCount, in pSubmits.GetPinnableReference(), fence));
 }
Exemplo n.º 6
0
 internal static unsafe extern Result vkCreateFence(Device device, FenceCreateInfo* createInfo, AllocationCallbacks* allocator, Fence* fence);
Exemplo n.º 7
0
 public void OnBegin()
 {
     _queue = new NaiveLockFreeQueue();
     Fence.Insert(MemoryOrder.SequentiallyConsistent);
 }
Exemplo n.º 8
0
        private void LoadAssets()
        {
            RootParameter parameter1 = new RootParameter(ShaderVisibility.All, new DescriptorRange() { RangeType = DescriptorRangeType.ConstantBufferView, BaseShaderRegister = 0, DescriptorCount = 1 });
            RootParameter parameter2 = new RootParameter(ShaderVisibility.Pixel, new DescriptorRange() { RangeType = DescriptorRangeType.ShaderResourceView, BaseShaderRegister = 0, DescriptorCount = 1 });
            RootParameter parameter3 = new RootParameter(ShaderVisibility.Pixel, new DescriptorRange() { RangeType = DescriptorRangeType.Sampler, BaseShaderRegister = 0, DescriptorCount = 1 });

            // Create a root signature.
            RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, new RootParameter[] { parameter1, parameter2, parameter3 });
            rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.

            #if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0"));
            #endif

            #if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
            #endif

            // Define the vertex input layout.
            InputElement[] inputElementDescs = new InputElement[]
            {
                    new InputElement("POSITION",0,Format.R32G32B32_Float,0,0),
                    new InputElement("NORMAL",0,Format.R32G32B32_Float,12,0),
                    new InputElement("TEXCOORD",0,Format.R32G32B32_Float,24,0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout = new InputLayoutDescription(inputElementDescs),
                RootSignature = rootSignature,
                VertexShader = vertexShader,
                PixelShader = pixelShader,
                RasterizerState = RasterizerStateDescription.Default(),
                BlendState = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState = DepthStencilStateDescription.Default(),
                SampleMask = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount = 1,
                Flags = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            // Create the command list.
            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);

            // Command lists are created in the recording state, but there is nothing
            // to record yet. The main loop expects it to be closed, so close it now.
            commandList.Close();

            // Create the vertex buffer.
            float aspectRatio = viewport.Width / viewport.Height;

            //constant Buffer
            int constantBufferSize = (Utilities.SizeOf<Transform>() + 255) & ~255;
            constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(constantBufferSize), ResourceStates.GenericRead);
            constantBufferDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);

            //constant buffer
            ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription()
            {
                BufferLocation = constantBuffer.GPUVirtualAddress,
                SizeInBytes = constantBufferSize
            };

            CpuDescriptorHandle cbHandleHeapStart = constantBufferViewHeap.CPUDescriptorHandleForHeapStart;
            device.CreateConstantBufferView(cbvDesc, cbHandleHeapStart);
            cbvDesc.BufferLocation += Utilities.SizeOf<Transform>();

            cbHandleHeapStart += constantBufferDescriptorSize;
            LoadMesh(cbHandleHeapStart);

            // Create synchronization objects.
            {
                fence = device.CreateFence(0, FenceFlags.None);
                fenceValue = 1;

                // Create an event handle to use for frame synchronization.
                fenceEvent = new AutoResetEvent(false);
            }

            InitBundles();
        }
        public GraphicsHost(RenderForm window, bool hidden = false)
        {
            if (window == null)
            {
                throw new ArgumentNullException(nameof(window));
            }

            this.window = window;
            if (!hidden)
            {
                this.window.Visible = true;
            }

#if DEBUG
            Configuration.EnableObjectTracking      = true;
            Configuration.ThrowOnShaderCompileError = false;
#endif

            var swapChainDescription = new SwapChainDescription()
            {
                BufferCount       = SwapBufferCount,
                ModeDescription   = new ModeDescription(Format.R8G8B8A8_UNorm),
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = window.Handle,
                SwapEffect        = SwapEffect.FlipDiscard,
                SampleDescription = new SampleDescription(1, 0),
                IsWindowed        = true
            };

#if DEBUG
            // Enable the D3D12 debug layer.
            // DebugInterface.Get().EnableDebugLayer();
#endif

            try
            {
                // null == DriverType.Hardware
                device       = new Device(null, FeatureLevel.Level_11_0);
                commandQueue = device.CreateCommandQueue(new CommandQueueDescription(CommandListType.Direct));
            }
            catch (SharpDXException)
            {
                using (var factory = new Factory4())
                {
                    device       = new Device(factory.GetWarpAdapter(), FeatureLevel.Level_11_0);
                    commandQueue = device.CreateCommandQueue(new CommandQueueDescription(CommandListType.Direct));
                }
            }

            using (var factory = new Factory1())
                swapChain = new SwapChain(factory, commandQueue, swapChainDescription);

            commandListAllocator = device.CreateCommandAllocator(CommandListType.Direct);

            descriptorHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription()
            {
                Type            = DescriptorHeapType.RenderTargetView,
                DescriptorCount = 1
            });

            commandList = device.CreateCommandList(CommandListType.Direct, commandListAllocator, null);

            renderTarget = swapChain.GetBackBuffer <Resource>(0);
            device.CreateRenderTargetView(renderTarget, null, descriptorHeap.CPUDescriptorHandleForHeapStart);

            viewport         = new ViewportF(0, 0, this.Width, this.Height);
            scissorRectangle = new Rectangle(0, 0, this.Width, this.Height);

            fence        = device.CreateFence(0, FenceFlags.None);
            currentFence = 1;

            commandList.Close();

            eventHandle = new AutoResetEvent(false);

            WaitForPrevFrame();
        }
Exemplo n.º 10
0
 public override void setFence(Direction d, Fence f)
 {
 }
Exemplo n.º 11
0
 public partial Result AcquireNextImage([Count(Count = 0)] Device device, [Count(Count = 0)] SwapchainKHR swapchain, [Count(Count = 0)] ulong timeout, [Count(Count = 0)] Semaphore semaphore, [Count(Count = 0)] Fence fence, [Count(Count = 0)] ref uint pImageIndex);
Exemplo n.º 12
0
 public Fence Post([FromBody] Fence fence)
 {
     _context.Fence.Add(fence);
     _context.SaveChanges();
     return(fence);
 }
Exemplo n.º 13
0
        /// <summary>
        ///     Initializes the specified device.
        /// </summary>
        /// <param name="graphicsProfiles">The graphics profiles.</param>
        /// <param name="deviceCreationFlags">The device creation flags.</param>
        /// <param name="windowHandle">The window handle.</param>
        private void InitializePlatformDevice(GraphicsProfile[] graphicsProfiles, DeviceCreationFlags deviceCreationFlags, object windowHandle)
        {
            if (nativeDevice != null)
            {
                // Destroy previous device
                ReleaseDevice();
            }

            rendererName = Adapter.NativeAdapter.Description.Description;

            // Profiling is supported through pix markers
            IsProfilingSupported = true;

            // Command lists are thread-safe and execute deferred
            IsDeferred = true;

            bool isDebug = (deviceCreationFlags & DeviceCreationFlags.Debug) != 0;

            if (isDebug)
            {
                SharpDX.Direct3D12.DebugInterface.Get().EnableDebugLayer();
            }

            // Create Device D3D12 with feature Level based on profile
            for (int index = 0; index < graphicsProfiles.Length; index++)
            {
                var graphicsProfile = graphicsProfiles[index];
                try
                {
                    // D3D12 supports only feature level 11+
                    var level = graphicsProfile.ToFeatureLevel();
                    if (level < SharpDX.Direct3D.FeatureLevel.Level_11_0)
                    {
                        level = SharpDX.Direct3D.FeatureLevel.Level_11_0;
                    }

                    nativeDevice = new SharpDX.Direct3D12.Device(Adapter.NativeAdapter, level);

                    RequestedProfile    = graphicsProfile;
                    CurrentFeatureLevel = level;
                    break;
                }
                catch (Exception)
                {
                    if (index == graphicsProfiles.Length - 1)
                    {
                        throw;
                    }
                }
            }

            // Describe and create the command queue.
            var queueDesc = new SharpDX.Direct3D12.CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Direct);

            NativeCommandQueue = nativeDevice.CreateCommandQueue(queueDesc);
            //queueDesc.Type = CommandListType.Copy;
            NativeCopyCommandQueue = nativeDevice.CreateCommandQueue(queueDesc);
            TimestampFrequency     = NativeCommandQueue.TimestampFrequency;

            SrvHandleIncrementSize     = NativeDevice.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
            SamplerHandleIncrementSize = NativeDevice.GetDescriptorHandleIncrementSize(DescriptorHeapType.Sampler);

            if (isDebug)
            {
                var debugDevice = nativeDevice.QueryInterfaceOrNull <DebugDevice>();
                if (debugDevice != null)
                {
                    var infoQueue = debugDevice.QueryInterfaceOrNull <InfoQueue>();
                    if (infoQueue != null)
                    {
                        MessageId[] disabledMessages =
                        {
                            // This happens when render target or depth stencil clear value is diffrent
                            // than provided during resource allocation.
                            MessageId.CleardepthstencilviewMismatchingclearvalue,
                            MessageId.ClearrendertargetviewMismatchingclearvalue,

                            // This occurs when there are uninitialized descriptors in a descriptor table,
                            // even when a shader does not access the missing descriptors.
                            MessageId.InvalidDescriptorHandle,

                            // These happen when capturing with VS diagnostics
                            MessageId.MapInvalidNullRange,
                            MessageId.UnmapInvalidNullRange,
                        };

                        // Disable irrelevant debug layer warnings
                        InfoQueueFilter filter = new InfoQueueFilter
                        {
                            DenyList = new InfoQueueFilterDescription
                            {
                                Ids = disabledMessages
                            }
                        };
                        infoQueue.AddStorageFilterEntries(filter);

                        //infoQueue.SetBreakOnSeverity(MessageSeverity.Error, true);
                        //infoQueue.SetBreakOnSeverity(MessageSeverity.Warning, true);

                        infoQueue.Dispose();
                    }
                    debugDevice.Dispose();
                }
            }

            // Prepare pools
            CommandAllocators = new CommandAllocatorPool(this);
            SrvHeaps          = new HeapPool(this, SrvHeapSize, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
            SamplerHeaps      = new HeapPool(this, SamplerHeapSize, DescriptorHeapType.Sampler);

            // Prepare descriptor allocators
            SamplerAllocator            = new DescriptorAllocator(this, DescriptorHeapType.Sampler);
            ShaderResourceViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
            DepthStencilViewAllocator   = new DescriptorAllocator(this, DescriptorHeapType.DepthStencilView);
            RenderTargetViewAllocator   = new DescriptorAllocator(this, DescriptorHeapType.RenderTargetView);

            // Prepare copy command list (start it closed, so that every new use start with a Reset)
            NativeCopyCommandAllocator = NativeDevice.CreateCommandAllocator(CommandListType.Direct);
            NativeCopyCommandList      = NativeDevice.CreateCommandList(CommandListType.Direct, NativeCopyCommandAllocator, null);
            NativeCopyCommandList.Close();

            // Fence for next frame and resource cleaning
            nativeFence     = NativeDevice.CreateFence(0, FenceFlags.None);
            nativeCopyFence = NativeDevice.CreateFence(0, FenceFlags.None);
        }
Exemplo n.º 14
0
 public FenceState(Fence fence)
 {
     pos = fence.gatePosition;
 }
Exemplo n.º 15
0
 public abstract Result RegisterDisplayEvent([Count(Count = 0)] Device device, [Count(Count = 0)] DisplayKHR display, [Count(Count = 0), Flow(FlowDirection.In)] ref DisplayEventInfoEXT pDisplayEventInfo, [Count(Count = 0), Flow(FlowDirection.In)] ref AllocationCallbacks pAllocator, [Count(Count = 0)] ref Fence pFence);
Exemplo n.º 16
0
        private void GenerateFences()
        {
            List<Vector3> lengths = new List<Vector3>();

            // we aint gonna generate fences when we are higher than 4 blocks form the top
            for (int y = 4; y < tile.GetLength(1); y++)
            {
                // no need to check the first tile since that will be a level block
                int length = 0;
                int start = 0;
                Vector3 currLength = Vector3.Zero;

                for (int x = 0; x < tile.GetLength(0); x++)
                {
                    if(length == 0)
                    {
                        start = x;
                    }
                    // what we need to do is calculate how far we can generate a fence, if only 1 block, we are not generating one

                    // Make sure the 3 tiles above it is not Solid, we dont care what type of tile it is thou
                    if(tile[x, y - 1].Solid == false && tile[x, y - 2].Solid == false && tile[x, y - 3].Solid == false)
                    {
                        if (tile[x, y].ID == TileID.Platform)
                        {
                            length++;

                            if(tile[x + 1, y].Solid == false)
                            {
                                currLength = new Vector3(start, length, y);
                                lengths.Add(currLength);
                                length = 0;
                                start = 0;
                            }
                        }
                    }
                }
            }

            // Add the fences on current Y position..
            foreach (Vector3 v in lengths)
            {
                // Make sure the length is greater than 1, else ignore it
                if (v.Y < 2)
                    continue;
                else
                {
                    if (v.Y >= 3)
                    {
                        Fence f1 = new Fence(FenceStyle.LeftEdge);
                        f1.Position = new Vector2(v.X * Tile.WIDTH, (v.Z - 3) * Tile.HEIGHT);
                        fences.Add(f1);

                        if (v.Y > 4)
                        {
                            int width = (int)v.X + (int)v.Y;
                            bool doorLast = ATools.IntToBool(Engine.Randomizer.Next(0, 1 + 1));

                            if (doorLast)
                            {
                                for (int i = (int)v.X + 1; i < width - 4; i++)
                                {
                                    Fence currFence = new Fence(FenceStyle.Short);
                                    currFence.Position = new Vector2(i * Tile.WIDTH, (v.Z - 3) * Tile.HEIGHT);
                                    fences.Add(currFence);
                                }

                                Fence doorFence = new Fence(FenceStyle.Door);
                                doorFence.Position = new Vector2((width - 4) * Tile.WIDTH, (v.Z - 3) * Tile.HEIGHT);
                                fences.Add(doorFence);
                            }
                            else
                            {
                                Fence doorFence = new Fence(FenceStyle.Door);
                                doorFence.Position = new Vector2((v.X + 1) * Tile.WIDTH, (v.Z - 3) * Tile.HEIGHT);
                                fences.Add(doorFence);

                                for (int i = (int)v.X + 4; i < width - 1; i++)
                                {
                                    Fence currFence = new Fence(FenceStyle.Short);
                                    currFence.Position = new Vector2(i * Tile.WIDTH, (v.Z - 3) * Tile.HEIGHT);
                                    fences.Add(currFence);
                                }
                            }
                        }
                        else
                        {
                            int width = (int)v.X + (int)v.Y;

                            for (int i = (int)v.X + 1; i < width - 1; i++)
                            {
                                Fence currFence = new Fence(FenceStyle.Short);
                                currFence.Position = new Vector2(i * Tile.WIDTH, (v.Z - 3) * Tile.HEIGHT);
                                fences.Add(currFence);
                            }
                        }

                        Fence fLast = new Fence(FenceStyle.RightEdge);
                        fLast.Position = new Vector2((v.X + v.Y - 1) * Tile.WIDTH, (v.Z - 3) * Tile.HEIGHT);
                        fences.Add(fLast);
                    }
                    else
                    {
                        Fence f1 = new Fence(FenceStyle.LeftEdge);
                        f1.Position = new Vector2(v.X * Tile.WIDTH, (v.Z - 3) * Tile.HEIGHT);
                        fences.Add(f1);

                        Fence fLast = new Fence(FenceStyle.RightEdge);
                        fLast.Position = new Vector2((v.X + 1) * Tile.WIDTH, (v.Z - 3) * Tile.HEIGHT);
                        fences.Add(fLast);
                    }
                }
            }
        }
Exemplo n.º 17
0
 public void Dispose()
 {
     NativeCommandQueue.Dispose();
     Fence.Dispose();
 }
Exemplo n.º 18
0
        internal static Texture2D FromTextureData(Context ctx, TextureData tex2D)
        {
            var stagingBuffer = ctx.Device.CreateBuffer(
                new BufferCreateInfo(tex2D.Mipmaps[0].Size, BufferUsages.TransferSrc));
            MemoryRequirements stagingMemReq = stagingBuffer.GetMemoryRequirements();
            int heapIndex = ctx.MemoryProperties.MemoryTypes.IndexOf(
                stagingMemReq.MemoryTypeBits, MemoryProperties.HostVisible);
            DeviceMemory stagingMemory = ctx.Device.AllocateMemory(
                new MemoryAllocateInfo(stagingMemReq.Size, heapIndex));

            stagingBuffer.BindMemory(stagingMemory);

            unsafe
            {
                var dest = (byte *)stagingMemory.Map(0, stagingMemReq.Size);
                var src  = (byte *)tex2D.Mipmaps[0].Data.Scan0;
                for (var i = 0; i < stagingMemReq.Size - 3; i += 4)
                {
                    *(dest + 2) = *(src++);
                    *(dest + 1) = *(src++);
                    *(dest)     = *(src++);
                    *(dest + 3) = *(src++);
                    dest       += 4;
                }
            }
            //Interop.Write(ptr, tex2D.Mipmaps[0].Data);
            stagingMemory.Unmap();

            // Setup buffer copy regions for each mip level.
            var bufferCopyRegions = new BufferImageCopy[tex2D.Mipmaps.Length];
            int offset            = 0;

            for (int i = 0; i < bufferCopyRegions.Length; i++)
            {
                bufferCopyRegions = new[]
                {
                    new BufferImageCopy
                    {
                        ImageSubresource = new ImageSubresourceLayers(ImageAspects.Color, i, 0, 1),
                        ImageExtent      = tex2D.Mipmaps[0].Extent,
                        BufferOffset     = offset
                    }
                };
                offset += tex2D.Mipmaps[i].Size;
            }

            // Create optimal tiled target image.
            Image image = ctx.Device.CreateImage(new ImageCreateInfo
            {
                ImageType     = ImageType.Image2D,
                Format        = tex2D.Format,
                MipLevels     = tex2D.Mipmaps.Length,
                ArrayLayers   = 1,
                Samples       = SampleCounts.Count1,
                Tiling        = ImageTiling.Optimal,
                SharingMode   = SharingMode.Exclusive,
                InitialLayout = ImageLayout.Undefined,
                Extent        = tex2D.Mipmaps[0].Extent,
                Usage         = ImageUsages.Sampled | ImageUsages.TransferDst
            });
            MemoryRequirements imageMemReq = image.GetMemoryRequirements();
            int imageHeapIndex             = ctx.MemoryProperties.MemoryTypes.IndexOf(
                imageMemReq.MemoryTypeBits, MemoryProperties.DeviceLocal);
            DeviceMemory memory = ctx.Device.AllocateMemory(new MemoryAllocateInfo(imageMemReq.Size, imageHeapIndex));

            image.BindMemory(memory);

            var subresourceRange = new ImageSubresourceRange(ImageAspects.Color, 0, tex2D.Mipmaps.Length, 0, 1);

            // Copy the data from staging buffers to device local buffers.
            CommandBuffer cmdBuffer = ctx.GraphicsCommandPool.AllocateBuffers(new CommandBufferAllocateInfo(CommandBufferLevel.Primary, 1))[0];

            cmdBuffer.Begin(new CommandBufferBeginInfo(CommandBufferUsages.OneTimeSubmit));
            cmdBuffer.CmdPipelineBarrier(PipelineStages.TopOfPipe, PipelineStages.Transfer,
                                         imageMemoryBarriers: new[]
            {
                new ImageMemoryBarrier(
                    image, subresourceRange,
                    0, Accesses.TransferWrite,
                    ImageLayout.Undefined, ImageLayout.TransferDstOptimal)
            });
            cmdBuffer.CmdCopyBufferToImage(stagingBuffer, image, ImageLayout.TransferDstOptimal, bufferCopyRegions);
            cmdBuffer.CmdPipelineBarrier(PipelineStages.Transfer, PipelineStages.FragmentShader,
                                         imageMemoryBarriers: new[]
            {
                new ImageMemoryBarrier(
                    image, subresourceRange,
                    Accesses.TransferWrite, Accesses.ShaderRead,
                    ImageLayout.TransferDstOptimal, ImageLayout.ShaderReadOnlyOptimal)
            });
            cmdBuffer.End();

            // Submit.
            Fence fence = ctx.Device.CreateFence();

            ctx.GraphicsQueue.Submit(new SubmitInfo(commandBuffers: new[] { cmdBuffer }), fence);
            fence.Wait();

            // Cleanup staging resources.
            fence.Dispose();
            stagingMemory.Dispose();
            stagingBuffer.Dispose();

            // Create image view.
            ImageView view = image.CreateView(new ImageViewCreateInfo(tex2D.Format, subresourceRange));

            var sampler = VKHelper.CreateSampler(ctx, Filter.Linear, Filter.Linear, SamplerMipmapMode.Linear);

            return(new Texture2D(ctx, image, memory, view, tex2D.Format, new Vector2I(tex2D.Mipmaps[0].Extent.Width, tex2D.Mipmaps[0].Extent.Height), false));
        }
        private void LoadAssets()
        {
            DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange() { RangeType = DescriptorRangeType.ConstantBufferView, BaseShaderRegister = 0, OffsetInDescriptorsFromTableStart = int.MinValue, DescriptorCount = 1 } };
            RootParameter parameter = new RootParameter(ShaderVisibility.Vertex, ranges);

            // Create an empty root signature.
            RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, new RootParameter[] { parameter });
            rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.
            #if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0"));
            #endif

            #if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
            #endif

            // Define the vertex input layout.
            InputElement[] inputElementDescs = new InputElement[]
            {
                    new InputElement("POSITION",0,Format.R32G32B32_Float,0,0),
                    new InputElement("COLOR",0,Format.R32G32B32A32_Float,12,0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout = new InputLayoutDescription(inputElementDescs),
                RootSignature = rootSignature,
                VertexShader = vertexShader,
                PixelShader = pixelShader,
                RasterizerState = RasterizerStateDescription.Default(),
                BlendState = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState = new DepthStencilStateDescription() { IsDepthEnabled = false, IsStencilEnabled = false },
                SampleMask = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount = 1,
                Flags = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            // Create the command list.
            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);

            // Create the vertex buffer.
            float aspectRatio = viewport.Width / viewport.Height;

            // Define the geometry for a triangle.
            Vertex[] triangleVertices = new Vertex[]
            {
                    new Vertex() {position=new Vector3(0.0f, 0.25f * aspectRatio, 0.0f ),color=new Vector4(1.0f, 0.0f, 0.0f, 1.0f ) },
                    new Vertex() {position=new Vector3(0.25f, -0.25f * aspectRatio, 0.0f),color=new Vector4(0.0f, 1.0f, 0.0f, 1.0f) },
                    new Vertex() {position=new Vector3(-0.25f, -0.25f * aspectRatio, 0.0f),color=new Vector4(0.0f, 0.0f, 1.0f, 1.0f ) },
            };

            int vertexBufferSize = Utilities.SizeOf(triangleVertices);

            // Note: using upload heaps to transfer static data like vert buffers is not
            // recommended. Every time the GPU needs it, the upload heap will be marshalled
            // over. Please read up on Default Heap usage. An upload heap is used here for
            // code simplicity and because there are very few verts to actually transfer.
            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length);
            vertexBuffer.Unmap(0);

            // Initialize the vertex buffer view.
            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes = Utilities.SizeOf<Vertex>();
            vertexBufferView.SizeInBytes = vertexBufferSize;

            // Command lists are created in the recording state, but there is nothing
            // to record yet. The main loop expects it to be closed, so close it now.
            commandList.Close();

            constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead);

            //// Describe and create a constant buffer view.
            ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription()
            {
                BufferLocation = constantBuffer.GPUVirtualAddress,
                SizeInBytes = (Utilities.SizeOf<ConstantBuffer>() + 255) & ~255
            };
            device.CreateConstantBufferView(cbvDesc, constantBufferViewHeap.CPUDescriptorHandleForHeapStart);

            // Initialize and map the constant buffers. We don't unmap this until the
            // app closes. Keeping things mapped for the lifetime of the resource is okay.
            constantBufferPointer = constantBuffer.Map(0);
            Utilities.Write(constantBufferPointer, ref constantBufferData);

            // Create synchronization objects.
            fence = device.CreateFence(0, FenceFlags.None);
            fenceValue = 1;

            // Create an event handle to use for frame synchronization.
            fenceEvent = new AutoResetEvent(false);
        }
Exemplo n.º 20
0
        private static void InitialiseRotationAndBounds(AreaControlSet areaControlSet,
                                                        double subGridMinX, double subGridMinY, double subGridMaxX, double subGridMaxY,
                                                        out int numRowsToScan, out int numColsToScan,
                                                        out double stepNorthX, out double stepNorthY, out double stepEastX, out double stepEastY,
                                                        out double firstScanPointEast, out double firstScanPointNorth)
        {
            var stepX = areaControlSet.PixelXWorldSize;
            var stepY = areaControlSet.PixelYWorldSize;

            // Take into account the effect of having to have a grid probe position at
            // the 'first point' defined in areaControlSet
            // Calculate the intra-interval offset that needs to be applied to align the
            // skip-stepping to that modified grid search
            var intraGridOffsetX = areaControlSet.UserOriginX - (Math.Floor(areaControlSet.UserOriginX / stepX) * stepX);
            var intraGridOffsetY = areaControlSet.UserOriginY - (Math.Floor(areaControlSet.UserOriginY / stepY) * stepY);

            if (areaControlSet.Rotation != Consts.NullDouble && areaControlSet.Rotation != 0) // Radians, north azimuth survey angle
            {
                var rotatedSubGridBoundary = new Fence();

                // Create the rotated boundary by 'un-rotating' the sub grid world extents into a context
                // where the grid is itself not rotated
                GeometryHelper.RotatePointAbout(areaControlSet.Rotation, subGridMinX, subGridMinY, out var x, out var y, areaControlSet.UserOriginX, areaControlSet.UserOriginY);
                rotatedSubGridBoundary.Points.Add(new FencePoint(x, y));
                GeometryHelper.RotatePointAbout(areaControlSet.Rotation, subGridMinX, subGridMaxY, out x, out y, areaControlSet.UserOriginX, areaControlSet.UserOriginY);
                rotatedSubGridBoundary.Points.Add(new FencePoint(x, y));
                GeometryHelper.RotatePointAbout(areaControlSet.Rotation, subGridMaxX, subGridMaxY, out x, out y, areaControlSet.UserOriginX, areaControlSet.UserOriginY);
                rotatedSubGridBoundary.Points.Add(new FencePoint(x, y));
                GeometryHelper.RotatePointAbout(areaControlSet.Rotation, subGridMaxX, subGridMinY, out x, out y, areaControlSet.UserOriginX, areaControlSet.UserOriginY);
                rotatedSubGridBoundary.Points.Add(new FencePoint(x, y));

                rotatedSubGridBoundary.UpdateExtents();
                firstScanPointEast  = Math.Truncate(rotatedSubGridBoundary.MinX / stepX) * stepX + intraGridOffsetX;
                firstScanPointNorth = Math.Truncate(rotatedSubGridBoundary.MinY / stepY) * stepY + intraGridOffsetY;

                numRowsToScan = (int)Math.Ceiling((rotatedSubGridBoundary.MaxY - firstScanPointNorth) / stepY) + 1;
                numColsToScan = (int)Math.Ceiling((rotatedSubGridBoundary.MaxX - firstScanPointEast) / stepX) + 1;

                // Rotate the first scan point back to the context of the grid projection north oriented
                // sub grid world extents
                GeometryHelper.RotatePointAbout(-areaControlSet.Rotation, firstScanPointEast, firstScanPointNorth, out firstScanPointEast,
                                                out firstScanPointNorth, areaControlSet.UserOriginX, areaControlSet.UserOriginY);

                // Perform a 'unit' rotation of the StepX and StepY quantities about the
                // origin to define step quantities that orient the vector of probe position movement
                // to the rotated probe grid
                var sinOfRotation = Math.Sin(areaControlSet.Rotation);
                var cosOfRotation = Math.Cos(areaControlSet.Rotation);

                stepNorthY = cosOfRotation * stepY;
                stepNorthX = sinOfRotation * stepX;
                stepEastX  = cosOfRotation * stepX;
                stepEastY  = -sinOfRotation * stepY;
            }
            else
            {
                firstScanPointEast  = Math.Truncate(subGridMinX / stepX) * stepX + intraGridOffsetX;
                firstScanPointNorth = Math.Truncate(subGridMinY / stepY) * stepY + intraGridOffsetY;

                numRowsToScan = (int)Math.Ceiling((subGridMaxY - firstScanPointNorth) / stepY) + 1;
                numColsToScan = (int)Math.Ceiling((subGridMaxX - firstScanPointEast) / stepX) + 1;

                stepNorthX = 0;
                stepNorthY = stepY;
                stepEastX  = stepX;
                stepEastY  = 0;
            }
        }
        private void LoadAssets()
        {
            // Create the root signature description.
            var rootSignatureDesc = new RootSignatureDescription(
                RootSignatureFlags.AllowInputAssemblerInputLayout,
                // Root Parameters
                new[]
                {
                    new RootParameter(ShaderVisibility.All,
                        new []
                        {
                            new DescriptorRange()
                            {
                                RangeType = DescriptorRangeType.ConstantBufferView,
                                DescriptorCount = 1,
                                OffsetInDescriptorsFromTableStart = 0,
                                BaseShaderRegister = 0
                            }
                        }),
                    new RootParameter(ShaderVisibility.All,
                        new RootConstants() {
                            ShaderRegister = 1,
                            Value32BitCount = 1
                        }),
                    new RootParameter(ShaderVisibility.All,
                        new []
                        {
                            new DescriptorRange()
                            {
                                RangeType = DescriptorRangeType.ShaderResourceView,
                                DescriptorCount = 2,
                                OffsetInDescriptorsFromTableStart = 0,
                                BaseShaderRegister = 0
                            }
                        }),
                    new RootParameter(ShaderVisibility.Pixel,
                        new DescriptorRange()
                        {
                            RangeType = DescriptorRangeType.Sampler,
                            DescriptorCount = 1,
                            OffsetInDescriptorsFromTableStart = 0,
                            BaseShaderRegister = 0
                        }),
                });

            rootSignature = device.CreateRootSignature(0, rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));

            // Define the vertex input layout.
            var inputElementDescs = new[]
            {
                    new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                    new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
                    new InputElement("TANGENT", 0, Format.R32G32B32_Float, 24, 0),
                    new InputElement("BITANGENT", 0, Format.R32G32B32_Float, 36, 0),
                    new InputElement("DIFFUSE", 0, Format.R32G32B32_Float, 48, 0),
                    new InputElement("EMISSIVE", 0, Format.R32G32B32_Float, 64, 0),
                    new InputElement("SPECULAR", 0, Format.R32G32B32_Float, 80, 0),
                    new InputElement("TEXCOORD", 0, Format.R32G32_Float, 96, 0)
            };

            CreatePSO(inputElementDescs, vertexShader, pixelShader);

            // build model resources
            BuildModelResources();

            // build depth buffer
            BuildDepthBuffer();

            CreateTerrainBind();
            BuildTerrainResouces();

            fence = device.CreateFence(0, FenceFlags.None);
            fenceValue = 1;
            fenceEvent = new AutoResetEvent(false);
        }
        private void LoadAssets()
        {
            // Create the root signature description.
            var rootSignatureDesc = new RootSignatureDescription(

                RootSignatureFlags.AllowInputAssemblerInputLayout,
                // Root Parameters
                new[]
                {
                    new RootParameter(ShaderVisibility.All,
                        new []
                        {
                            new DescriptorRange()
                            {
                                RangeType = DescriptorRangeType.ShaderResourceView,
                                DescriptorCount = 1,
                                OffsetInDescriptorsFromTableStart = int.MinValue,
                                BaseShaderRegister = 0
                            },
                            new DescriptorRange()
                            {
                                RangeType = DescriptorRangeType.ConstantBufferView,
                                DescriptorCount = 1,
                                OffsetInDescriptorsFromTableStart = int.MinValue + 1,
                                BaseShaderRegister = 0
                            }
                        }),
                    new RootParameter(ShaderVisibility.Pixel,
                        new DescriptorRange()
                        {
                            RangeType = DescriptorRangeType.Sampler,
                            DescriptorCount = 1,
                            OffsetInDescriptorsFromTableStart = int.MinValue,
                            BaseShaderRegister = 0
                        }),
                });
                //// Samplers
                //new[]
                //{
                //    new StaticSamplerDescription(ShaderVisibility.Pixel, 0, 0)
                //    {
                //        Filter = Filter.MinimumMinMagMipPoint,
                //        AddressUVW = TextureAddressMode.Border,
                //    }
                //});

            rootSignature = device.CreateRootSignature(0, rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.
            #if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0"));
            #endif

            #if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
            #endif

            #if DEBUG
            //var result = SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "GSMain", "gs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug);
            var geometryShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "GSMain", "gs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
            #endif

            // Define the vertex input layout.
            var inputElementDescs = new[]
            {
                    new InputElement("POSITION",0,Format.R32G32B32_Float,0,0),
                    new InputElement("TEXCOORD",0,Format.R32G32_Float,12,0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            var psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout = new InputLayoutDescription(inputElementDescs),
                RootSignature = rootSignature,
                VertexShader = vertexShader,
                GeometryShader = geometryShader,
                PixelShader = pixelShader,
                RasterizerState = RasterizerStateDescription.Default(),
                BlendState = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = true,
                    DepthComparison = Comparison.LessEqual,
                    DepthWriteMask = DepthWriteMask.All,
                    IsStencilEnabled = false
                },
                SampleMask = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount = 1,
                Flags = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);
            commandList.Close();

            // build vertex buffer

            var triangleVertices = new[]
            {
                //TOP
                new Vertex() {Position = new Vector3(-1f , 1f , 1f) , TexCoord = new Vector2(1f ,1f)} ,
                new Vertex() {Position = new Vector3(1f , 1f , 1f) , TexCoord = new Vector2(0f ,1f)} ,
                new Vertex() {Position = new Vector3(1f , 1f ,-1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(-1f , 1f ,-1f) , TexCoord = new Vector2(1f ,0f)} ,
                //BOTTOM
                new Vertex() {Position = new Vector3(-1f ,-1f , 1f) , TexCoord = new Vector2(1f ,1f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f , 1f) , TexCoord = new Vector2(0f ,1f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f ,-1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(-1f ,-1f ,-1f) , TexCoord = new Vector2(1f ,0f)} ,
                //LEFT
                new Vertex() {Position = new Vector3(-1f ,-1f , 1f) , TexCoord = new Vector2(0f ,1f)} ,
                new Vertex() {Position = new Vector3(-1f , 1f , 1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(-1f , 1f ,-1f) , TexCoord = new Vector2(1f ,0f)} ,
                new Vertex() {Position = new Vector3(-1f ,-1f ,-1f) , TexCoord = new Vector2(1f ,1f)} ,
                //RIGHT
                new Vertex() {Position = new Vector3(1f ,-1f , 1f) , TexCoord = new Vector2(1f ,1f)} ,
                new Vertex() {Position = new Vector3(1f , 1f , 1f) , TexCoord = new Vector2(1f ,0f)} ,
                new Vertex() {Position = new Vector3(1f , 1f ,-1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f ,-1f) , TexCoord = new Vector2(0f ,1f)} ,
                //FRONT
                new Vertex() {Position = new Vector3(-1f , 1f , 1f) , TexCoord = new Vector2(1f ,0f)} ,
                new Vertex() {Position = new Vector3(1f , 1f , 1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f , 1f) , TexCoord = new Vector2(0f ,1f)} ,
                new Vertex() {Position = new Vector3(-1f ,-1f , 1f) , TexCoord = new Vector2(1f ,1f)} ,
                //BACK
                new Vertex() {Position = new Vector3(-1f , 1f ,-1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(1f , 1f ,-1f) , TexCoord = new Vector2(1f ,0f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f ,-1f) , TexCoord = new Vector2(1f ,1f)} ,
                new Vertex() {Position = new Vector3(-1f ,-1f ,-1f) , TexCoord = new Vector2(0f ,1f)}
            };

            int vertexBufferSize = Utilities.SizeOf(triangleVertices);

            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length);
            vertexBuffer.Unmap(0);

            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes = Utilities.SizeOf<Vertex>();
            vertexBufferView.SizeInBytes = vertexBufferSize;

            // build index buffer

            var triangleIndexes = new uint[]
            {
                0,1,2,
                0,2,3,

                4,6,5,
                4,7,6,

                8,9,10,
                8,10,11,

                12,14,13,
                12,15,14,

                16,18,17,
                16,19,18,

                20,21,22,
                20,22,23
            };

            int indexBufferSize = Utilities.SizeOf(triangleIndexes);

            indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indexBufferSize), ResourceStates.GenericRead);
            IntPtr pIndexDataBegin = indexBuffer.Map(0);
            Utilities.Write(pIndexDataBegin, triangleIndexes, 0, triangleIndexes.Length);
            indexBuffer.Unmap(0);

            indexBufferView = new IndexBufferView();
            indexBufferView.BufferLocation = indexBuffer.GPUVirtualAddress;
            indexBufferView.SizeInBytes = indexBufferSize;
            indexBufferView.Format = Format.R32_UInt;

            // Create the texture.
            // Describe and create a Texture2D.
            var textureDesc = ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, TextureWidth, TextureHeight, 1, 1, 1, 0, ResourceFlags.None, TextureLayout.Unknown, 0);
            texture = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, textureDesc, ResourceStates.GenericRead, null);

            // Copy data to the intermediate upload heap and then schedule a copy
            // from the upload heap to the Texture2D.
            byte[] textureData = Utilities.ReadStream(new FileStream("../../texture1.dds", FileMode.Open));

            texture.Name = "Texture";

            var handle = GCHandle.Alloc(textureData, GCHandleType.Pinned);
            var ptr = Marshal.UnsafeAddrOfPinnedArrayElement(textureData, 0);
            texture.WriteToSubresource(0, null, ptr, TextureWidth * 4, textureData.Length);
            handle.Free();

            // Describe and create a SRV for the texture.
            var srvDesc = new ShaderResourceViewDescription
            {
                Shader4ComponentMapping = ((((0) & 0x7) |(((1) & 0x7) << 3) |(((2) & 0x7) << (3 * 2)) |(((3) & 0x7) << (3 * 3)) | (1 << (3 * 4)))),

                Format = textureDesc.Format,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D =
                {
                    MipLevels = 1,
                    MostDetailedMip = 0,
                    PlaneSlice = 0,
                    ResourceMinLODClamp = 0.0f
                },
            };

            device.CreateShaderResourceView(texture, srvDesc, srvCbvHeap.CPUDescriptorHandleForHeapStart);

            SamplerStateDescription samplerDesc = new SamplerStateDescription
            {
                Filter = Filter.MinMagMipLinear,
                AddressU = TextureAddressMode.Clamp,
                AddressV = TextureAddressMode.Clamp,
                AddressW = TextureAddressMode.Clamp,
                MaximumAnisotropy = 0,
                MaximumLod = float.MaxValue,
                MinimumLod = -float.MaxValue,
                MipLodBias = 0,
                ComparisonFunction = Comparison.Never
            };

            device.CreateSampler(samplerDesc, samplerViewHeap.CPUDescriptorHandleForHeapStart);

            // build constant buffer

            constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead);

            var cbDesc = new ConstantBufferViewDescription()
            {
                BufferLocation = constantBuffer.GPUVirtualAddress,
                SizeInBytes = (Utilities.SizeOf<ConstantBufferData>() + 255) & ~255
            };
            var srvCbvStep = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
            device.CreateConstantBufferView(cbDesc, srvCbvHeap.CPUDescriptorHandleForHeapStart + srvCbvStep);

            constantBufferData = new ConstantBufferData
            {
                Project = Matrix.Identity
            };

            constantBufferPointer = constantBuffer.Map(0);
            Utilities.Write(constantBufferPointer, ref constantBufferData);

            // build depth buffer

            DescriptorHeapDescription descDescriptorHeapDSB = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Type = DescriptorHeapType.DepthStencilView,
                Flags = DescriptorHeapFlags.None
            };

            DescriptorHeap descriptorHeapDSB = device.CreateDescriptorHeap(descDescriptorHeapDSB);
            ResourceDescription descDepth = new ResourceDescription()
            {
                Dimension = ResourceDimension.Texture2D,
                DepthOrArraySize = 1,
                MipLevels = 0,
                Flags = ResourceFlags.AllowDepthStencil,
                Width = (int)viewport.Width,
                Height = (int)viewport.Height,
                Format = Format.R32_Typeless,
                Layout = TextureLayout.Unknown,
                SampleDescription = new SampleDescription() { Count = 1 }
            };

            ClearValue dsvClearValue = new ClearValue()
            {
                Format = Format.D32_Float,
                DepthStencil = new DepthStencilValue()
                {
                    Depth = 1.0f,
                    Stencil = 0
                }
            };

            Resource renderTargetDepth = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, descDepth, ResourceStates.GenericRead, dsvClearValue);

            DepthStencilViewDescription depthDSV = new DepthStencilViewDescription()
            {
                Dimension = DepthStencilViewDimension.Texture2D,
                Format = Format.D32_Float,
                Texture2D = new DepthStencilViewDescription.Texture2DResource()
                {
                    MipSlice = 0
                }
            };

            device.CreateDepthStencilView(renderTargetDepth, depthDSV, descriptorHeapDSB.CPUDescriptorHandleForHeapStart);
            handleDSV = descriptorHeapDSB.CPUDescriptorHandleForHeapStart;

            fence = device.CreateFence(0, FenceFlags.None);
            fenceValue = 1;
            fenceEvent = new AutoResetEvent(false);
        }
Exemplo n.º 23
0
        private void LoadAssets()
        {
            // Create the descriptor heap for the render target view
            descriptorHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription()
            {
                Type = DescriptorHeapType.RenderTargetView,
                DescriptorCount = 1
            });

            // Create the main command list
            commandList = device.CreateCommandList(CommandListType.Direct, commandListAllocator, null);

            // Get the backbuffer and creates the render target view
            renderTarget = swapChain.GetBackBuffer<Resource>(0);
            device.CreateRenderTargetView(renderTarget, null, descriptorHeap.CPUDescriptorHandleForHeapStart);

            // Create the viewport
            viewPort = new ViewportF(0, 0, width, height);

            // Create the scissor
            scissorRectangle = new Rectangle(0, 0, width, height);

            // Create a fence to wait for next frame
            fence = device.CreateFence(0, FenceFlags.None);
            currentFence = 1;

            // Close command list
            commandList.Close();

            // Create an event handle use for VTBL
            eventHandle = new AutoResetEvent(false);

            // Wait the command list to complete
            WaitForPrevFrame();
        }
Exemplo n.º 24
0
 internal static unsafe extern void vkDestroyFence(Device device, Fence fence, AllocationCallbacks* allocator);
Exemplo n.º 25
0
 internal static unsafe extern Result vkAcquireNextImageKHR(Device device, Swapchain swapchain, ulong timeout, Semaphore semaphore, Fence fence, uint* imageIndex);
Exemplo n.º 26
0
 internal static unsafe extern Result vkGetFenceStatus(Device device, Fence fence);
Exemplo n.º 27
0
        /// <param name="DrawStack">True if <see cref="Item.Stack"/> should be drawn</param>
        /// <param name="DrawQuality">True if <see cref="Object.Quality"/> should be drawn</param>
        /// <param name="IconScale">Does not affect the scaling for the quality, quantity, or other special rendered things like the capacity bar for a watering can</param>
        public static void DrawItem(SpriteBatch b, Rectangle Destination, Item Item, bool DrawStack, bool DrawQuality, float IconScale, float Transparency, Color Overlay, Color StackColor)
        {
            if (Destination.Width != Destination.Height)
            {
                throw new InvalidOperationException("Can only call DrawItem on a perfect square Destination");
            }

            //  Normally I'd just use Item.drawInMenu but that method doesn't scale stack size, qualities, or shadows correctly and thus will only display correctly at the default size of 64x64.
            //  Some items also render several textures to the destination point, and use hardcoded offsets for the sprites that also don't respect desired scaling. (Such as wallpapers or watering cans)
            //  So this method is my attempt at re-creating the Item.drawInMenu implementations in a way that will correctly scale to the desired Destination rectangle.
            //  It doesn't handle all cases correctly, but whatever, it's close enough

            DrawStack   = DrawStack && (Item.maximumStackSize() > 1 || Item.Stack > 1);
            DrawQuality = DrawQuality && Item is Object Obj && Enum.IsDefined(typeof(ObjectQuality), Obj.Quality);

            int       ScaledIconSize        = (int)(Destination.Width * IconScale * 0.8f);
            Rectangle ScaledIconDestination = new Rectangle(Destination.Center.X - ScaledIconSize / 2, Destination.Center.Y - ScaledIconSize / 2, ScaledIconSize, ScaledIconSize);

            Texture2D SourceTexture          = null;
            Rectangle?SourceTextureRectangle = null;

            if (Item is ItemBag Bag)
            {
                float   BaseScale          = Destination.Width / (float)BagInventoryMenu.DefaultInventoryIconSize;
                Vector2 OffsetDueToScaling = new Vector2((BaseScale - 1.0f) * BagInventoryMenu.DefaultInventoryIconSize * 0.5f); // I honestly forget why I needed this lmao. Maybe ItemBag.drawInMenu override was scaling around a different origin or some shit
                Bag.drawInMenu(b, new Vector2(Destination.X, Destination.Y) + OffsetDueToScaling, IconScale * Destination.Width / 64f * 0.8f, Transparency, 1.0f, StackDrawType.Hide, Overlay, false);
            }
            else if (Item is Tool Tool)
            {
                if (Item is MeleeWeapon Weapon)
                {
                    SourceTexture          = MeleeWeapon.weaponsTexture;
                    SourceTextureRectangle = new Rectangle?(Game1.getSquareSourceRectForNonStandardTileSheet(SourceTexture, 16, 16, Tool.IndexOfMenuItemView));
                }
                else
                {
                    SourceTexture          = Game1.toolSpriteSheet;
                    SourceTextureRectangle = new Rectangle?(Game1.getSquareSourceRectForNonStandardTileSheet(SourceTexture, 16, 16, Tool.IndexOfMenuItemView));
                }
            }
            else if (Item is Ring Ring)
            {
                SourceTexture          = Game1.objectSpriteSheet;
                SourceTextureRectangle = new Rectangle?(Game1.getSourceRectForStandardTileSheet(SourceTexture, Ring.indexInTileSheet, 16, 16));
            }
            else if (Item is Hat Hat)
            {
                SourceTexture          = FarmerRenderer.hatsTexture;
                SourceTextureRectangle = new Rectangle?(new Rectangle(Hat.which * 20 % SourceTexture.Width, Hat.which * 20 / SourceTexture.Width * 20 * 4, 20, 20));
            }
            else if (Item is Boots Boots)
            {
                SourceTexture          = Game1.objectSpriteSheet;
                SourceTextureRectangle = new Rectangle?(Game1.getSourceRectForStandardTileSheet(SourceTexture, Boots.indexInTileSheet.Value, 16, 16));
            }
            else if (Item is Clothing Clothing)
            {
                Color clothes_color = Clothing.clothesColor;
                if (Clothing.isPrismatic.Value)
                {
                    clothes_color = Utility.GetPrismaticColor(0);
                }
                if (Clothing.clothesType.Value != 0)
                {
                    if (Clothing.clothesType.Value == 1)
                    {
                        b.Draw(FarmerRenderer.pantsTexture, Destination,
                               new Rectangle?(new Rectangle(192 * (Clothing.indexInTileSheetMale.Value % (FarmerRenderer.pantsTexture.Width / 192)), 688 * (Clothing.indexInTileSheetMale.Value / (FarmerRenderer.pantsTexture.Width / 192)) + 672, 16, 16)),
                               Utility.MultiplyColor(clothes_color, Color.White) * Transparency, 0f, Vector2.Zero, SpriteEffects.None, 1f);
                        //b.Draw(FarmerRenderer.pantsTexture, location + new Vector2(32f, 32f),
                        //new Rectangle?(new Rectangle(192 * (this.indexInTileSheetMale.Value % (FarmerRenderer.pantsTexture.Width / 192)), 688 * (this.indexInTileSheetMale.Value / (FarmerRenderer.pantsTexture.Width / 192)) + 672, 16, 16)),
                        //Utility.MultiplyColor(clothes_color, color) * transparency, 0f, new Vector2(8f, 8f), scaleSize * 4f, SpriteEffects.None, layerDepth);
                    }
                }
                else
                {
                    b.Draw(FarmerRenderer.shirtsTexture, Destination,
                           new Rectangle?(new Rectangle(Clothing.indexInTileSheetMale.Value * 8 % 128, Clothing.indexInTileSheetMale.Value * 8 / 128 * 32, 8, 8)),
                           Color.White * Transparency, 0f, Vector2.Zero, SpriteEffects.None, 1f);
                    b.Draw(FarmerRenderer.shirtsTexture, Destination,
                           new Rectangle?(new Rectangle(Clothing.indexInTileSheetMale.Value * 8 % 128 + 128, Clothing.indexInTileSheetMale.Value * 8 / 128 * 32, 8, 8)),
                           Utility.MultiplyColor(clothes_color, Color.White) * Transparency, 0f, Vector2.Zero, SpriteEffects.None, 1f);
                    //b.Draw(FarmerRenderer.shirtsTexture, location + new Vector2(32f, 32f), new Rectangle?(new Rectangle(this.indexInTileSheetMale.Value * 8 % 128, this.indexInTileSheetMale.Value * 8 / 128 * 32, 8, 8)), color * transparency, 0f, new Vector2(4f, 4f), scaleSize * 4f, SpriteEffects.None, layerDepth);
                    //b.Draw(FarmerRenderer.shirtsTexture, location + new Vector2(32f, 32f), new Rectangle?(new Rectangle(this.indexInTileSheetMale.Value * 8 % 128 + 128, this.indexInTileSheetMale.Value * 8 / 128 * 32, 8, 8)), Utility.MultiplyColor(clothes_color, color) * transparency, 0f, new Vector2(4f, 4f), scaleSize * 4f, SpriteEffects.None, layerDepth + dye_portion_layer_offset);
                }
            }
            else if (Item is Fence Fence)
            {
                int DrawSum            = Fence.getDrawSum(Game1.currentLocation);
                int SourceRectPosition = Fence.fenceDrawGuide[DrawSum];
                SourceTexture = Fence.fenceTexture.Value;
                if (Fence.isGate)
                {
                    if (DrawSum == 110)
                    {
                        SourceTextureRectangle = new Rectangle?(new Rectangle(0, 512, 88, 24));
                    }
                    else if (DrawSum == 1500)
                    {
                        SourceTextureRectangle = new Rectangle?(new Rectangle(112, 512, 16, 64));
                    }
                }
                SourceTextureRectangle = new Rectangle?(Game1.getArbitrarySourceRect(SourceTexture, 64, 128, SourceRectPosition));
            }
            else if (Item is Furniture Furniture)
            {
                SourceTexture          = Furniture.furnitureTexture;
                SourceTextureRectangle = Furniture.defaultSourceRect;
            }
            else if (Item is Wallpaper WP)
            {
                SourceTexture          = Wallpaper.wallpaperTexture;
                SourceTextureRectangle = WP.sourceRect;
            }
            else
            {
                if (Item is Object BigCraftable && BigCraftable.bigCraftable.Value)
                {
                    SourceTexture          = Game1.bigCraftableSpriteSheet;
                    SourceTextureRectangle = Object.getSourceRectForBigCraftable(Item.ParentSheetIndex);
                    //ScaledIconDestination = new Rectangle(ScaledIconDestination.X + ScaledIconDestination.Width / 8, ScaledIconDestination.Y - ScaledIconDestination.Height / 8,
                    //    ScaledIconDestination.Width - ScaledIconDestination.Width / 4, ScaledIconDestination.Height + ScaledIconDestination.Height / 4);
                    ScaledIconDestination = new Rectangle(ScaledIconDestination.X + ScaledIconDestination.Width / 4, ScaledIconDestination.Y,
                                                          ScaledIconDestination.Width - ScaledIconDestination.Width / 2, ScaledIconDestination.Height);
                    //From decompiled .exe code:
                    //spriteBatch.Draw(Game1.bigCraftableSpriteSheet, location + new Vector2(32f, 32f), new Rectangle?(sourceRect), color * transparency,
                    //    0f, new Vector2(8f, 16f), 4f * ((double)scaleSize < 0.2 ? scaleSize : scaleSize / 2f), SpriteEffects.None, layerDepth);
                }
Exemplo n.º 28
0
 internal static unsafe extern Result vkResetFences(Device device, uint fenceCount, Fence* fences);
Exemplo n.º 29
0
 public override void ResetFence(Fence fence)
 {
     Util.AssertSubtype <Fence, MTLFence>(fence).Reset();
 }
Exemplo n.º 30
0
 internal static unsafe extern Result vkWaitForFences(Device device, uint fenceCount, Fence* fences, RawBool waitAll, ulong timeout);
Exemplo n.º 31
0
        public unsafe void Copy_Compressed_Array(bool separateLayerCopies)
        {
            PixelFormat format = PixelFormat.BC3_UNorm;

            if (!GD.GetPixelFormatSupport(format, TextureType.Texture2D, TextureUsage.Sampled))
            {
                return;
            }

            TextureDescription texDesc = TextureDescription.Texture2D(
                16, 16,
                1, 4,
                format,
                TextureUsage.Sampled);

            Texture copySrc = RF.CreateTexture(texDesc);

            texDesc.Usage = TextureUsage.Staging;
            Texture copyDst = RF.CreateTexture(texDesc);

            for (uint layer = 0; layer < copySrc.ArrayLayers; layer++)
            {
                int    byteCount = 16 * 16;
                byte[] data      = Enumerable.Range(0, byteCount).Select(i => (byte)(i + layer)).ToArray();
                GD.UpdateTexture(
                    copySrc,
                    data,
                    0, 0, 0,
                    16, 16, 1,
                    0, layer);
            }

            CommandList copyCL = RF.CreateCommandList();

            copyCL.Begin();
            if (separateLayerCopies)
            {
                for (uint layer = 0; layer < copySrc.ArrayLayers; layer++)
                {
                    copyCL.CopyTexture(copySrc, 0, 0, 0, 0, layer, copyDst, 0, 0, 0, 0, layer, 16, 16, 1, 1);
                }
            }
            else
            {
                copyCL.CopyTexture(copySrc, 0, 0, 0, 0, 0, copyDst, 0, 0, 0, 0, 0, 16, 16, 1, copySrc.ArrayLayers);
            }
            copyCL.End();
            Fence fence = RF.CreateFence(false);

            GD.SubmitCommands(copyCL, fence);
            GD.WaitForFence(fence);

            for (uint layer = 0; layer < copyDst.ArrayLayers; layer++)
            {
                MappedResource map     = GD.Map(copyDst, MapMode.Read, layer);
                byte *         basePtr = (byte *)map.Data;

                int  index   = 0;
                uint rowSize = 64;
                uint numRows = 4;
                for (uint row = 0; row < numRows; row++)
                {
                    byte *rowBase = basePtr + (row * map.RowPitch);
                    for (uint x = 0; x < rowSize; x++)
                    {
                        Assert.Equal((byte)(index + layer), rowBase[x]);
                        index += 1;
                    }
                }

                GD.Unmap(copyDst, layer);
            }
        }
Exemplo n.º 32
0
 public unsafe void BindSparse(uint bindInfoCount, BindSparseInfo* bindInfo, Fence fence)
 {
     vkQueueBindSparse(this, bindInfoCount, bindInfo, fence).CheckError();
 }
Exemplo n.º 33
0
 public override bool HitFence( Fence hitter )
 {
     hitter.Move( Owner.Speed * 2, Owner.RelativeAngle );
     return true;
 }
Exemplo n.º 34
0
 public unsafe void Submit(uint submitCount, SubmitInfo* submits, Fence fence)
 {
     vkQueueSubmit(this, submitCount, submits, fence).CheckError();
 }
Exemplo n.º 35
0
 public override bool WaitForFence(Fence fence, ulong nanosecondTimeout)
 {
     return(Util.AssertSubtype <Fence, MTLFence>(fence).Wait(nanosecondTimeout));
 }
Exemplo n.º 36
0
 internal static unsafe extern Result vkQueueBindSparse(Queue queue, uint bindInfoCount, BindSparseInfo* bindInfo, Fence fence);
        private void InitBundles()
        {
            // Create and record the bundle.
            bundle = device.CreateCommandList(0, CommandListType.Bundle, bundleAllocator, pipelineState);
            bundle.SetGraphicsRootSignature(rootSignature);
            bundle.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;
            bundle.SetVertexBuffer(0, vertexBufferView);
            bundle.SetIndexBuffer(indexBufferView);

            bundle.SetDescriptorHeaps(1, new DescriptorHeap[] { constantBufferViewHeap });

            //first cube
            GpuDescriptorHandle heapStart = constantBufferViewHeap.GPUDescriptorHandleForHeapStart;

            for (int i = 0; i < NumCubes; i++)
            {
                bundle.SetGraphicsRootDescriptorTable(0, heapStart);
                bundle.DrawIndexedInstanced(36, 1, 0, 0, 0);
                heapStart += constantBufferDescriptorSize;
            }

            bundle.Close();

            // Create synchronization objects.
            {
                fence = device.CreateFence(0, FenceFlags.None);
                fenceValue = 1;

                // Create an event handle to use for frame synchronization.
                fenceEvent = new AutoResetEvent(false);
            }
        }
Exemplo n.º 38
0
 internal static unsafe extern Result vkQueueSubmit(Queue queue, uint submitCount, SubmitInfo* submits, Fence fence);
Exemplo n.º 39
0
 public unsafe uint AcquireNextImage(Swapchain swapchain, ulong timeout, Semaphore semaphore, Fence fence)
 {
     uint imageIndex;
     vkAcquireNextImageKHR(this, swapchain, timeout, semaphore, fence, &imageIndex).CheckError();
     return imageIndex;
 }
Exemplo n.º 40
0
 public unsafe void DestroyFence(Fence fence, AllocationCallbacks* allocator = null)
 {
     vkDestroyFence(this, fence, allocator);
 }
Exemplo n.º 41
0
        private void LoadAssets()
        {
            // Create the command list.
            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, null);

            // Command lists are created in the recording state, but there is nothing
            // to record yet. The main loop expects it to be closed, so close it now.
            commandList.Close();

            // Create synchronization objects.
            fence = device.CreateFence(0, FenceFlags.None);
            fenceValue = 1;

            // Create an event handle to use for frame synchronization.
            fenceEvent = new AutoResetEvent(false);
        }
Exemplo n.º 42
0
 public unsafe Result GetFenceStatus(Fence fence)
 {
     Result __result__;
     __result__ = vkGetFenceStatus(this, fence);
     __result__.CheckError();
     return __result__;
 }
Exemplo n.º 43
0
 public override bool Control( GameEntity control, TimeSpan gameTime, Microsoft.Xna.Framework.Input.KeyboardState keyState )
 {
     // Move angle
     angle += 5F;
     if ( angle >= 370 + orig_angle )
     {
         Owner.RemoveTankController();
     }
     else
     {
         // Put fence
         float dist = Vector2.Distance( Vector2.Zero, Owner.Origin );
         float sideDeg = 40F;
         Vector2 Pos = Position + ( new Vector2( ( float )Math.Cos( MathHelper.ToRadians( angle ) ), ( float )Math.Sin( MathHelper.ToRadians( angle ) ) ) * rad );
         Fence newFence = new Fence(
             Pos + ( new Vector2( ( float )Math.Cos( MathHelper.ToRadians( angle + sideDeg ) ), ( float )Math.Sin( MathHelper.ToRadians( angle + sideDeg ) ) ) * dist * Scale * 1.5F ),
             Pos + ( new Vector2( ( float )Math.Cos( MathHelper.ToRadians( angle - sideDeg ) ), ( float )Math.Sin( MathHelper.ToRadians( angle - sideDeg ) ) ) * dist * Scale * 1.5F ), Owner, 16, gameTime, Owner.FenceLifeTime );
         newFence.Initialize( Game );
         Game.QueueEntity( newFence );
     }
     return base.Control( control, gameTime, keyState );
 }
Exemplo n.º 44
0
 public unsafe void ResetFences(uint fenceCount, Fence* fences)
 {
     vkResetFences(this, fenceCount, fences).CheckError();
 }
Exemplo n.º 45
0
        private void LoadAssets()
        {
            // Create an empty root signature.
            var rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout);
            rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.

            #if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("shaders.hlsl"), "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0"));
            #endif

            #if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("shaders.hlsl"), "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
            #endif

            // Define the vertex input layout.
            var inputElementDescs = new []
            {
                    new InputElement("POSITION",0,Format.R32G32B32_Float,0,0),
                    new InputElement("COLOR",0,Format.R32G32B32A32_Float,12,0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            var psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout = new InputLayoutDescription(inputElementDescs),
                RootSignature = rootSignature,
                VertexShader = vertexShader,
                PixelShader = pixelShader,
                RasterizerState = RasterizerStateDescription.Default(),
                BlendState = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState = new DepthStencilStateDescription() { IsDepthEnabled = false, IsStencilEnabled = false },
                SampleMask = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount = 1,
                Flags = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            // Create the command list.
            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);

            // Command lists are created in the recording state, but there is nothing
            // to record yet. The main loop expects it to be closed, so close it now.
            commandList.Close();

            // Create the vertex buffer.
            float aspectRatio = viewport.Width / viewport.Height;

            // Define the geometry for a triangle.
            var triangleVertices = new []
            {
                    new Vertex() {Position=new Vector3(0.0f, 0.25f * aspectRatio, 0.0f ),Color=new Vector4(1.0f, 0.0f, 0.0f, 1.0f ) },
                    new Vertex() {Position=new Vector3(0.25f, -0.25f * aspectRatio, 0.0f),Color=new Vector4(0.0f, 1.0f, 0.0f, 1.0f) },
                    new Vertex() {Position=new Vector3(-0.25f, -0.25f * aspectRatio, 0.0f),Color=new Vector4(0.0f, 0.0f, 1.0f, 1.0f ) },
            };

            int vertexBufferSize = Utilities.SizeOf(triangleVertices);

            // Note: using upload heaps to transfer static data like vert buffers is not
            // recommended. Every time the GPU needs it, the upload heap will be marshalled
            // over. Please read up on Default Heap usage. An upload heap is used here for
            // code simplicity and because there are very few verts to actually transfer.
            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length);
            vertexBuffer.Unmap(0);

            // Initialize the vertex buffer view.
            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes = Utilities.SizeOf<Vertex>();
            vertexBufferView.SizeInBytes = vertexBufferSize;

            // Create and record the bundle.
            bundle = device.CreateCommandList(0, CommandListType.Bundle, bundleAllocator, pipelineState);
            bundle.SetGraphicsRootSignature(rootSignature);
            bundle.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;
            bundle.SetVertexBuffer(0, vertexBufferView);
            bundle.DrawInstanced(3, 1, 0, 0);
            bundle.Close();

            // Create synchronization objects.
            {
                fence = device.CreateFence(0, FenceFlags.None);
                fenceValue = 1;

                // Create an event handle to use for frame synchronization.
                fenceEvent = new AutoResetEvent(false);
            }
        }
Exemplo n.º 46
0
 public unsafe void WaitForFences(uint fenceCount, Fence* fences, RawBool waitAll, ulong timeout)
 {
     vkWaitForFences(this, fenceCount, fences, waitAll, timeout).CheckError();
 }
Exemplo n.º 47
0
        private void LoadAssets()
        {
            DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange() { RangeType = DescriptorRangeType.ShaderResourceView, DescriptorCount = 1, OffsetInDescriptorsFromTableStart = int.MinValue, BaseShaderRegister = 0 } };

            StaticSamplerDescription sampler = new StaticSamplerDescription()
            {
                Filter = Filter.MinimumMinMagMipPoint,
                AddressU = TextureAddressMode.Border,
                AddressV = TextureAddressMode.Border,
                AddressW = TextureAddressMode.Border,
                MipLODBias = 0,
                MaxAnisotropy = 0,
                ComparisonFunc = Comparison.Never,
                BorderColor = StaticBorderColor.TransparentBlack,
                MinLOD = 0.0f,
                MaxLOD = float.MaxValue,
                ShaderRegister = 0,
                RegisterSpace = 0,
                ShaderVisibility = ShaderVisibility.Pixel,
            };

            RootParameter[] rootParameters = new RootParameter[] { new RootParameter(ShaderVisibility.Pixel, ranges) };

            RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, rootParameters, new StaticSamplerDescription[] { sampler });
            rootSignature = device.CreateRootSignature(0, rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.
            #if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0"));
            #endif

            #if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
            #endif

            // Define the vertex input layout.
            InputElement[] inputElementDescs = new InputElement[]
            {
                    new InputElement("POSITION",0,Format.R32G32B32_Float,0,0),
                    new InputElement("TEXCOORD",0,Format.R32G32_Float,12,0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout = new InputLayoutDescription(inputElementDescs),
                RootSignature = rootSignature,
                VertexShader = vertexShader,
                PixelShader = pixelShader,
                RasterizerState = RasterizerStateDescription.Default(),
                BlendState = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState = new DepthStencilStateDescription() { IsDepthEnabled = false, IsStencilEnabled = false },
                SampleMask = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount = 1,
                Flags = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            // Create the command list.
            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);

            // Create the vertex buffer.
            float aspectRatio = viewport.Width / viewport.Height;

            // Define the geometry for a triangle.
            Vertex[] triangleVertices = new Vertex[]
            {
                    new Vertex() {position=new Vector3(0.0f, 0.25f * aspectRatio, 0.0f ),uv=new Vector2(0.5f, 0.0f) },
                    new Vertex() {position=new Vector3(0.25f, -0.25f * aspectRatio, 0.0f),uv=new Vector2(1.0f, 1.0f) },
                    new Vertex() {position=new Vector3(-0.25f, -0.25f * aspectRatio, 0.0f),uv=new Vector2(0.0f, 1.0f) },
            };

            int vertexBufferSize = Utilities.SizeOf(triangleVertices);

            // Note: using upload heaps to transfer static data like vert buffers is not
            // recommended. Every time the GPU needs it, the upload heap will be marshalled
            // over. Please read up on Default Heap usage. An upload heap is used here for
            // code simplicity and because there are very few verts to actually transfer.
            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length);
            vertexBuffer.Unmap(0);

            // Initialize the vertex buffer view.
            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes = Utilities.SizeOf<Vertex>();
            vertexBufferView.SizeInBytes = vertexBufferSize;

            Resource textureUploadHeap;

            // Create the texture.
            // Describe and create a Texture2D.
            ResourceDescription textureDesc = ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, TextureWidth, TextureHeight);
            texture = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, textureDesc, ResourceStates.CopyDestination);

            long uploadBufferSize = GetRequiredIntermediateSize(this.texture, 0, 1);

            // Create the GPU upload buffer.
            textureUploadHeap = device.CreateCommittedResource(new HeapProperties(CpuPageProperty.WriteBack, MemoryPool.L0), HeapFlags.None, ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, TextureWidth, TextureHeight), ResourceStates.GenericRead);

            // Copy data to the intermediate upload heap and then schedule a copy
            // from the upload heap to the Texture2D.
            byte[] textureData = GenerateTextureData();

            GCHandle handle = GCHandle.Alloc(textureData, GCHandleType.Pinned);
            IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement(textureData, 0);
            textureUploadHeap.WriteToSubresource(0, null, ptr, TexturePixelSize * TextureWidth, textureData.Length);
            handle.Free();

            commandList.CopyTextureRegion(new TextureCopyLocation(texture, 0), 0, 0, 0, new TextureCopyLocation(textureUploadHeap, 0), null);

            commandList.ResourceBarrierTransition(this.texture, ResourceStates.CopyDestination, ResourceStates.PixelShaderResource);

            // Describe and create a SRV for the texture.
            ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription()
            {
                Shader4ComponentMapping = D3DXUtilities.DefaultComponentMapping(),
                Format = textureDesc.Format,
                Dimension = ShaderResourceViewDimension.Texture2D,
            };
            srvDesc.Texture2D.MipLevels = 1;

            device.CreateShaderResourceView(this.texture, srvDesc, shaderRenderViewHeap.CPUDescriptorHandleForHeapStart);

            // Command lists are created in the recording state, but there is nothing
            // to record yet. The main loop expects it to be closed, so close it now.
            commandList.Close();

            commandQueue.ExecuteCommandList(commandList);

            // Create synchronization objects.
            fence = device.CreateFence(0, FenceFlags.None);
            fenceValue = 1;

            // Create an event handle to use for frame synchronization.
            fenceEvent = new AutoResetEvent(false);

            WaitForPreviousFrame();

            //release temp texture
            textureUploadHeap.Dispose();
        }
Exemplo n.º 48
0
        /// <summary>
        ///     Initializes the specified device.
        /// </summary>
        /// <param name="graphicsProfiles">The graphics profiles.</param>
        /// <param name="deviceCreationFlags">The device creation flags.</param>
        /// <param name="windowHandle">The window handle.</param>
        private void InitializePlatformDevice(GraphicsProfile[] graphicsProfiles, DeviceCreationFlags deviceCreationFlags, object windowHandle)
        {
            if (nativeDevice != null)
            {
                // Destroy previous device
                ReleaseDevice();
            }

            rendererName = Adapter.NativeAdapter.Description.Description;

            // Profiling is supported through pix markers
            IsProfilingSupported = true;

            if ((deviceCreationFlags & DeviceCreationFlags.Debug) != 0)
            {
                SharpDX.Direct3D12.DebugInterface.Get().EnableDebugLayer();
            }

            // Default fallback
            if (graphicsProfiles.Length == 0)
            {
                graphicsProfiles = new[] { GraphicsProfile.Level_11_0 }
            }
            ;

            // Create Device D3D12 with feature Level based on profile
            for (int index = 0; index < graphicsProfiles.Length; index++)
            {
                var graphicsProfile = graphicsProfiles[index];
                try
                {
                    // D3D12 supports only feature level 11+
                    var level = graphicsProfile.ToFeatureLevel();
                    if (level < SharpDX.Direct3D.FeatureLevel.Level_11_0)
                    {
                        level = SharpDX.Direct3D.FeatureLevel.Level_11_0;
                    }

                    nativeDevice = new SharpDX.Direct3D12.Device(Adapter.NativeAdapter, level);

                    RequestedProfile    = graphicsProfile;
                    CurrentFeatureLevel = level;
                    break;
                }
                catch (Exception)
                {
                    if (index == graphicsProfiles.Length - 1)
                    {
                        throw;
                    }
                }
            }

            // Describe and create the command queue.
            var queueDesc = new SharpDX.Direct3D12.CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Direct);

            NativeCommandQueue = nativeDevice.CreateCommandQueue(queueDesc);

            SrvHandleIncrementSize     = NativeDevice.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
            SamplerHandleIncrementSize = NativeDevice.GetDescriptorHandleIncrementSize(DescriptorHeapType.Sampler);

            // Prepare pools
            CommandAllocators = new CommandAllocatorPool(this);
            SrvHeaps          = new HeapPool(this, SrvHeapSize, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
            SamplerHeaps      = new HeapPool(this, SamplerHeapSize, DescriptorHeapType.Sampler);

            // Prepare descriptor allocators
            SamplerAllocator            = new DescriptorAllocator(this, DescriptorHeapType.Sampler);
            ShaderResourceViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
            DepthStencilViewAllocator   = new DescriptorAllocator(this, DescriptorHeapType.DepthStencilView);
            RenderTargetViewAllocator   = new DescriptorAllocator(this, DescriptorHeapType.RenderTargetView);

            // Prepare copy command list (start it closed, so that every new use start with a Reset)
            NativeCopyCommandAllocator = NativeDevice.CreateCommandAllocator(CommandListType.Direct);
            NativeCopyCommandList      = NativeDevice.CreateCommandList(CommandListType.Direct, NativeCopyCommandAllocator, null);
            NativeCopyCommandList.Close();

            // Fence for next frame and resource cleaning
            nativeFence = NativeDevice.CreateFence(0, FenceFlags.None);
        }