Example #1
0
        protected override void CopyBufferCore(DeviceBuffer source, uint sourceOffset, DeviceBuffer destination, uint destinationOffset, uint sizeInBytes)
        {
            D3D11Buffer srcD3D11Buffer = Util.AssertSubtype <DeviceBuffer, D3D11Buffer>(source);
            D3D11Buffer dstD3D11Buffer = Util.AssertSubtype <DeviceBuffer, D3D11Buffer>(destination);

            ResourceRegion region = new ResourceRegion((int)sourceOffset, 0, 0, (int)(sourceOffset + sizeInBytes), 1, 1);

            _context.CopySubresourceRegion(srcD3D11Buffer.Buffer, 0, region, dstD3D11Buffer.Buffer, 0, (int)destinationOffset, 0, 0);
        }
        /// <summary>
        /// Copies a range of data to an array
        /// </summary>
        /// <param name="index">Index from which to start copying</param>
        /// <param name="count">Number of elements to copy</param>
        /// <param name="array">Destination array to copy to</param>
        /// <param name="arrayIndex">Destination array index to copy to</param>
        public void CopyRangeTo(int index, int count, T[] array, int arrayIndex)
        {
            if (count == 0)
            {
                return;
            }

            if (count < 0)
            {
                throw new IndexOutOfRangeException();
            }
            if (index < 0 || index >= Count)
            {
                throw new IndexOutOfRangeException();
            }
            if (index + count < 0 || index + count > Count)
            {
                throw new IndexOutOfRangeException();
            }

            if (array == null)
            {
                throw new ArgumentNullException();
            }
            if (arrayIndex < 0 || arrayIndex >= array.Length)
            {
                throw new IndexOutOfRangeException();
            }
            if (arrayIndex + array.Length < 0 || arrayIndex + count > array.Length)
            {
                throw new IndexOutOfRangeException();
            }

            int dataSize = Marshal.SizeOf(typeof(T));
            //Buffer stagingBuffer = new Buffer(context.Device, dataSize * count, ResourceUsage.Staging,
            //    BindFlags.None, CpuAccessFlags.Read, ResourceOptionFlags.None, 0);
            Buffer bufferToUse = GetStagingBuffer();


            context.CopySubresourceRegion(buffer, 0,
                                          new ResourceRegion(dataSize * index, 0, 0, dataSize * (index + count), 1, 1),
                                          bufferToUse, 0, 0, 0, 0);

            DataBox box = context.MapSubresource(bufferToUse,
                                                 MapMode.Read, SlimDX.Direct3D11.MapFlags.None);

            box.Data.ReadRange <T>(array, arrayIndex, count);
            context.UnmapSubresource(bufferToUse, 0);

            //stagingBuffer.Dispose();
        }
Example #3
0
        public static void CreateTexture2D(DeviceContext context, Texture2D[] texturesCollection, out Texture2D textureArray, SharpDX.DXGI.Format InMemoryArrayFormat = SharpDX.DXGI.Format.R8G8B8A8_UNorm)
        {
            //Create TextureArray object
            var imagesdesc   = texturesCollection[0].Description;
            var texArrayDesc = new Texture2DDescription
            {
                Width             = imagesdesc.Width,
                Height            = imagesdesc.Height,
                MipLevels         = imagesdesc.MipLevels,
                ArraySize         = texturesCollection.Length,
                Format            = InMemoryArrayFormat,
                SampleDescription = new SharpDX.DXGI.SampleDescription {
                    Count = 1, Quality = 0
                },
                Usage          = ResourceUsage.Default,
                BindFlags      = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = ResourceOptionFlags.None
            };

            textureArray = new Texture2D(context.Device, texArrayDesc);

            //Foreach Texture
            for (var arraySlice = 0; arraySlice < texturesCollection.Length; arraySlice++)
            {
                //Foreach mipmap level
                for (var mipSlice = 0; mipSlice < imagesdesc.MipLevels; mipSlice++)
                {
                    context.CopySubresourceRegion(texturesCollection[arraySlice], mipSlice, null, textureArray, Resource.CalculateSubResourceIndex(mipSlice, arraySlice, imagesdesc.MipLevels));
                }
            }
        }
Example #4
0
        public static void CreateTexture2D(DeviceContext context, Texture2D[] texturesCollection, string resourceName, out ShaderResourceView textureArrayView, SharpDX.DXGI.Format InMemoryArrayFormat = SharpDX.DXGI.Format.R8G8B8A8_UNorm)
        {
            //Create TextureArray object
            var imagesdesc   = texturesCollection[0].Description;
            var texArrayDesc = new Texture2DDescription
            {
                Width             = imagesdesc.Width,
                Height            = imagesdesc.Height,
                MipLevels         = imagesdesc.MipLevels,
                ArraySize         = texturesCollection.Length,
                Format            = InMemoryArrayFormat,
                SampleDescription = new SharpDX.DXGI.SampleDescription {
                    Count = 1, Quality = 0
                },
                Usage          = ResourceUsage.Default,
                BindFlags      = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = ResourceOptionFlags.None
            };

            var texArray = new Texture2D(context.Device, texArrayDesc);

            //Foreach Texture
            for (var arraySlice = 0; arraySlice < texturesCollection.Length; arraySlice++)
            {
                //Foreach mipmap level
                for (var mipSlice = 0; mipSlice < imagesdesc.MipLevels; mipSlice++)
                {
                    context.CopySubresourceRegion(texturesCollection[arraySlice], mipSlice, null, texArray, Resource.CalculateSubResourceIndex(mipSlice, arraySlice, imagesdesc.MipLevels));
                }
            }

            //Create Resource view to texture array
            var viewDesc = new ShaderResourceViewDescription
            {
                Format         = texArrayDesc.Format,
                Dimension      = ShaderResourceViewDimension.Texture2DArray,
                Texture2DArray = new ShaderResourceViewDescription.Texture2DArrayResource
                {
                    MostDetailedMip = 0,
                    MipLevels       = texArrayDesc.MipLevels,
                    FirstArraySlice = 0,
                    ArraySize       = texturesCollection.Length
                }
            };

            textureArrayView = new ShaderResourceView(context.Device, texArray, viewDesc);

            //Set resource Name, will only be done at debug time.
#if DEBUG
            textureArrayView.DebugName = resourceName;
#endif

            //Disposing resources used to create the texture array
            texArray.Dispose();
        }
Example #5
0
        /// <summary>
        /// Update D3DImage for WPF
        /// </summary>
        /// <param name="surface">Pointer to Surface from FFMpeg</param>
        /// <param name="surfaceIndex">Index to subsufaace from the current update</param>
        private void UpdateImage(IntPtr surface, uint surfaceIndex)
        {
            if (Shutdown == false)
            {
                if (surface != IntPtr.Zero)
                {
                    //Access ffmpeg d3d device
                    using (var ffmpegSrc = CppObject.FromPointer <Texture2D>(surface)) {
                        if (FFmpegD3DDevice == null)
                        {
                            FFmpegD3DDevice  = ffmpegSrc.Device;
                            FFmpegD3DContext = FFmpegD3DDevice.ImmediateContext;
                        }

                        //Need to Create a Transfer Texture on the ffmpeg device to allow shared access from wpf d3ddevice
                        //Only Create Once
                        if (TransferTexture == null)
                        {
                            var tempDesc = ffmpegSrc.Description;
                            tempDesc.ArraySize   = 1;
                            tempDesc.BindFlags  |= BindFlags.ShaderResource;
                            tempDesc.OptionFlags = ResourceOptionFlags.Shared;
                            tempDesc.Usage       = ResourceUsage.Default;

                            TransferTexture = new Texture2D(FFmpegD3DDevice, tempDesc);
                        }

                        ////Copy the ffmpegTexture to Transfer Texture, Also select the correct sub texture index to a single texture for transfer
                        FFmpegD3DContext.CopySubresourceRegion(ffmpegSrc, Convert.ToInt32(surfaceIndex), null, TransferTexture, 0);
                    }

                    //Hack to create D3D Device so we dont miss the first frame
                    if (D3DDevice == null)
                    {
                        RequestD3DRender();
                    }

                    if (D3DDevice != null && TransferTexture != null && DisplayTexture == null)
                    {
                        //Convert transfer texture thru to DXGI resource Object
                        using (var resource = TransferTexture.QueryInterface <SharpDX.DXGI.Resource>()) {
                            //Get shared handle from DXGI resource
                            using (var sharedResource = D3DDevice.OpenSharedResource <SharpDX.DXGI.Resource>(resource.SharedHandle)) {
                                //Convert back to Texture2D Object
                                using (var sharedTexture = sharedResource.QueryInterface <SharpDX.Direct3D11.Texture2D>()) {
                                    DisplayTexture = sharedResource.QueryInterface <SharpDX.Direct3D11.Texture2D>();
                                }
                            }
                        }
                    }

                    //Request a render evey time we have a new frame from FFMpeg
                    RequestD3DRender();
                }
            }
        }
Example #6
0
        public void GetResults(DeviceContext context, out float min, out float max)
        {
            context.CopySubresourceRegion(texture2DMinMax, texture2DMinMaxResourceView.Length - 1, null, textureReadback, 0, 0, 0, 0);
            DataStream result;

            context.MapSubresource(textureReadback, 0, MapMode.Read, MapFlags.None, out result);
            min = result.Read <float>();
            max = result.Read <float>();
            context.UnmapSubresource(textureReadback, 0);
        }
        public T readPixel <T>(Resource resource) where T : struct
        {
            context.CopySubresourceRegion(resource, Resource.CalculateSubresourceIndex(0, 0, 1),
                                          new ResourceRegion(0, 0, 0, 1, 1, 1), tempTex,
                                          Resource.CalculateSubresourceIndex(0, 0, 1), 0, 0, 0);
            var data = context.MapSubresource(tempTex,
                                              Resource.CalculateSubresourceIndex(0, 0, 1), 4, MapMode.Read,
                                              global::SlimDX.Direct3D11.MapFlags.None);

            var ret = data.Data.Read <T>();

            context.UnmapSubresource(tempTex, Resource.CalculateSubresourceIndex(0, 0, 1));
            return(ret);
        }
Example #8
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;
        }
Example #9
0
            public void UpdateColorImage(DeviceContext deviceContext, byte[] colorImage)
            {
                DataStream dataStream;

                deviceContext.MapSubresource(colorImageStagingTexture, 0,
                                             MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out dataStream);
                dataStream.WriteRange <byte>(colorImage, 0, Kinect2Calibration.colorImageWidth * Kinect2Calibration.colorImageHeight * 4);
                deviceContext.UnmapSubresource(colorImageStagingTexture, 0);

                var resourceRegion = new ResourceRegion()
                {
                    Left   = 0,
                    Top    = 0,
                    Right  = Kinect2Calibration.colorImageWidth,
                    Bottom = Kinect2Calibration.colorImageHeight,
                    Front  = 0,
                    Back   = 1,
                };

                deviceContext.CopySubresourceRegion(colorImageStagingTexture, 0, resourceRegion, colorImageTexture, 0);
                deviceContext.GenerateMips(colorImageTextureRV);
            }
Example #10
0
        public override ImageC RetrieveTestImage()
        {
            const int            mipLevelToRetrieve = 0;
            Texture2DDescription dx11Description;

            dx11Description.ArraySize         = 1;
            dx11Description.BindFlags         = BindFlags.None;
            dx11Description.CpuAccessFlags    = CpuAccessFlags.Read;
            dx11Description.Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm;
            dx11Description.Height            = Size.X >> mipLevelToRetrieve;
            dx11Description.MipLevels         = 1;
            dx11Description.OptionFlags       = ResourceOptionFlags.None;
            dx11Description.SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0);
            dx11Description.Usage             = ResourceUsage.Staging;
            dx11Description.Width             = Size.Y >> mipLevelToRetrieve;
            using (Texture2D tempTexture = new Texture2D(Context.Device, dx11Description))
            {
                int    bytesPerSlice = (Size.X >> mipLevelToRetrieve) * (Size.Y >> mipLevelToRetrieve) * ImageC.PixelSize;
                byte[] result        = new byte[bytesPerSlice * Size.Z];
                for (int z = 0; z < Size.Z; ++z)
                {
                    int subresourceIndex = MipLevelCount * z + mipLevelToRetrieve;
                    Context.CopySubresourceRegion(Texture, subresourceIndex, null, tempTexture, 0);
                    DataBox mappedBuffer = Context.MapSubresource(tempTexture, 0, MapMode.Read, MapFlags.None);
                    try
                    {
                        Marshal.Copy(mappedBuffer.DataPointer, result, bytesPerSlice * z, bytesPerSlice);
                    }
                    finally
                    {
                        Context.UnmapSubresource(tempTexture, 0);
                    }
                }
                return(ImageC.FromByteArray(result, Size.X >> mipLevelToRetrieve, (Size.Y >> mipLevelToRetrieve) * Size.Z));
            }
        }
 public void GetResults(DeviceContext context, out float min, out float max)
 {
     context.CopySubresourceRegion(texture2DMinMax, texture2DMinMaxResourceView.Length - 1, null, textureReadback, 0, 0, 0, 0);
     DataStream result;
     context.MapSubresource(textureReadback, 0, MapMode.Read, MapFlags.None, out result);
     min = result.ReadFloat();
     max = result.ReadFloat();
     context.UnmapSubresource(textureReadback, 0);
 }
Example #12
0
        protected unsafe override void UpdateBufferCore(DeviceBuffer buffer, uint bufferOffsetInBytes, IntPtr source, uint sizeInBytes)
        {
            D3D11Buffer d3dBuffer = Util.AssertSubtype <DeviceBuffer, D3D11Buffer>(buffer);

            if (sizeInBytes == 0)
            {
                return;
            }

            bool isDynamic            = (buffer.Usage & BufferUsage.Dynamic) == BufferUsage.Dynamic;
            bool isStaging            = (buffer.Usage & BufferUsage.Staging) == BufferUsage.Staging;
            bool isUniformBuffer      = (buffer.Usage & BufferUsage.UniformBuffer) == BufferUsage.UniformBuffer;
            bool updateFullBuffer     = bufferOffsetInBytes == 0 && sizeInBytes == buffer.SizeInBytes;
            bool useUpdateSubresource = (!isDynamic && !isStaging) && (!isUniformBuffer || updateFullBuffer);
            bool useMap = (isDynamic && updateFullBuffer) || isStaging;

            if (useUpdateSubresource)
            {
                ResourceRegion?subregion = new ResourceRegion()
                {
                    Left   = (int)bufferOffsetInBytes,
                    Right  = (int)(sizeInBytes + bufferOffsetInBytes),
                    Bottom = 1,
                    Back   = 1
                };

                if (isUniformBuffer)
                {
                    subregion = null;
                }

                lock (_immediateContextLock)
                {
                    _immediateContext.UpdateSubresource(d3dBuffer.Buffer, 0, subregion, source, 0, 0);
                }
            }
            else if (useMap)
            {
                MappedResource mr = MapCore(buffer, MapMode.Write, 0);
                if (sizeInBytes < 1024)
                {
                    Unsafe.CopyBlock((byte *)mr.Data + bufferOffsetInBytes, source.ToPointer(), sizeInBytes);
                }
                else
                {
                    System.Buffer.MemoryCopy(
                        source.ToPointer(),
                        (byte *)mr.Data + bufferOffsetInBytes,
                        buffer.SizeInBytes,
                        sizeInBytes);
                }
                UnmapCore(buffer, 0);
            }
            else
            {
                D3D11Buffer staging = GetFreeStagingBuffer(sizeInBytes);
                UpdateBuffer(staging, 0, source, sizeInBytes);
                ResourceRegion sourceRegion = new ResourceRegion(0, 0, 0, (int)sizeInBytes, 1, 1);
                lock (_immediateContextLock)
                {
                    _immediateContext.CopySubresourceRegion(
                        staging.Buffer, 0, sourceRegion,
                        d3dBuffer.Buffer, 0,
                        (int)bufferOffsetInBytes, 0, 0);
                }

                lock (_stagingResourcesLock)
                {
                    _availableStagingBuffers.Add(staging);
                }
            }
        }
Example #13
0
        public static void GetTexture_BGRA4444 <T>(this Texture2D texture, int level, int arraySlice, Rectangle?rect, T[] data, int startIndex, int elementCount) where T : struct
        {
            int num  = Math.Max(texture.Width >> level, 1);
            int num2 = Math.Max(texture.Height >> level, 1);
            Texture2DDescription description = new Texture2DDescription
            {
                Width          = num,
                Height         = num2,
                MipLevels      = 1,
                ArraySize      = 1,
                Format         = DXGI_FORMAT_B4G4R4A4_UNORM,
                BindFlags      = BindFlags.None,
                CpuAccessFlags = CpuAccessFlags.Read
            };

            description.SampleDescription.Count   = 1;
            description.SampleDescription.Quality = 0;
            description.Usage       = ResourceUsage.Staging;
            description.OptionFlags = ResourceOptionFlags.None;

            DeviceContext context = texture.GraphicsDevice._d3dContext();

            using (SharpDX.Direct3D11.Texture2D textured = new SharpDX.Direct3D11.Texture2D(texture.GraphicsDevice._d3dDevice(), description))
            {
                lock (context)
                {
                    int width;
                    int height;
                    SharpDX.DataStream stream;
                    int sourceSubresource = 0;
                    if (rect.HasValue)
                    {
                        width  = rect.Value.Width;
                        height = rect.Value.Height;
                        context.CopySubresourceRegion(texture.GetTexture(), sourceSubresource, new ResourceRegion(rect.Value.Left, rect.Value.Top, 0, rect.Value.Right, rect.Value.Bottom, 1), textured, 0, 0, 0, 0);
                    }
                    else
                    {
                        width  = num;
                        height = texture.Height;
                        context.CopySubresourceRegion(texture.GetTexture(), sourceSubresource, null, textured, 0, 0, 0, 0);
                    }
                    SharpDX.DataBox box  = context.MapSubresource(textured, 0, MapMode.Read, MapFlags.None, out stream);
                    int             num7 = 2 * width;
                    if (num7 == box.RowPitch)
                    {
                        stream.ReadRange <T>(data, startIndex, elementCount);
                    }
                    else
                    {
                        stream.Seek((long)startIndex, SeekOrigin.Begin);
                        int num8 = Marshal.SizeOf(typeof(T));
                        for (int i = 0; i < height; i++)
                        {
                            int index = (i * num7) / num8;
                            while (index < (((i + 1) * num7) / num8))
                            {
                                data[index] = stream.Read <T>();
                                index++;
                            }
                            if (index >= elementCount)
                            {
                                break;
                            }
                            stream.Seek((long)(box.RowPitch - num7), SeekOrigin.Current);
                        }
                    }
                    stream.Dispose();
                }
            }
        }
Example #14
0
        //create a bitmap from a texture2D. DOES NOT WORK
        public static System.Drawing.Bitmap GetTextureBitmap(Device device, Texture2D tex, int mipSlice)
        {
            int w = tex.Description.Width;
            int h = tex.Description.Height;

            var textureCopy = new Texture2D(device, new Texture2DDescription
            {
                Width             = w,
                Height            = h,
                MipLevels         = tex.Description.MipLevels,
                ArraySize         = 1,
                Format            = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
                Usage             = ResourceUsage.Staging,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                BindFlags         = BindFlags.None,
                CpuAccessFlags    = CpuAccessFlags.Read,
                OptionFlags       = ResourceOptionFlags.None
            });
            DataStream dataStream;// = new DataStream(8 * tex.Description.Width * tex.Description.Height, true, true);

            DeviceContext context = device.ImmediateContext;

            //context.CopyResource(tex, textureCopy);
            context.CopySubresourceRegion(tex, mipSlice, null, textureCopy, 0);


            var dataBox = context.MapSubresource(
                textureCopy,
                mipSlice,
                0,
                MapMode.Read,
                SharpDX.Direct3D11.MapFlags.None,
                out dataStream);

            //int bytesize = w * h * 4;
            //byte[] pixels = new byte[bytesize];
            //dataStream.Read(pixels, 0, bytesize);
            //dataStream.Position = 0;

            var dataRectangle = new DataRectangle
            {
                DataPointer = dataStream.DataPointer,
                Pitch       = dataBox.RowPitch
            };


            ImagingFactory wicf = new ImagingFactory();

            var b = new SharpDX.WIC.Bitmap(wicf, w, h, SharpDX.WIC.PixelFormat.Format32bppBGRA, dataRectangle);


            var s = new MemoryStream();

            using (var bitmapEncoder = new PngBitmapEncoder(wicf, s))
            {
                using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder))
                {
                    bitmapFrameEncode.Initialize();
                    bitmapFrameEncode.SetSize(b.Size.Width, b.Size.Height);
                    var pixelFormat = PixelFormat.FormatDontCare;
                    bitmapFrameEncode.SetPixelFormat(ref pixelFormat);
                    bitmapFrameEncode.WriteSource(b);
                    bitmapFrameEncode.Commit();
                    bitmapEncoder.Commit();
                }
            }

            context.UnmapSubresource(textureCopy, 0);
            textureCopy.Dispose();
            b.Dispose();



            s.Position = 0;
            var bmp = new System.Drawing.Bitmap(s);



            //Palette pal = new Palette(wf);
            //b.CopyPalette(pal);

            //byte[] pixels = new byte[w * h * 4];
            //b.CopyPixels(pixels, w * 4);
            //GCHandle handle = GCHandle.Alloc(pixels, GCHandleType.Pinned);
            //var hptr = handle.AddrOfPinnedObject();
            //System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(w, h, w * 4, System.Drawing.Imaging.PixelFormat.Format32bppArgb, hptr);
            //handle.Free();

            //System.Threading.Thread.Sleep(1000);

            //System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(w, h, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
            //System.Drawing.Imaging.BitmapData data = bmp.LockBits(
            //  new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size),
            //  System.Drawing.Imaging.ImageLockMode.WriteOnly,
            //  System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
            ////b.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
            //b.CopyPixels(data.Stride, data.Scan0, data.Height * data.Stride);
            //bmp.UnlockBits(data);


            var c1 = bmp.GetPixel(10, 2);


            //dataStream.Dispose();


            return(bmp);
        }
        public void CopyInstanceCount(DeviceContext ctx, Buffer buffer, int offset)
        {
            ResourceRegion region = new ResourceRegion(offset, 0, 0, offset + 4, 1, 1);

            ctx.CopySubresourceRegion(buffer, 0, region, this.ArgumentBuffer, 0, 4, 0, 0);
        }
 public void UnmapAndCopy(DeviceContext context, Texture2D target)
 {
     dataBox = new DataBox();
     context.UnmapSubresource(texture, 0);
     context.CopySubresourceRegion(texture, 0, null, target, 0);
 }