/// <summary>
        /// Creates a dynamic depth texture, allocates GPU resources
        /// </summary>
        /// <param name="device">Direct3D Device</param>
        /// <param name="frameData">Initial frame data</param>
        public ImmutableInfraredTexture(Device device, InfraredFrameData frameData)
        {
            if (device == null)
                throw new ArgumentNullException("device");
            if (frameData == null)
                throw new ArgumentNullException("frameData");

            DataRectangle rect = new DataRectangle(frameData.DataPointer, Consts.DepthWidth * sizeof(ushort));

            this.texture = new Texture2D(device, InfraredTextureDescriptors.DynamicResource,rect);
            this.shaderView = new ShaderResourceView(device, this.texture);
        }
        /// <summary>
        /// Creates an immutable depth texture, allocates GPU resources
        /// </summary>
        /// <param name="device">Direct3D Device</param>
        /// <param name="data">Depth frame data</param>
        public ImmutableDepthTexture(Device device, DepthFrameData data)
        {
            if (device == null)
                throw new ArgumentNullException("device");
            if (data == null)
                throw new ArgumentNullException("data");

            DataRectangle dr = new DataRectangle(data.DataPointer, Consts.DepthWidth * sizeof(ushort));

            this.texture = new Texture2D(device, DepthTextureDescriptors.ImmutableResource, dr);
            this.rawView = new ShaderResourceView(device,this.texture, DepthTextureDescriptors.RawView);
            this.normalizedView = new ShaderResourceView(device,this.texture, DepthTextureDescriptors.NormalizedView);
        }
Example #3
0
        /// <summary>
        /// Convenience factory to create table from Kinect point list
        /// </summary>
        /// <param name="device">Direct3D Device</param>
        /// <param name="initialData">Initial points array</param>
        /// <returns>Ray table texture</returns>
        public static unsafe RayTableTexture FromPoints(Device device, PointF[] initialData)
        {
            if (initialData.Length != Consts.DepthPixelCount)
                throw new ArgumentException("initialData", "Initial data length should be same size as depth frame pixel count");

            fixed (PointF* ptr = &initialData[0])
            {
                DataRectangle rect = new DataRectangle(new IntPtr(ptr), Consts.DepthWidth * 8);
                var texture = new Texture2D(device, LookupTableTextureDescriptors.DepthToCameraRayTable, rect);
                var view = new ShaderResourceView(device, texture);
                return new RayTableTexture(texture, view);
            }
        }
Example #4
0
        public IImage CreateImage(Color[] colors, int width, double scale = 1.0)
        {
            var factories = Direct2DFactories.Shared;
            var pf = WIC.PixelFormat.Format32bppBGRA;

            unsafe {
                fixed (Color* p = colors) {
                    var data = new DataRectangle {
                        Pitch = width * 4,
                        DataPointer = (IntPtr)p,
                    };
                    var bmp = new WIC.Bitmap (factories.WICFactory, width, colors.Length / width, pf, data);
                    return new WICBitmapSourceImage (bmp, factories);
                }
            }
        }
        private Bitmap GetDX9ScreenShot()
        {
            try
            {
                screenShot = null;
                screenShot = new System.Drawing.Bitmap(WIDTH, HEIGHT, pixelFormat);
                dx9ScreenSurface = SharpDX.Direct3D9.Surface.CreateOffscreenPlain(
                dx9Device,
                WIDTH,
                HEIGHT,
                SharpDX.Direct3D9.Format.A8R8G8B8,
                Pool.SystemMemory);

                dx9Device.GetFrontBufferData(0, dx9ScreenSurface);

                dx9Map = dx9ScreenSurface.LockRectangle(LockFlags.None);
                bmpData = screenShot.LockBits(boundsRect,
                    System.Drawing.Imaging.ImageLockMode.WriteOnly, screenShot.PixelFormat);

                var sourcePtr = dx9Map.DataPointer;
                var destPtr = bmpData.Scan0;
                for (int y = 0; y < HEIGHT; y++)
                {
                    // Copy a single line
                    Utilities.CopyMemory(destPtr, sourcePtr, ARGB_WIDTH);
                    // Advance pointers
                    sourcePtr = IntPtr.Add(sourcePtr, dx9Map.Pitch);
                    destPtr = IntPtr.Add(destPtr, bmpData.Stride);
                }

                screenShot.UnlockBits(bmpData);
                dx9ScreenSurface.UnlockRectangle();
                dx9ScreenSurface.Dispose();
                bmpData = null;
                GC.Collect();
                return screenShot;
            }
            catch (Exception ex)
            {
                LdpLog.Error("GetDX9ScreenShot error.\n" + ex.Message);
                return screenShot = null;
            }
        }
Example #6
0
        private static void Save(IResource res, Stream stream, ImageFileFormat fmt)
        {
            var texture = res.Resource as Texture2D;
            var textureCopy = new Texture2D(MyRender11.Device, new Texture2DDescription
            {
                Width = (int)texture.Description.Width,
                Height = (int)texture.Description.Height,
                MipLevels = 1,
                ArraySize = 1,
                Format = texture.Description.Format,
                Usage = ResourceUsage.Staging,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                BindFlags = BindFlags.None,
                CpuAccessFlags = CpuAccessFlags.Read,
                OptionFlags = ResourceOptionFlags.None
            });
            RC.CopyResource(res, textureCopy);

            DataStream dataStream;
            var dataBox = RC.MapSubresource(
                textureCopy,
                0,
                0,
                MapMode.Read,
                MapFlags.None,
                out dataStream);

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

            var bitmap = new Bitmap(
                MyRender11.WIC,
                textureCopy.Description.Width,
                textureCopy.Description.Height,
                PixelFormatFromFormat(textureCopy.Description.Format), // TODO: should use some conversion from textureCopy.Description.Format
                dataRectangle);

            using (var wicStream = new WICStream(MyRender11.WIC, stream))
            {
                BitmapEncoder bitmapEncoder;
                switch (fmt)
                {
                    case ImageFileFormat.Png:
                        bitmapEncoder = new PngBitmapEncoder(MyRender11.WIC, wicStream);
                        break;
                    case ImageFileFormat.Jpg:
                        bitmapEncoder = new JpegBitmapEncoder(MyRender11.WIC, wicStream);
                        break;
                    case ImageFileFormat.Bmp:
                        bitmapEncoder = new BmpBitmapEncoder(MyRender11.WIC, wicStream);
                        break;
                    default:
                        MyRenderProxy.Assert(false, "Unsupported file format.");
                        bitmapEncoder = null;
                        break;
                }
                if (bitmapEncoder != null)
                {
                    using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder))
                    {
                        bitmapFrameEncode.Initialize();
                        bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height);
                        var pixelFormat = PixelFormat.FormatDontCare;
                        bitmapFrameEncode.SetPixelFormat(ref pixelFormat);
                        bitmapFrameEncode.WriteSource(bitmap);
                        bitmapFrameEncode.Commit();
                        bitmapEncoder.Commit();
                    }
                    bitmapEncoder.Dispose();
                }
            }

            RC.UnmapSubresource(textureCopy, 0);
            textureCopy.Dispose();
            bitmap.Dispose();
        }
Example #7
0
        public Texture2D GetTexture2D(Device device)
        {
            IntPtr unmanagedPtr = Marshal.AllocHGlobal(PixelCount);
            Marshal.Copy(GetPixelData(), 0, unmanagedPtr, PixelCount);
            DataRectangle data = new DataRectangle();
            data.DataPointer = unmanagedPtr;
            data.Pitch = Width * 4;

            Texture2DDescription textureDesc = new Texture2DDescription
            {
                ArraySize = 1,
                BindFlags = BindFlags.ShaderResource,
                Usage = ResourceUsage.Dynamic,
                CpuAccessFlags = CpuAccessFlags.Write,
                Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                Height = Height,
                Width = Width,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0)
            };

            Texture2D texture = new Texture2D(device, textureDesc, data);
            Marshal.FreeHGlobal(unmanagedPtr);
            return texture;
        }
Example #8
0
 private static Texture2D CreateTexture2DFromBitmapSource(Device device, BitmapSource bitmapSource, TextureLoadOptions options) {
     // Allocate DataStream to receive the WIC image pixels
     var stride = bitmapSource.Size.Width * 4;
     using (var buffer = new DataStream(bitmapSource.Size.Height * stride, true, true)) {
         // Copy the content of the WIC to the buffer
         bitmapSource.CopyPixels(stride, buffer);
         var texture2DDescription = new Texture2DDescription() {
             Width = bitmapSource.Size.Width,
             Height = bitmapSource.Size.Height,
             ArraySize = 1,
             BindFlags = options.BindFlags,
             Usage = options.ResourceUsage,
             CpuAccessFlags = options.CpuAccessFlags,
             Format = options.Format,
             MipLevels = options.MipLevels,
             OptionFlags = ResourceOptionFlags.None,
             SampleDescription = new SampleDescription(1, 0),
         };
         bitmapSource.Dispose();
         var dataRectangle = new DataRectangle(buffer.DataPointer, stride);
         return new Texture2D(device, texture2DDescription, dataRectangle);
     }
 }
Example #9
0
        Texture2D createTextureFromFile(string filename)
        {
            BitmapImage loadedImage = new BitmapImage();

            loadedImage.BeginInit();
            loadedImage.CacheOption = BitmapCacheOption.OnLoad;
            loadedImage.UriSource = new Uri(filename);
            loadedImage.EndInit();

            loadedImage.Freeze();

            int stride = loadedImage.PixelWidth * (loadedImage.Format.BitsPerPixel / 8);

            byte[] pixels = new byte[loadedImage.PixelHeight * stride];

            loadedImage.CopyPixels(pixels, stride, 0);

            pinnedArray = GCHandle.Alloc(pixels, GCHandleType.Pinned);
            IntPtr pixelPtr = pinnedArray.AddrOfPinnedObject();

            DataRectangle data = new DataRectangle(pixelPtr, stride);           

            var texDesc = new Texture2DDescription
            {
                ArraySize = 1,
                BindFlags = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.B8G8R8A8_UNorm,
                Height = loadedImage.PixelHeight,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                Width = loadedImage.PixelWidth
            };

            Texture2D texture = new Texture2D(Host.Device, texDesc, data);
                               
            return (texture);            
        }
        private Bitmap GetDX11ScreenShot()
        {
            try
            {
                screenShot = null;
                screenShot = new Bitmap(WIDTH, HEIGHT, this.pixelFormat);
                if (dx11DuplicatedOutput != null)
                {

                    dx11DuplicatedOutput.AcquireNextFrame(NEXT_FRAME_TIMEOUT,
                        out dx11DuplFrameInfo, out dx11ScreenResource);

                    dx11Device.ImmediateContext
                        .CopyResource(dx11ScreenResource.QueryInterface<SharpDX.Direct3D11.Resource>(),
                        dx11ScreenTexture);

                    // cast from texture to surface, so we can access its bytes
                    dx11ScreenSurface = dx11ScreenTexture.QueryInterface<SharpDX.DXGI.Surface>();
                    // map the resource to access it
                    dx11Map = dx11ScreenSurface.Map(SharpDX.DXGI.MapFlags.Read);
                    bmpData = screenShot.LockBits(boundsRect, ImageLockMode.WriteOnly, screenShot.PixelFormat);
                    var sourcePtr = dx11Map.DataPointer;
                    var destPtr = bmpData.Scan0;
                    for (int y = 0; y < HEIGHT; y++)
                    {
                        // Copy a single line
                        Utilities.CopyMemory(destPtr, sourcePtr, ARGB_WIDTH);
                        // Advance pointers
                        sourcePtr = IntPtr.Add(sourcePtr, dx11Map.Pitch);
                        destPtr = IntPtr.Add(destPtr, bmpData.Stride);
                    }

                    dx11Device.ImmediateContext.UnmapSubresource(dx11ScreenTexture, 0);
                    screenShot.UnlockBits(bmpData);
                    dx11ScreenSurface.Unmap();
                    dx11ScreenSurface.Dispose();
                    dx11ScreenResource.Dispose();
                    dx11DuplicatedOutput.ReleaseFrame();
                }
                else return screenShot = null;

                dx11ScreenSurface = null;
                bmpData = null;
                GC.Collect();

                return screenShot;
            }
            catch (SharpDX.SharpDXException e)
            {
                if (e.ResultCode.Code == SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code)
                {
                    //screen does not changed
                    LdpLog.Warning("DX11 surface timeout.. Recursion is coming:)");
                    return GetDX11ScreenShot();
                }
                else { return screenShot = null; }
            }
            catch (Exception ex)
            {
                LdpLog.Error("GetDX11ScreenShot\n" + ex.Message);
                return screenShot = null;
            }
        }
Example #11
0
        private static DxTexture ReadTextureCubeFromStream(GtexData gtex, Stream input)
        {
            Texture2DDescription descriptor = GetTextureCubeDescription(gtex);

            using (SafeUnmanagedArray array = new SafeUnmanagedArray(gtex.MipMapData.Sum(d => d.Length)))
            {
                DataRectangle[] rects = new DataRectangle[gtex.MipMapData.Length];
                using (UnmanagedMemoryStream io = array.OpenStream(FileAccess.Write))
                {
                    byte[] buff = new byte[32 * 1024];
                    for (int index = 0; index < gtex.MipMapData.Length; index++)
                    {
                        GtexMipMapLocation mimMap = gtex.MipMapData[index];
                        Int32 pitch = GetPitch(descriptor, index);
                        rects[index] = CreateDataRectangle(array, io, pitch);
                        input.SetPosition(mimMap.Offset);
                        input.CopyToStream(io, mimMap.Length, buff);
                    }
                }

                Texture2D texture = new Texture2D(_device, descriptor, rects);

                // Workaround
                _textureCreatingWorkaround(_device.ImmediateContext, texture, ImageFileFormat.Dds);

                return new DxTexture(texture, descriptor);
            }
        }
        private async void context_DeviceReset(object sender, DeviceResetEventArgs e)
        {
            this.ReleaseResources();

            string assetsPath = Package.Current.InstalledLocation.Path + "/Assets/Render/";

            byte[] vertexShaderByteCode = NativeFile.ReadAllBytes(assetsPath + "MiniCubeTexture_VS.fxo");
            this.vertexShader = new VertexShader(this.parentContext.D3DDevice, vertexShaderByteCode);

            byte[] pixelShaderByteCode = NativeFile.ReadAllBytes(assetsPath + "MiniCubeTexture_PS.fxo");
            this.pixelShader = new PixelShader(this.parentContext.D3DDevice, pixelShaderByteCode);

            this.vertexLayout = new InputLayout(this.parentContext.D3DDevice, vertexShaderByteCode, new[]
            {
                new InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32A32_Float, 0, 0),
                new InputElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32_Float, 16, 0)
            });

            SharpDX.Direct3D11.Buffer vertices = SharpDX.Direct3D11.Buffer.Create(this.parentContext.D3DDevice, BindFlags.VertexBuffer, new[]
            {
                -0.5f, -0.5f, -0.5f, 0.5f,     0.0f, 1.0f,
                -0.5f,  0.5f, -0.5f, 0.5f,     0.0f, 0.0f,
                0.5f,  0.5f, -0.5f, 0.5f,     1.0f, 0.0f,
                -0.5f, -0.5f, -0.5f, 0.5f,     0.0f, 1.0f,
                0.5f,  0.5f, -0.5f, 0.5f,     1.0f, 0.0f,
                0.5f, -0.5f, -0.5f, 0.5f,     1.0f, 1.0f,
            });

            this.vertexBufferBinding = new VertexBufferBinding(vertices, sizeof(float) * 6, 0);

            this.constantBuffer = new SharpDX.Direct3D11.Buffer(this.parentContext.D3DDevice, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            this.sampler = new SamplerState(this.parentContext.D3DDevice, new SamplerStateDescription()
            {
                Filter = Filter.MinMagMipLinear,
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                BorderColor = Color.Black,
                ComparisonFunction = Comparison.Never,
                MaximumAnisotropy = 16,
                MipLodBias = 0,
                MinimumLod = -float.MaxValue,
                MaximumLod = float.MaxValue
            });

#if SILVERLIGHT
            Deployment.Current.Dispatcher.BeginInvoke(() =>
#else
            await CoreWindow.GetForCurrentThread().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
#endif

            {
                using (MemoryStream sourceStream = new MemoryStream(NativeFile.ReadAllBytes(assetsPath + "sharpdx.png")))
                {
#if SILVERLIGHT
                    BitmapImage image = new BitmapImage();
                    image.CreateOptions = BitmapCreateOptions.None;
                    image.SetSource(sourceStream);

                    WriteableBitmap bitmap = new WriteableBitmap(image);

                    using (DataStream dataStream = new DataStream(bitmap.Pixels.Length * 4, true, true))
                    {
                        dataStream.WriteRange<int>(bitmap.Pixels);
#else
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream.AsRandomAccessStream());
                    BitmapFrame bitmap = await decoder.GetFrameAsync(0);
                    PixelDataProvider dataProvider = await bitmap.GetPixelDataAsync(BitmapPixelFormat.Bgra8,
                        BitmapAlphaMode.Premultiplied,
                        new BitmapTransform(),
                        ExifOrientationMode.IgnoreExifOrientation,
                        ColorManagementMode.DoNotColorManage);
                    byte[] pixelData = dataProvider.DetachPixelData();

                    using (DataStream dataStream = new DataStream(pixelData.Length, true, true))
                    {
                        dataStream.WriteRange<byte>(pixelData);
#endif

                        dataStream.Seek(0, SeekOrigin.Begin);

                        DataRectangle dataRectangle = new DataRectangle(dataStream.DataPointer, (int)(bitmap.PixelWidth * 4));

                        this.texture = new Texture2D(this.parentContext.D3DDevice, new Texture2DDescription()
                        {
                            Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                            Width = (int)bitmap.PixelWidth,
                            Height = (int)bitmap.PixelHeight,
                            ArraySize = 1,
                            MipLevels = 1,
                            BindFlags = BindFlags.ShaderResource,
                            Usage = ResourceUsage.Default,
                            CpuAccessFlags = CpuAccessFlags.None,
                            OptionFlags = ResourceOptionFlags.None,
                            SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0)
                        }, dataRectangle);

                        this.textureView = new ShaderResourceView(this.parentContext.D3DDevice, this.texture);
                    }

#if SILVERLIGHT
                    bitmap = null;
                    image = null;
#else
                    pixelData = null;
                    dataProvider = null;
                    bitmap = null;
                    decoder = null;
#endif
                }
            });
        }
        public unsafe Texture2D GetTexture(Imaging.ImageFile source)
        {
            var key = source.Path;

            Texture2D tex;
            if (_Textures.TryGetValue(key, out tex))
                return tex;

            byte[] buffer;
            var desc = new Texture2DDescription {
                ArraySize = 1,
                BindFlags = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Height = source.Height,
                Width = source.Width,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage = ResourceUsage.Immutable
            };
            if (source.Format == Imaging.ImageFormat.A16R16G16B16Float) {
                buffer = source.GetData();
                desc.Format = SharpDX.DXGI.Format.R16G16B16A16_Float;
            } else {
                buffer = Imaging.ImageConverter.GetA8R8G8B8(source);
                for (var i = 0; i < buffer.Length; i += 4) {
                    var r = buffer[i + 0];
                    var b = buffer[i + 2];

                    buffer[i + 0] = b;
                    buffer[i + 2] = r;
                }
                desc.Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm;
                if (source.Format == Imaging.ImageFormat.A8R8G8B8_Cube)
                    desc.ArraySize = 6;
            }

            fixed (byte* p = buffer) {
                var ptr = (IntPtr)p;
                var pitch = SharpDX.DXGI.FormatHelper.SizeOfInBytes(desc.Format) * source.Width;
                var dataRects = new DataRectangle[desc.ArraySize];
                for (var i = 0; i < desc.ArraySize; ++i)
                    dataRects[i] = new DataRectangle(ptr + i * pitch * source.Height, pitch);
                tex = new Texture2D(_Engine.Device, desc, dataRects);
            }

            _Textures.Add(key, tex);
            return tex;
        }