Esempio n. 1
0
        /// <summary>
        /// Sets the capacity of the vertex buffer, retaining old data. If the new buffer is smaller than the old one, the remainder will be truncated.
        /// </summary>
        /// <param name="context">Context used to perform the copy operation.</param>
        /// <param name="newCapacity">New capacity of the buffer.</param>
        public void SetCapacityWithCopy(DeviceContext context, int newCapacity)
        {
            CreateBufferForSize(newCapacity, out Buffer newBuffer, out ShaderResourceView newSRV, out UnorderedAccessView newUAV);

            //Copies data from the previous buffer to the new buffer, truncating anything which does not fit.
            context.CopySubresourceRegion(buffer, 0, new ResourceRegion(0, 0, 0, Math.Min(Capacity, newCapacity) * Stride, 1, 1), newBuffer, 0);
            buffer.Dispose();
            srv.Dispose();
            uav.Dispose();
            buffer   = newBuffer;
            srv      = newSRV;
            uav      = newUAV;
            Capacity = newCapacity;
        }
Esempio n. 2
0
 protected override void DisposeResource()
 {
     mUnorderedAccessView?.Dispose();
     mResourceView?.Dispose();
     mHardwareBuffer?.Dispose();
     mSwapBuffer?.Dispose();
 }
Esempio n. 3
0
        public ShaderResourceView GenerateNoiseTexture(Buffer constantBuffer, DirectComputeConstantBuffer container)
        {
            Texture3D noiseTexture = new Texture3D(graphicsDevice, new Texture3DDescription()
            {
                BindFlags      = BindFlags.ShaderResource | BindFlags.UnorderedAccess,
                CpuAccessFlags = CpuAccessFlags.None,
                Format         = Format.R32_Float,
                MipLevels      = 1,
                OptionFlags    = ResourceOptionFlags.None,
                Usage          = ResourceUsage.Default,
                Width          = container.Width,
                Height         = container.Height,
                Depth          = container.Depth
            });

            UnorderedAccessView noiseTextureUAV = new UnorderedAccessView(graphicsDevice, noiseTexture);

            DataBox data = graphicsDevice.ImmediateContext.MapSubresource(constantBuffer, MapMode.WriteDiscard, MapFlags.None);

            data.Data.Write <DirectComputeConstantBuffer>(container);
            graphicsDevice.ImmediateContext.UnmapSubresource(constantBuffer, 0);

            graphicsDevice.ImmediateContext.ComputeShader.Set(computeFillNoiseTexture);
            graphicsDevice.ImmediateContext.ComputeShader.SetConstantBuffer(constantBuffer, 0);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(noiseTextureUAV, 0);

            Vector3 gridDim = new Vector3((float)Math.Ceiling(container.Width / 8.0f), (float)Math.Ceiling(container.Height / 8.0f), (float)Math.Ceiling(container.Depth / 8.0f));

            graphicsDevice.ImmediateContext.Dispatch((int)gridDim.X, (int)gridDim.Y, (int)gridDim.Z);

            noiseTextureUAV.Dispose();

            return(new ShaderResourceView(graphicsDevice, noiseTexture));
        }
 public void OnDeviceEnd()
 {
     if (m_uav != null)
     {
         m_uav.Dispose();
         m_uav = null;
     }
 }
Esempio n. 5
0
        public virtual void Dispose()
        {
#if DIRECTX
            _uav.Dispose();
#else
            throw new NotImplementedException();
#endif
        }
Esempio n. 6
0
 /// <summary>
 /// 廃棄
 /// </summary>
 public override void Dispose()
 {
     base.Dispose();
     if (unorderedAccessView_ != null)
     {
         unorderedAccessView_.Dispose();
     }
 }
Esempio n. 7
0
        /// <summary cref="DisposeBase.Dispose(bool)"/>
        protected override void Dispose(bool disposing)
        {
            ResourceView?.Dispose();
            ResourceView = null;

            UnorderedAccessView?.Dispose();
            UnorderedAccessView = null;
        }
Esempio n. 8
0
        public override void DisposeInternal()
        {
            if (m_uav != null)
            {
                m_uav.Dispose();
                m_uav = null;
            }

            base.DisposeInternal();
        }
Esempio n. 9
0
        internal override void Release()
        {
            if (m_uav != null)
            {
                m_uav.Dispose();
                m_uav = null;
            }

            base.Release();
        }
        internal override void Release()
        {
            if (m_UAV != null)
            {
                m_UAV.Dispose();
                m_UAV = null;
            }

            base.Release();
        }
        internal override void Release()
        {
            if (m_uav != null)
            {
                m_uav.Dispose();
            }

            m_owner = null;

            base.Release();
        }
Esempio n. 12
0
        public void Dispose()
        {
            _srv1.Dispose();
            _srv2.Dispose();

            _uav1.Dispose();
            _uav2.Dispose();

            _data1.Dispose();
            _data2.Dispose();
        }
Esempio n. 13
0
 public void Dispose()
 {
     if (views != null)
     {
         foreach (var uav in views)
         {
             uav.Value.Dispose();
         }
     }
     View?.Dispose();
     Handle?.Dispose();
 }
        public override void Resize()
        {
            base.Resize();
            int NumTiles            = GetNumTilesX() * GetNumTilesY();
            int MaxNumLightsPerTile = GetMaxNumLightsPerTile();

            LightIndexBuffer?.Dispose();
            LightIndexBuffer = new Buffer(GetDevice, new BufferDescription()
            {
                Usage       = ResourceUsage.Default,
                SizeInBytes = 4 * MaxNumLightsPerTile * NumTiles,
                BindFlags   = BindFlags.ShaderResource | BindFlags.UnorderedAccess,
            });

            LightIndexSRV?.Dispose();
            LightIndexSRV = new ShaderResourceView(GetDevice, LightIndexBuffer, new ShaderResourceViewDescription()
            {
                Format    = Format.R32_UInt,
                Dimension = ShaderResourceViewDimension.Buffer,
                Buffer    = new ShaderResourceViewDescription.BufferResource()
                {
                    ElementOffset = 0,
                    ElementWidth  = MaxNumLightsPerTile * NumTiles,
                },
            });

            LightIndexURV?.Dispose();
            LightIndexURV = new UnorderedAccessView(GetDevice, LightIndexBuffer, new UnorderedAccessViewDescription()
            {
                Format    = Format.R32_UInt,
                Dimension = UnorderedAccessViewDimension.Buffer,
                Buffer    = new UnorderedAccessViewDescription.BufferResource()
                {
                    FirstElement = 0,
                    ElementCount = MaxNumLightsPerTile * NumTiles,
                },
            });
        }
Esempio n. 15
0
        public void OnDeviceEnd()
        {
            if (m_rtv != null)
            {
                m_rtv.Dispose();
                m_rtv = null;
            }

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

            OnDeviceEndInternal();
        }
Esempio n. 16
0
            public void OnDeviceEnd()
            {
                if (m_Rtv != null)
                {
                    m_Rtv.Dispose();
                    m_Rtv = null;
                }

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

                OnDeviceEndInternal();
            }
Esempio n. 17
0
 public void Dispose()
 {
     if (UAV != null)
     {
         UAV.Dispose();
         UAV = null;
     }
     if (SRV != null)
     {
         SRV.Dispose();
         SRV = null;
     }
     if (Buffer != null)
     {
         Buffer.Dispose();
         Buffer = null;
     }
 }
Esempio n. 18
0
        /// <summary>
        /// Initializes render target object using specified values. If resources have been created
        /// earlier then it will dispose them.
        /// </summary>
        /// <param name="width">Texture width.</param>
        /// <param name="height">Texture height.</param>
        /// <param name="format">Texture format.</param>
        public void Initialize(int width, int height, Format format)
        {
            this.width  = width;
            this.height = height;
            this.format = format;

            Texture2DDescription textureDescription = new Texture2DDescription()
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource | BindFlags.UnorderedAccess,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = format,
                Height            = height,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                Width             = width
            };

            if (texture != null)
            {
                texture.Dispose();
            }
            texture = new Texture2D(graphicsDevice, textureDescription);

            if (renderTargetView != null)
            {
                renderTargetView.Dispose();
            }
            renderTargetView = new RenderTargetView(graphicsDevice, texture);

            if (shaderResourceView != null)
            {
                shaderResourceView.Dispose();
            }
            shaderResourceView = new ShaderResourceView(graphicsDevice, texture);

            if (unorderedAccessView != null)
            {
                unorderedAccessView.Dispose();
            }
            unorderedAccessView = new UnorderedAccessView(graphicsDevice, texture);
        }
Esempio n. 19
0
 /// <summary>
 /// 廃棄
 /// </summary>
 public override void Dispose()
 {
     base.Dispose();
     if (renderTargetView_ != null)
     {
         renderTargetView_.Dispose();
     }
     if (depthStencilView_ != null)
     {
         depthStencilView_.Dispose();
     }
     if (unorderedAccessView_ != null)
     {
         unorderedAccessView_.Dispose();
     }
     if (arrayRenderTargetView_ != null)
     {
         foreach (var t in arrayRenderTargetView_)
         {
             t.Dispose();
         }
     }
 }
        public ShaderResourceView GenerateNoiseTexture(Buffer constantBuffer, DirectComputeConstantBuffer container)
        {
            Texture3D noiseTexture = new Texture3D(graphicsDevice, new Texture3DDescription()
            {
                BindFlags = BindFlags.ShaderResource | BindFlags.UnorderedAccess,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.R32_Float,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                Usage = ResourceUsage.Default,
                Width = container.Width,
                Height = container.Height,
                Depth = container.Depth
            });

            UnorderedAccessView noiseTextureUAV = new UnorderedAccessView(graphicsDevice, noiseTexture);

            DataBox data = graphicsDevice.ImmediateContext.MapSubresource(constantBuffer, MapMode.WriteDiscard, MapFlags.None);
            data.Data.Write<DirectComputeConstantBuffer>(container);
            graphicsDevice.ImmediateContext.UnmapSubresource(constantBuffer, 0);

            graphicsDevice.ImmediateContext.ComputeShader.Set(computeFillNoiseTexture);
            graphicsDevice.ImmediateContext.ComputeShader.SetConstantBuffer(constantBuffer, 0);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(noiseTextureUAV, 0);

            Vector3 gridDim = new Vector3((float)Math.Ceiling(container.Width / 8.0f), (float)Math.Ceiling(container.Height / 8.0f), (float)Math.Ceiling(container.Depth / 8.0f));

            graphicsDevice.ImmediateContext.Dispatch((int)gridDim.X, (int)gridDim.Y, (int)gridDim.Z);

            noiseTextureUAV.Dispose();

            return new ShaderResourceView(graphicsDevice, noiseTexture);
        }
 public void Dispose()
 {
     buffer.Dispose();
     view.Dispose();
     stagingBuffer.Dispose();
 }
Esempio n. 22
0
        static void Main()
        {
            var form = new RenderForm("SlimDX - Conway's game of life Direct3D 11 Sample");
            var desc = new SwapChainDescription()
            {
                BufferCount       = 1,
                ModeDescription   = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            Device    device;
            SwapChain swapChain;

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

            device.Factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            Texture2D backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
            var       renderView = new RenderTargetView(device, backBuffer);
            var       bytecode   = ShaderBytecode.CompileFromFile("Render.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None);
            var       effect     = new Effect(device, bytecode);
            var       technique  = effect.GetTechniqueByIndex(0);
            var       pass       = technique.GetPassByIndex(0);
            String    errors;
            var       computeByteCode = ShaderBytecode.CompileFromFile("compute.fx", "CS", "cs_5_0", ShaderFlags.None, EffectFlags.None, null, null, out errors);
            var       compute         = new ComputeShader(device, computeByteCode);

            // shader variable handles
            var conwayResourceH = effect.GetVariableByName("tex").AsResource();
            var resolutionInvH  = effect.GetVariableByName("resolutionInv").AsVector();

            resolutionInvH.Set(new Vector2(1.0f / form.ClientSize.Width, 1.0f / form.ClientSize.Height));
            EffectVectorVariable lightPosSSH = effect.GetVariableByName("lightPosSS").AsVector();

            // create texture, fill it with random data
            Texture2DDescription textureDesc = new Texture2DDescription()
            {
                Width             = form.ClientSize.Width,
                Height            = form.ClientSize.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                CpuAccessFlags    = CpuAccessFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                OptionFlags       = ResourceOptionFlags.None,
                BindFlags         = BindFlags.UnorderedAccess | BindFlags.ShaderResource,
                Format            = Format.R32_Float
            };

            var random = new Random();
            var data   = new float[form.ClientSize.Width * form.ClientSize.Height];

            for (int i = 0; i < form.ClientSize.Width; ++i)
            {
                for (int j = 0; j < form.ClientSize.Height; ++j)
                {
                    data[i * form.ClientSize.Height + j] = (float)random.Next(2);
                }
            }

            DataStream    ds       = new DataStream(data, true, false);
            DataRectangle dataRect = new DataRectangle(4 * form.ClientSize.Width, ds);

            Texture2D conwayTex = new Texture2D(device, textureDesc, dataRect);

            // Create SRV and UAV over the same texture
            UnorderedAccessView conwayUAV = new UnorderedAccessView(device, conwayTex);
            ShaderResourceView  conwaySRV = new ShaderResourceView(device, conwayTex);

            // On the more typical setup where you switch shaders,
            // you will have to set the texture after every
            conwayResourceH.SetResource(conwaySRV);

            device.ImmediateContext.OutputMerger.SetTargets(renderView);
            device.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
            device.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;

            Vector2 lightPosSS;
            float   angle = 0;

            MessagePump.Run(form, () =>
            {
                // this does the light rotation
                angle     += 0.002f;
                lightPosSS = new Vector2((float)Math.Sin(angle) * 0.5f + 0.5f, (float)Math.Cos(angle) * 0.5f + 0.5f);
                lightPosSSH.Set(lightPosSS);

                device.ImmediateContext.ComputeShader.Set(compute);
                device.ImmediateContext.ComputeShader.SetUnorderedAccessView(conwayUAV, 0);
                device.ImmediateContext.Dispatch(form.ClientSize.Width / 16 + 1, form.ClientSize.Height / 16 + 1, 1);

                // After running the CS you have to unset UAV from the shader, so you can use it as SRV
                device.ImmediateContext.ComputeShader.SetUnorderedAccessView(null, 0);

                device.ImmediateContext.ClearRenderTargetView(renderView, Color.Black);

                for (int i = 0; i < technique.Description.PassCount; ++i)
                {
                    pass.Apply(device.ImmediateContext);
                    // No vertices are send as they are created in the vertex shader on the fly.
                    device.ImmediateContext.Draw(4, 0);
                }

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

            computeByteCode.Dispose();
            conwayUAV.Dispose();
            conwaySRV.Dispose();
            conwayTex.Dispose();
            ds.Dispose();
            bytecode.Dispose();
            effect.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            device.Dispose();
            swapChain.Dispose();
        }
Esempio n. 23
0
        public void Release()
        {
#if DIRECTX
            _uav?.Dispose();
#endif
        }
        private void Generate(ComputeShader computePositionWeight, int width, int height, int depth)
        {
            int count = width * height * depth;
            int widthD = width - 1;
            int heightD = height - 1;
            int depthD = depth - 1;
            int countD = widthD * heightD * depthD;

            int nearestW = NearestPowerOfTwo(widthD);
            int nearestH = NearestPowerOfTwo(heightD);
            int nearestD = NearestPowerOfTwo(depthD);
            int nearestCount = nearestW * nearestH * nearestD;

            Vector3 gridDim = new Vector3((float)Math.Ceiling(width / 8.0f), (float)Math.Ceiling(height / 8.0f), (float)Math.Ceiling(depth / 8.0f));
            Vector3 gridDimD = new Vector3((float)Math.Ceiling(widthD / 8.0f), (float)Math.Ceiling(heightD / 8.0f), (float)Math.Ceiling(depthD / 8.0f));

            constantBufferContainer = new DirectComputeConstantBuffer()
            {
                Width = 16,
                Height = 16,
                Depth = 16,
                Seed = (int)DateTime.Now.Ticks
            };

            DirectComputeNoiseCube noiseCube = new DirectComputeNoiseCube(graphicsDevice);

            ShaderResourceView noiseSRV = noiseCube.GenerateNoiseTexture(constantBuffer, constantBufferContainer);

            Buffer voxelsBuffer = new Buffer(graphicsDevice, new BufferDescription()
            {
                BindFlags = BindFlags.UnorderedAccess,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.StructuredBuffer,
                Usage = ResourceUsage.Default,
                SizeInBytes = Marshal.SizeOf(typeof(Voxel)) * count,
                StructureByteStride = Marshal.SizeOf(typeof(Voxel))
            });

            UnorderedAccessView voxelsUAV = new UnorderedAccessView(graphicsDevice, voxelsBuffer);

            constantBufferContainer = new DirectComputeConstantBuffer()
            {
                Width = width,
                Height = height,
                Depth = depth,
                AmbientRayWidth = container.Settings.AmbientRayWidth,
                AmbientSamplesCount = container.Settings.AmbientSamplesCount,
                NearestWidth = nearestW,
                NearestHeight = nearestH,
                NearestDepth = nearestD
            };

            DataBox data = graphicsDevice.ImmediateContext.MapSubresource(constantBuffer, MapMode.WriteDiscard, MapFlags.None);
            data.Data.Write<DirectComputeConstantBuffer>(constantBufferContainer);
            graphicsDevice.ImmediateContext.UnmapSubresource(constantBuffer, 0);

            graphicsDevice.ImmediateContext.ComputeShader.Set(computePositionWeight);
            graphicsDevice.ImmediateContext.ComputeShader.SetConstantBuffer(constantBuffer, 0);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(voxelsUAV, 0);
            graphicsDevice.ImmediateContext.ComputeShader.SetShaderResource(noiseSRV, 0);

            graphicsDevice.ImmediateContext.Dispatch((int)gridDim.X, (int)gridDim.Y, (int)gridDim.Z);

            graphicsDevice.ImmediateContext.ComputeShader.Set(computeNormalAmbient);

            graphicsDevice.ImmediateContext.Dispatch((int)gridDim.X, (int)gridDim.Y, (int)gridDim.Z);

            Buffer offsetsBuffer = new Buffer(graphicsDevice, new BufferDescription()
            {
                BindFlags = BindFlags.UnorderedAccess,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.StructuredBuffer,
                Usage = ResourceUsage.Default,
                SizeInBytes = Marshal.SizeOf(typeof(int)) * countD,
                StructureByteStride = Marshal.SizeOf(typeof(int))
            });

            UnorderedAccessView offsetsUAV = new UnorderedAccessView(graphicsDevice, offsetsBuffer);

            Buffer trisCountBuffer = new Buffer(graphicsDevice, new BufferDescription()
            {
                BindFlags = BindFlags.UnorderedAccess,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.StructuredBuffer,
                Usage = ResourceUsage.Default,
                SizeInBytes = Marshal.SizeOf(typeof(int)) * nearestCount,
                StructureByteStride = Marshal.SizeOf(typeof(int))
            });

            UnorderedAccessView trisCountUAV = new UnorderedAccessView(graphicsDevice, trisCountBuffer);

            graphicsDevice.ImmediateContext.ClearUnorderedAccessView(trisCountUAV, new int[] { 0, 0, 0, 0 });

            graphicsDevice.ImmediateContext.ComputeShader.Set(computeMarchingCubesCases);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(offsetsUAV, 1);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(trisCountUAV, 2);

            graphicsDevice.ImmediateContext.Dispatch((int)gridDimD.X, (int)gridDimD.Y, (int)gridDimD.Z);

            UnorderedAccessView prefixSumsUAV = prefixScan.PrefixSumArray(constantBuffer, trisCountUAV);

            int lastTrisCount = DirectComputeBufferHelper.CopyBuffer<int>(graphicsDevice, trisCountBuffer, nearestCount - 1, 1)[0];

            int lastPrefixSum = DirectComputeBufferHelper.CopyBuffer<int>(graphicsDevice, prefixSumsUAV.Resource, nearestCount - 1, 1)[0];

            int totalVerticesCount = (lastTrisCount + lastPrefixSum) * 3;

            if (totalVerticesCount > 0)
            {
                if (container.Geometry != null)
                    container.Geometry.Dispose();

                container.VertexCount = totalVerticesCount;

                container.Geometry = new Buffer(graphicsDevice, new BufferDescription()
                {
                    BindFlags = BindFlags.VertexBuffer,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None,
                    SizeInBytes = Marshal.SizeOf(typeof(VoxelMeshVertex)) * totalVerticesCount,
                    Usage = ResourceUsage.Default
                });

                Buffer verticesBuffer = new Buffer(graphicsDevice, new BufferDescription()
                {
                    BindFlags = BindFlags.UnorderedAccess,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.StructuredBuffer,
                    Usage = ResourceUsage.Default,
                    SizeInBytes = Marshal.SizeOf(typeof(VoxelMeshVertex)) * totalVerticesCount,
                    StructureByteStride = Marshal.SizeOf(typeof(VoxelMeshVertex))
                });

                UnorderedAccessView verticesUAV = new UnorderedAccessView(graphicsDevice, verticesBuffer);

                constantBufferContainer = new DirectComputeConstantBuffer()
                {
                    Width = width,
                    Height = height,
                    Depth = depth,
                    NearestWidth = nearestW,
                    NearestHeight = nearestH,
                    NearestDepth = nearestD
                };

                data = graphicsDevice.ImmediateContext.MapSubresource(constantBuffer, MapMode.WriteDiscard, MapFlags.None);
                data.Data.Write<DirectComputeConstantBuffer>(constantBufferContainer);
                graphicsDevice.ImmediateContext.UnmapSubresource(constantBuffer, 0);

                graphicsDevice.ImmediateContext.ComputeShader.Set(computeMarchingCubesVertices);
                graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(trisCountUAV, 2);
                graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(prefixSumsUAV, 3);
                graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(verticesUAV, 5);

                graphicsDevice.ImmediateContext.Dispatch((int)gridDimD.X, (int)gridDimD.Y, (int)gridDimD.Z);

                graphicsDevice.ImmediateContext.CopyResource(verticesBuffer, container.Geometry);

                verticesUAV.Dispose();
                verticesBuffer.Dispose();
            }
            else
            {
                container.VertexCount = 0;

                if (container.Geometry != null)
                    container.Geometry.Dispose();
            }

            for (int i = 0; i <= 5; i++)
            {
                graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(null, i);
            }

            prefixSumsUAV.Resource.Dispose();
            prefixSumsUAV.Dispose();
            noiseCube.Dispose();
            noiseSRV.Resource.Dispose();
            noiseSRV.Dispose();
            voxelsBuffer.Dispose();
            voxelsUAV.Dispose();
            offsetsBuffer.Dispose();
            offsetsUAV.Dispose();
            trisCountBuffer.Dispose();
            trisCountUAV.Dispose();
        }
Esempio n. 25
0
        static void Main()
        {
            var form = new RenderForm("SlimDX - Conway's game of life Direct3D 11 Sample");
            var desc = new SwapChainDescription()
            {
                BufferCount = 1,
                ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed = true,
                OutputHandle = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect = SwapEffect.Discard,
                Usage = Usage.RenderTargetOutput
            };

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

            device.Factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            Texture2D backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            var renderView = new RenderTargetView(device, backBuffer);
            var bytecode = ShaderBytecode.CompileFromFile("Render.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None);
            var effect = new Effect(device, bytecode);
            var technique = effect.GetTechniqueByIndex(0);
            var pass = technique.GetPassByIndex(0);
            String errors;
            var computeByteCode = ShaderBytecode.CompileFromFile("compute.fx", "CS", "cs_5_0", ShaderFlags.None, EffectFlags.None, null, null, out errors);
            var compute = new ComputeShader(device, computeByteCode);

            // shader variable handles
            var conwayResourceH = effect.GetVariableByName("tex").AsResource();
            var resolutionInvH = effect.GetVariableByName("resolutionInv").AsVector();
            resolutionInvH.Set(new Vector2(1.0f / form.ClientSize.Width, 1.0f / form.ClientSize.Height));
            EffectVectorVariable lightPosSSH = effect.GetVariableByName("lightPosSS").AsVector();

            // create texture, fill it with random data
            Texture2DDescription textureDesc = new Texture2DDescription()
            {
                Width = form.ClientSize.Width,
                Height = form.ClientSize.Height,
                MipLevels = 1,
                ArraySize = 1,
                CpuAccessFlags = CpuAccessFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                OptionFlags = ResourceOptionFlags.None,
                BindFlags = BindFlags.UnorderedAccess | BindFlags.ShaderResource,
                Format = Format.R32_Float
            };

            var random = new Random();
            var data = new float[form.ClientSize.Width * form.ClientSize.Height];
            for (int i = 0; i < form.ClientSize.Width; ++i)
            {
                for (int j = 0; j < form.ClientSize.Height; ++j)
                    data[i * form.ClientSize.Height + j] = (float)random.Next(2);
            }

            DataStream ds = new DataStream(data, true, false);
            DataRectangle dataRect = new DataRectangle(4 * form.ClientSize.Width, ds);

            Texture2D conwayTex = new Texture2D(device, textureDesc, dataRect);

            // Create SRV and UAV over the same texture
            UnorderedAccessView conwayUAV = new UnorderedAccessView(device, conwayTex);
            ShaderResourceView conwaySRV = new ShaderResourceView(device, conwayTex);

            // On the more typical setup where you switch shaders, 
            // you will have to set the texture after every
            conwayResourceH.SetResource(conwaySRV);

            device.ImmediateContext.OutputMerger.SetTargets(renderView);
            device.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
            device.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;

            Vector2 lightPosSS;
            float angle = 0;

            MessagePump.Run(form, () =>
            {
                // this does the light rotation
                angle += 0.002f;
                lightPosSS = new Vector2((float)Math.Sin(angle) * 0.5f + 0.5f, (float)Math.Cos(angle) * 0.5f + 0.5f);
                lightPosSSH.Set(lightPosSS);

                device.ImmediateContext.ComputeShader.Set(compute);
                device.ImmediateContext.ComputeShader.SetUnorderedAccessView(conwayUAV, 0);
                device.ImmediateContext.Dispatch(form.ClientSize.Width / 16 + 1, form.ClientSize.Height / 16 + 1, 1);

                // After running the CS you have to unset UAV from the shader, so you can use it as SRV
                device.ImmediateContext.ComputeShader.SetUnorderedAccessView(null, 0);

                device.ImmediateContext.ClearRenderTargetView(renderView, Color.Black);

                for (int i = 0; i < technique.Description.PassCount; ++i)
                {
                    pass.Apply(device.ImmediateContext);
                    // No vertices are send as they are created in the vertex shader on the fly.
                    device.ImmediateContext.Draw(4, 0);
                }

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

            computeByteCode.Dispose();
            conwayUAV.Dispose();
            conwaySRV.Dispose();
            conwayTex.Dispose();
            ds.Dispose();
            bytecode.Dispose();
            effect.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            device.Dispose();
            swapChain.Dispose();
        }
    public void Dilate(MultiUvTextureMask mask, Size2 size, bool isLinear, DataBox imageData)
    {
        //set every alpha value to 0
        for (int i = 0; i < imageData.SlicePitch; i += 4)
        {
            var rgba = Utilities.Read <uint>(imageData.DataPointer + i);
            rgba &= 0xffffff;
            Utilities.Write <uint>(imageData.DataPointer + i, ref rgba);
        }

        var sourceTextureDesc = new Texture2DDescription {
            Width             = size.Width,
            Height            = size.Height,
            MipLevels         = 0,
            ArraySize         = 1,
            Format            = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
            SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
            BindFlags         = BindFlags.ShaderResource | BindFlags.RenderTarget | BindFlags.UnorderedAccess,
            OptionFlags       = ResourceOptionFlags.GenerateMipMaps
        };
        var sourceTexture        = new Texture2D(device, sourceTextureDesc);
        var sourceTextureInView  = new ShaderResourceView(device, sourceTexture);
        var sourceTextureOutView = new UnorderedAccessView(device, sourceTexture);

        var destTextureDesc = new Texture2DDescription {
            Width             = size.Width,
            Height            = size.Height,
            MipLevels         = 1,
            ArraySize         = 1,
            Format            = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
            SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
            BindFlags         = BindFlags.UnorderedAccess
        };
        var destTexture        = new Texture2D(device, destTextureDesc);
        var destTextureOutView = new UnorderedAccessView(device, destTexture);

        var stagingTextureDesc = new Texture2DDescription {
            Width             = size.Width,
            Height            = size.Height,
            MipLevels         = 1,
            ArraySize         = 1,
            Format            = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
            SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
            Usage             = ResourceUsage.Staging,
            CpuAccessFlags    = CpuAccessFlags.Read
        };
        var stagingTexture = new Texture2D(device, stagingTextureDesc);

        var context = device.ImmediateContext;

        context.UpdateSubresource(imageData, sourceTexture, 0);

        foreach (var perUvMask in mask.PerUvMasks)
        {
            maskRenderer.RenderMaskToAlpha(perUvMask, size, sourceTexture);
        }

        context.ClearState();
        context.ComputeShader.Set(alphaPremultiplerShader);
        context.ComputeShader.SetUnorderedAccessView(0, sourceTextureOutView);
        context.Dispatch(
            IntegerUtils.RoundUp(size.Width, ShaderNumThreadsPerDim),
            IntegerUtils.RoundUp(size.Height, ShaderNumThreadsPerDim),
            1);
        context.ClearState();

        context.GenerateMips(sourceTextureInView);

        context.ClearState();
        context.ComputeShader.Set(dilatorShader);
        context.ComputeShader.SetShaderResources(0, sourceTextureInView);
        context.ComputeShader.SetUnorderedAccessView(0, destTextureOutView);
        context.Dispatch(
            IntegerUtils.RoundUp(size.Width, ShaderNumThreadsPerDim),
            IntegerUtils.RoundUp(size.Height, ShaderNumThreadsPerDim),
            1);
        context.ClearState();

        context.CopyResource(destTexture, stagingTexture);

        var resultImageData = context.MapSubresource(stagingTexture, 0, MapMode.Read, MapFlags.None);

        CopyDataBox(resultImageData, imageData);
        context.UnmapSubresource(stagingTexture, 0);

        stagingTexture.Dispose();

        destTexture.Dispose();
        destTextureOutView.Dispose();

        sourceTexture.Dispose();
        sourceTextureInView.Dispose();
        sourceTextureOutView.Dispose();
    }
        public UnorderedAccessView PrefixSumArray(Buffer constantBuffer, UnorderedAccessView trisCountUAV)
        {
            int arrayLength = trisCountUAV.Description.ElementCount;
            int batchSize   = trisCountUAV.Description.ElementCount / arrayLength;

            if (!IsPowerOfTwo(trisCountUAV.Description.ElementCount))
            {
                throw new Exception("Input array length is not power of two.");
            }

            Buffer buffer = new Buffer(graphicsDevice, new BufferDescription()
            {
                BindFlags           = BindFlags.UnorderedAccess,
                CpuAccessFlags      = CpuAccessFlags.None,
                OptionFlags         = ResourceOptionFlags.StructuredBuffer,
                Usage               = ResourceUsage.Default,
                SizeInBytes         = Marshal.SizeOf(typeof(int)) * trisCountUAV.Description.ElementCount,
                StructureByteStride = Marshal.SizeOf(typeof(int))
            });

            UnorderedAccessView bufferUAV = new UnorderedAccessView(graphicsDevice, buffer);

            Buffer output = new Buffer(graphicsDevice, new BufferDescription()
            {
                BindFlags           = BindFlags.UnorderedAccess,
                CpuAccessFlags      = CpuAccessFlags.None,
                OptionFlags         = ResourceOptionFlags.StructuredBuffer,
                Usage               = ResourceUsage.Default,
                SizeInBytes         = Marshal.SizeOf(typeof(int)) * trisCountUAV.Description.ElementCount,
                StructureByteStride = Marshal.SizeOf(typeof(int))
            });

            UnorderedAccessView outputUAV = new UnorderedAccessView(graphicsDevice, output);

            DirectComputeConstantBuffer constantBufferContainer = new DirectComputeConstantBuffer()
            {
                PrefixSize        = 4 * threadBlockSize,
                PrefixN           = (batchSize * arrayLength) / (4 * threadBlockSize),
                PrefixArrayLength = arrayLength / (4 * threadBlockSize)
            };

            DataBox data = graphicsDevice.ImmediateContext.MapSubresource(constantBuffer, MapMode.WriteDiscard, MapFlags.None);

            data.Data.Write <DirectComputeConstantBuffer>(constantBufferContainer);
            graphicsDevice.ImmediateContext.UnmapSubresource(constantBuffer, 0);

            Vector3 gridDim        = new Vector3((batchSize * arrayLength) / (4 * threadBlockSize), 1, 1);
            Vector3 gridDimShared2 = new Vector3((int)Math.Ceiling(((batchSize * arrayLength) / (4 * threadBlockSize)) / (double)threadBlockSize), 1, 1);

            graphicsDevice.ImmediateContext.ComputeShader.Set(computeScanExclusiveShared);
            graphicsDevice.ImmediateContext.ComputeShader.SetConstantBuffer(constantBuffer, 0);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(trisCountUAV, 2);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(outputUAV, 3);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(bufferUAV, 4);

            graphicsDevice.ImmediateContext.Dispatch((int)gridDim.X, (int)gridDim.Y, (int)gridDim.Z);

            graphicsDevice.ImmediateContext.ComputeShader.Set(computeScanExclusiveShared2);

            graphicsDevice.ImmediateContext.Dispatch((int)gridDimShared2.X, (int)gridDimShared2.Y, (int)gridDimShared2.Z);

            graphicsDevice.ImmediateContext.ComputeShader.Set(computeUniformUpdate);

            graphicsDevice.ImmediateContext.Dispatch((int)gridDim.X, (int)gridDim.Y, (int)gridDim.Z);

            buffer.Dispose();
            bufferUAV.Dispose();

            return(outputUAV);
        }
Esempio n. 28
0
        /// <summary>
        /// Sets the internal capacity of the list
        /// </summary>
        /// <param name="newCapacity"></param>
        private void setCapacity(int newCapacity)
        {
            if (newCapacity < 0)
            {
                throw new ArgumentOutOfRangeException();
            }

            if (newCapacity == capacity)
            {
                return;
            }

            if (newCapacity == 0)
            {
                if (unorderedAccessView != null)
                {
                    unorderedAccessView.Dispose();
                }
                if (shaderResourceView != null)
                {
                    shaderResourceView.Dispose();
                }
                if (buffer != null)
                {
                    buffer.Dispose();
                }

                unorderedAccessView = null;
                shaderResourceView  = null;
                buffer = null;

                capacity = count = 0;
                return;
            }

            int    dataSize  = Marshal.SizeOf(typeof(T));
            Buffer newBuffer = new Buffer(context.Device, dataSize * newCapacity, ResourceUsage.Default,
                                          BindFlags.ShaderResource | BindFlags.UnorderedAccess,
                                          CpuAccessFlags.None, ResourceOptionFlags.StructuredBuffer, dataSize);

            int sizeToCopy = Math.Min(newCapacity, Count);

            if (sizeToCopy > 0)
            {
                context.CopySubresourceRegion(buffer, 0, new ResourceRegion(0, 0, 0, dataSize * sizeToCopy, 1, 1), newBuffer, 0, 0, 0, 0);
            }

            count    = sizeToCopy;
            capacity = newCapacity;

            if (unorderedAccessView != null)
            {
                unorderedAccessView.Dispose();
            }
            if (shaderResourceView != null)
            {
                shaderResourceView.Dispose();
            }
            if (buffer != null)
            {
                buffer.Dispose();
            }

            buffer = newBuffer;
            unorderedAccessView = new UnorderedAccessView(context.Device, buffer);
            shaderResourceView  = new ShaderResourceView(context.Device, buffer);
        }
        public UnorderedAccessView PrefixSumArray(Buffer constantBuffer, UnorderedAccessView trisCountUAV)
        {
            int arrayLength = trisCountUAV.Description.ElementCount;
            int batchSize = trisCountUAV.Description.ElementCount / arrayLength;

            if (!IsPowerOfTwo(trisCountUAV.Description.ElementCount))
                throw new Exception("Input array length is not power of two.");

            Buffer buffer = new Buffer(graphicsDevice, new BufferDescription()
            {
                BindFlags = BindFlags.UnorderedAccess,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.StructuredBuffer,
                Usage = ResourceUsage.Default,
                SizeInBytes = Marshal.SizeOf(typeof(int)) * trisCountUAV.Description.ElementCount,
                StructureByteStride = Marshal.SizeOf(typeof(int))
            });

            UnorderedAccessView bufferUAV = new UnorderedAccessView(graphicsDevice, buffer);

            Buffer output = new Buffer(graphicsDevice, new BufferDescription()
            {
                BindFlags = BindFlags.UnorderedAccess,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.StructuredBuffer,
                Usage = ResourceUsage.Default,
                SizeInBytes = Marshal.SizeOf(typeof(int)) * trisCountUAV.Description.ElementCount,
                StructureByteStride = Marshal.SizeOf(typeof(int))
            });

            UnorderedAccessView outputUAV = new UnorderedAccessView(graphicsDevice, output);

            DirectComputeConstantBuffer constantBufferContainer = new DirectComputeConstantBuffer()
            {
                PrefixSize = 4 * threadBlockSize,
                PrefixN = (batchSize * arrayLength) / (4 * threadBlockSize),
                PrefixArrayLength = arrayLength / (4 * threadBlockSize)
            };

            DataBox data = graphicsDevice.ImmediateContext.MapSubresource(constantBuffer, MapMode.WriteDiscard, MapFlags.None);
            data.Data.Write<DirectComputeConstantBuffer>(constantBufferContainer);
            graphicsDevice.ImmediateContext.UnmapSubresource(constantBuffer, 0);

            Vector3 gridDim = new Vector3((batchSize * arrayLength) / (4 * threadBlockSize), 1, 1);
            Vector3 gridDimShared2 = new Vector3((int)Math.Ceiling(((batchSize * arrayLength) / (4 * threadBlockSize)) / (double)threadBlockSize), 1, 1);

            graphicsDevice.ImmediateContext.ComputeShader.Set(computeScanExclusiveShared);
            graphicsDevice.ImmediateContext.ComputeShader.SetConstantBuffer(constantBuffer, 0);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(trisCountUAV, 2);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(outputUAV, 3);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(bufferUAV, 4);

            graphicsDevice.ImmediateContext.Dispatch((int)gridDim.X, (int)gridDim.Y, (int)gridDim.Z);
            
            graphicsDevice.ImmediateContext.ComputeShader.Set(computeScanExclusiveShared2);

            graphicsDevice.ImmediateContext.Dispatch((int)gridDimShared2.X, (int)gridDimShared2.Y, (int)gridDimShared2.Z);

            graphicsDevice.ImmediateContext.ComputeShader.Set(computeUniformUpdate);

            graphicsDevice.ImmediateContext.Dispatch((int)gridDim.X, (int)gridDim.Y, (int)gridDim.Z);

            buffer.Dispose();
            bufferUAV.Dispose();

            return outputUAV;
        }
Esempio n. 30
0
        private void Generate(ComputeShader computePositionWeight, int width, int height, int depth)
        {
            int count   = width * height * depth;
            int widthD  = width - 1;
            int heightD = height - 1;
            int depthD  = depth - 1;
            int countD  = widthD * heightD * depthD;

            int nearestW     = NearestPowerOfTwo(widthD);
            int nearestH     = NearestPowerOfTwo(heightD);
            int nearestD     = NearestPowerOfTwo(depthD);
            int nearestCount = nearestW * nearestH * nearestD;

            Vector3 gridDim  = new Vector3((float)Math.Ceiling(width / 8.0f), (float)Math.Ceiling(height / 8.0f), (float)Math.Ceiling(depth / 8.0f));
            Vector3 gridDimD = new Vector3((float)Math.Ceiling(widthD / 8.0f), (float)Math.Ceiling(heightD / 8.0f), (float)Math.Ceiling(depthD / 8.0f));

            constantBufferContainer = new DirectComputeConstantBuffer()
            {
                Width  = 16,
                Height = 16,
                Depth  = 16,
                Seed   = (int)DateTime.Now.Ticks
            };

            DirectComputeNoiseCube noiseCube = new DirectComputeNoiseCube(graphicsDevice);

            ShaderResourceView noiseSRV = noiseCube.GenerateNoiseTexture(constantBuffer, constantBufferContainer);

            Buffer voxelsBuffer = new Buffer(graphicsDevice, new BufferDescription()
            {
                BindFlags           = BindFlags.UnorderedAccess,
                CpuAccessFlags      = CpuAccessFlags.None,
                OptionFlags         = ResourceOptionFlags.StructuredBuffer,
                Usage               = ResourceUsage.Default,
                SizeInBytes         = Marshal.SizeOf(typeof(Voxel)) * count,
                StructureByteStride = Marshal.SizeOf(typeof(Voxel))
            });

            UnorderedAccessView voxelsUAV = new UnorderedAccessView(graphicsDevice, voxelsBuffer);

            constantBufferContainer = new DirectComputeConstantBuffer()
            {
                Width               = width,
                Height              = height,
                Depth               = depth,
                AmbientRayWidth     = container.Settings.AmbientRayWidth,
                AmbientSamplesCount = container.Settings.AmbientSamplesCount,
                NearestWidth        = nearestW,
                NearestHeight       = nearestH,
                NearestDepth        = nearestD
            };

            DataBox data = graphicsDevice.ImmediateContext.MapSubresource(constantBuffer, MapMode.WriteDiscard, MapFlags.None);

            data.Data.Write <DirectComputeConstantBuffer>(constantBufferContainer);
            graphicsDevice.ImmediateContext.UnmapSubresource(constantBuffer, 0);

            graphicsDevice.ImmediateContext.ComputeShader.Set(computePositionWeight);
            graphicsDevice.ImmediateContext.ComputeShader.SetConstantBuffer(constantBuffer, 0);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(voxelsUAV, 0);
            graphicsDevice.ImmediateContext.ComputeShader.SetShaderResource(noiseSRV, 0);

            graphicsDevice.ImmediateContext.Dispatch((int)gridDim.X, (int)gridDim.Y, (int)gridDim.Z);

            graphicsDevice.ImmediateContext.ComputeShader.Set(computeNormalAmbient);

            graphicsDevice.ImmediateContext.Dispatch((int)gridDim.X, (int)gridDim.Y, (int)gridDim.Z);

            Buffer offsetsBuffer = new Buffer(graphicsDevice, new BufferDescription()
            {
                BindFlags           = BindFlags.UnorderedAccess,
                CpuAccessFlags      = CpuAccessFlags.None,
                OptionFlags         = ResourceOptionFlags.StructuredBuffer,
                Usage               = ResourceUsage.Default,
                SizeInBytes         = Marshal.SizeOf(typeof(int)) * countD,
                StructureByteStride = Marshal.SizeOf(typeof(int))
            });

            UnorderedAccessView offsetsUAV = new UnorderedAccessView(graphicsDevice, offsetsBuffer);

            Buffer trisCountBuffer = new Buffer(graphicsDevice, new BufferDescription()
            {
                BindFlags           = BindFlags.UnorderedAccess,
                CpuAccessFlags      = CpuAccessFlags.None,
                OptionFlags         = ResourceOptionFlags.StructuredBuffer,
                Usage               = ResourceUsage.Default,
                SizeInBytes         = Marshal.SizeOf(typeof(int)) * nearestCount,
                StructureByteStride = Marshal.SizeOf(typeof(int))
            });

            UnorderedAccessView trisCountUAV = new UnorderedAccessView(graphicsDevice, trisCountBuffer);

            graphicsDevice.ImmediateContext.ClearUnorderedAccessView(trisCountUAV, new int[] { 0, 0, 0, 0 });

            graphicsDevice.ImmediateContext.ComputeShader.Set(computeMarchingCubesCases);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(offsetsUAV, 1);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(trisCountUAV, 2);

            graphicsDevice.ImmediateContext.Dispatch((int)gridDimD.X, (int)gridDimD.Y, (int)gridDimD.Z);

            UnorderedAccessView prefixSumsUAV = prefixScan.PrefixSumArray(constantBuffer, trisCountUAV);

            int lastTrisCount = DirectComputeBufferHelper.CopyBuffer <int>(graphicsDevice, trisCountBuffer, nearestCount - 1, 1)[0];

            int lastPrefixSum = DirectComputeBufferHelper.CopyBuffer <int>(graphicsDevice, prefixSumsUAV.Resource, nearestCount - 1, 1)[0];

            int totalVerticesCount = (lastTrisCount + lastPrefixSum) * 3;

            if (totalVerticesCount > 0)
            {
                if (container.Geometry != null)
                {
                    container.Geometry.Dispose();
                }

                container.VertexCount = totalVerticesCount;

                container.Geometry = new Buffer(graphicsDevice, new BufferDescription()
                {
                    BindFlags      = BindFlags.VertexBuffer,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags    = ResourceOptionFlags.None,
                    SizeInBytes    = Marshal.SizeOf(typeof(VoxelMeshVertex)) * totalVerticesCount,
                    Usage          = ResourceUsage.Default
                });

                Buffer verticesBuffer = new Buffer(graphicsDevice, new BufferDescription()
                {
                    BindFlags           = BindFlags.UnorderedAccess,
                    CpuAccessFlags      = CpuAccessFlags.None,
                    OptionFlags         = ResourceOptionFlags.StructuredBuffer,
                    Usage               = ResourceUsage.Default,
                    SizeInBytes         = Marshal.SizeOf(typeof(VoxelMeshVertex)) * totalVerticesCount,
                    StructureByteStride = Marshal.SizeOf(typeof(VoxelMeshVertex))
                });

                UnorderedAccessView verticesUAV = new UnorderedAccessView(graphicsDevice, verticesBuffer);

                constantBufferContainer = new DirectComputeConstantBuffer()
                {
                    Width         = width,
                    Height        = height,
                    Depth         = depth,
                    NearestWidth  = nearestW,
                    NearestHeight = nearestH,
                    NearestDepth  = nearestD
                };

                data = graphicsDevice.ImmediateContext.MapSubresource(constantBuffer, MapMode.WriteDiscard, MapFlags.None);
                data.Data.Write <DirectComputeConstantBuffer>(constantBufferContainer);
                graphicsDevice.ImmediateContext.UnmapSubresource(constantBuffer, 0);

                graphicsDevice.ImmediateContext.ComputeShader.Set(computeMarchingCubesVertices);
                graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(trisCountUAV, 2);
                graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(prefixSumsUAV, 3);
                graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(verticesUAV, 5);

                graphicsDevice.ImmediateContext.Dispatch((int)gridDimD.X, (int)gridDimD.Y, (int)gridDimD.Z);

                graphicsDevice.ImmediateContext.CopyResource(verticesBuffer, container.Geometry);

                verticesUAV.Dispose();
                verticesBuffer.Dispose();
            }
            else
            {
                container.VertexCount = 0;

                if (container.Geometry != null)
                {
                    container.Geometry.Dispose();
                }
            }

            for (int i = 0; i <= 5; i++)
            {
                graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(null, i);
            }

            prefixSumsUAV.Resource.Dispose();
            prefixSumsUAV.Dispose();
            noiseCube.Dispose();
            noiseSRV.Resource.Dispose();
            noiseSRV.Dispose();
            voxelsBuffer.Dispose();
            voxelsUAV.Dispose();
            offsetsBuffer.Dispose();
            offsetsUAV.Dispose();
            trisCountBuffer.Dispose();
            trisCountUAV.Dispose();
        }