Ejemplo n.º 1
0
        /// <summary>
        ///		空のテクスチャとそのシェーダーリソースビューを作成し、返す。
        /// </summary>
        public static (SharpDX.Direct3D11.ShaderResourceView srv, SharpDX.Direct3D11.Texture2D texture) CreateShaderResourceView(
            SharpDX.Direct3D11.Device d3dDevice,
            SharpDX.Direct3D11.BindFlags bindFlags,
            Size2 サイズ)
        {
            var textureDesc = new SharpDX.Direct3D11.Texture2DDescription()
            {
                ArraySize         = 1,
                BindFlags         = bindFlags,
                CpuAccessFlags    = SharpDX.Direct3D11.CpuAccessFlags.None,
                Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                Height            = サイズ.Height,
                Width             = サイズ.Width,
                MipLevels         = 1,
                OptionFlags       = SharpDX.Direct3D11.ResourceOptionFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage             = SharpDX.Direct3D11.ResourceUsage.Default
            };

            var 出力 = (srv : (SharpDX.Direct3D11.ShaderResourceView)null, texture : (SharpDX.Direct3D11.Texture2D)null);

            出力.texture = new SharpDX.Direct3D11.Texture2D(d3dDevice, textureDesc);
            出力.srv     = new SharpDX.Direct3D11.ShaderResourceView(d3dDevice, 出力.texture);

            return(出力);
        }
Ejemplo n.º 2
0
        private void Form1_Load(object sender, EventArgs e)
        {
            device   = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.None, SharpDX.Direct3D.FeatureLevel.Level_11_0);
            c_device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.None, SharpDX.Direct3D.FeatureLevel.Level_11_1);
            factory  = new SharpDX.DXGI.Factory1();

            int width  = factory.Adapters1[numAdapter].Outputs[numOutput].Description.DesktopBounds.Width;
            int height = factory.Adapters1[numAdapter].Outputs[numOutput].Description.DesktopBounds.Height;

            target = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            // creating CPU-accessible texture resource
            SharpDX.Direct3D11.Texture2DDescription texdes = new SharpDX.Direct3D11.Texture2DDescription();
            texdes.CpuAccessFlags            = SharpDX.Direct3D11.CpuAccessFlags.Read;
            texdes.BindFlags                 = SharpDX.Direct3D11.BindFlags.None;
            texdes.Format                    = SharpDX.DXGI.Format.B8G8R8A8_UNorm;
            texdes.Height                    = height;
            texdes.Width                     = width;
            texdes.OptionFlags               = SharpDX.Direct3D11.ResourceOptionFlags.Shared;
            texdes.MipLevels                 = 1;
            texdes.ArraySize                 = 1;
            texdes.SampleDescription.Count   = 1;
            texdes.SampleDescription.Quality = 0;
            texdes.Usage                     = SharpDX.Direct3D11.ResourceUsage.Staging;

            screenTexture        = new SharpDX.Direct3D11.Texture2D(c_device, texdes);
            sharedResourceHandle = screenTexture.QueryInterface <SharpDX.DXGI.Resource>().SharedHandle;
            sharedTexture        = device.OpenSharedResource <SharpDX.Direct3D11.Texture2D>(sharedResourceHandle);


            output           = new SharpDX.DXGI.Output1(factory.Adapters1[numAdapter].Outputs[numOutput].NativePointer);
            duplicatedOutput = output.DuplicateOutput(c_device);
        }
        private SharpDX.Direct3D11.Texture2D AllocateTextureReturnSurface(int drawingSizeWidth, int drawingSizeHeight)
        {
            
            // Setup local variables
            var d3dDevice = _deviceManager.DeviceDirect3D;
            var d3dContext = _deviceManager.ContextDirect3D;
            var d2dDevice = _deviceManager.DeviceDirect2D;
            var d2dContext = _deviceManager.ContextDirect2D;

            var desc = new SharpDX.Direct3D11.Texture2DDescription()
            {
                Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, //  D24_UNorm_S8_UInt,
                ArraySize = 1,
                MipLevels = 1,
                Width = drawingSizeWidth,
                Height = drawingSizeHeight,
                Usage = SharpDX.Direct3D11.ResourceUsage.Default,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                BindFlags = SharpDX.Direct3D11.BindFlags.RenderTarget | SharpDX.Direct3D11.BindFlags.ShaderResource,
            };

            desc.Usage = SharpDX.Direct3D11.ResourceUsage.Default;
            var tex2D = new SharpDX.Direct3D11.Texture2D(d3dDevice, desc);
            return tex2D;


        }
        private SharpDX.Direct3D11.Texture2D AllocateTextureReturnSurface(int drawingSizeWidth, int drawingSizeHeight)
        {
            // Setup local variables
            var d3dDevice  = _deviceManager.DeviceDirect3D;
            var d3dContext = _deviceManager.ContextDirect3D;
            var d2dDevice  = _deviceManager.DeviceDirect2D;
            var d2dContext = _deviceManager.ContextDirect2D;

            var desc = new SharpDX.Direct3D11.Texture2DDescription()
            {
                Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm, //  D24_UNorm_S8_UInt,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = drawingSizeWidth,
                Height            = drawingSizeHeight,
                Usage             = SharpDX.Direct3D11.ResourceUsage.Default,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                BindFlags         = SharpDX.Direct3D11.BindFlags.RenderTarget | SharpDX.Direct3D11.BindFlags.ShaderResource,
            };

            desc.Usage = SharpDX.Direct3D11.ResourceUsage.Default;
            var tex2D = new SharpDX.Direct3D11.Texture2D(d3dDevice, desc);

            return(tex2D);
        }
Ejemplo n.º 5
0
        internal override SharpDX.Direct3D11.Resource CreateTexture()
		{
            // TODO: Move this to SetData() if we want to make Immutable textures!
            var desc = new SharpDX.Direct3D11.Texture2DDescription();
            desc.Width = width;
            desc.Height = height;
            desc.MipLevels = _levelCount;
            desc.ArraySize = 1;
            desc.Format = SharpDXHelper.ToFormat(_format);
            desc.BindFlags = SharpDX.Direct3D11.BindFlags.ShaderResource;
            desc.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None;
            desc.SampleDescription.Count = 1;
            desc.SampleDescription.Quality = 0;
            desc.Usage = SharpDX.Direct3D11.ResourceUsage.Default;
            desc.OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None;

            if (_renderTarget)
            {
                desc.BindFlags |= SharpDX.Direct3D11.BindFlags.RenderTarget;
                if (_mipmap)
                {
                    // Note: XNA 4 does not have a method Texture.GenerateMipMaps() 
                    // because generation of mipmaps is not supported on the Xbox 360.
                    // TODO: New method Texture.GenerateMipMaps() required.
                    desc.OptionFlags |= SharpDX.Direct3D11.ResourceOptionFlags.GenerateMipMaps;
                }
            }
            if (_shared)
                desc.OptionFlags |= SharpDX.Direct3D11.ResourceOptionFlags.Shared;

            return new SharpDX.Direct3D11.Texture2D(GraphicsDevice._d3dDevice, desc);
        }
Ejemplo n.º 6
0
 void UpdateLayout(SharpDX.ViewportF viewport, SharpDX.Direct3D11.Texture2DDescription newBackBuffer)
 {
     InventoryButton.Bounds = new UniRectangle(20, viewport.Height - 90, 64, 64);
     CraftingButton.Bounds  = new UniRectangle(104, viewport.Height - 84, 64, 64);
     _inventoryLabel.Bounds = new UniRectangle(47, viewport.Height - 30, 20, 20);
     _craftingLabel.Bounds  = new UniRectangle(134, viewport.Height - 30, 20, 20);
 }
Ejemplo n.º 7
0
        private void InitializeBlankTexture(SizeInt32 size)
        {
            var description = new SharpDX.Direct3D11.Texture2DDescription
            {
                Width             = size.Width,
                Height            = size.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                SampleDescription = new SharpDX.DXGI.SampleDescription()
                {
                    Count   = 1,
                    Quality = 0
                },
                Usage          = SharpDX.Direct3D11.ResourceUsage.Default,
                BindFlags      = SharpDX.Direct3D11.BindFlags.ShaderResource | SharpDX.Direct3D11.BindFlags.RenderTarget,
                CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None,
                OptionFlags    = SharpDX.Direct3D11.ResourceOptionFlags.None
            };

            _blankTexture = new SharpDX.Direct3D11.Texture2D(_d3dDevice, description);

            using (var renderTargetView = new SharpDX.Direct3D11.RenderTargetView(_d3dDevice, _blankTexture))
            {
                _d3dDevice.ImmediateContext.ClearRenderTargetView(renderTargetView, new SharpDX.Mathematics.Interop.RawColor4(0, 0, 0, 1));
            }
        }
Ejemplo n.º 8
0
        public SharpDX.DataStream CaptureScreen()
        {
            // try to get duplicated frame within given time
            try
            {
                OutputDuplicateFrameInformation duplicateFrameInformation;
                duplicatedOutput.AcquireNextFrame(1000, out duplicateFrameInformation, out screenResource);

                // copy resource into memory that can be accessed by the CPU
                device.ImmediateContext.CopyResource(screenResource.QueryInterface <SharpDX.Direct3D11.Resource>(), screenTexture);
                // cast from texture to surface, so we can access its bytes
                screenSurface = screenTexture.QueryInterface <SharpDX.DXGI.Surface>();

                // map the resource to access it
                screenSurface.Map(MapFlags.Read, out dataStream);

                // seek within the stream and read one byte
                //dataStream.Position = 4;
                //dataStream.ReadByte();

                // free resources
                //dataStream.Close();
                screenSurface.Unmap();
                screenSurface.Dispose();
                screenResource.Dispose();
                duplicatedOutput.ReleaseFrame();
                return(dataStream);
            }
            catch (SharpDX.SharpDXException e)
            {
                device  = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware);
                factory = new Factory1();
                // creating CPU-accessible texture resource
                texdes = new SharpDX.Direct3D11.Texture2DDescription();
                texdes.CpuAccessFlags            = SharpDX.Direct3D11.CpuAccessFlags.Read;
                texdes.BindFlags                 = SharpDX.Direct3D11.BindFlags.None;
                texdes.Format                    = Format.B8G8R8A8_UNorm;
                texdes.Height                    = factory.Adapters1[numAdapter].Outputs[numOutput].Description.DesktopBounds.Height;
                texdes.Width                     = factory.Adapters1[numAdapter].Outputs[numOutput].Description.DesktopBounds.Width;
                texdes.OptionFlags               = SharpDX.Direct3D11.ResourceOptionFlags.None;
                texdes.MipLevels                 = 1;
                texdes.ArraySize                 = 1;
                texdes.SampleDescription.Count   = 1;
                texdes.SampleDescription.Quality = 0;
                texdes.Usage                     = SharpDX.Direct3D11.ResourceUsage.Staging;
                screenTexture                    = new SharpDX.Direct3D11.Texture2D(device, texdes);

                // duplicate output stuff
                output = new Output1(factory.Adapters1[numAdapter].Outputs[numOutput].NativePointer);
                try
                {
                    duplicatedOutput = output.DuplicateOutput(device);
                }
                catch { }
                return(CaptureScreen());
            }
        }
        /// <summary>
        /// Saves the contents of a <see cref="SharpDX.Direct3D11.Texture2D"/> to a file with name contained in <paramref name="filename"/> using the specified <see cref="System.Drawing.Imaging.ImageFormat"/>.
        /// </summary>
        /// <param name="texture">The <see cref="SharpDX.Direct3D11.Texture2D"/> containing the data to save.</param>
        /// <param name="filename">The filename on disk where the output image should be saved.</param>
        /// <param name="imageFormat">The format to use when saving the output file.</param>
        public void SaveTextureToFile(SharpDX.Direct3D11.Texture2D texture, string filename, System.Drawing.Imaging.ImageFormat imageFormat)
        {
            // If the existing debug texture doesn't exist, or the incoming texture is different than the existing debug texture...
            if (m_pDebugTexture == null || !TextureCanBeCopied(m_pDebugTexture, texture))
            {
                // Dispose of any existing texture
                if (m_pDebugTexture != null)
                {
                    m_pDebugTexture.Dispose();
                }

                // Copy the original texture's description...
                SharpDX.Direct3D11.Texture2DDescription newDescription = texture.Description;

                // Then modify the parameters to create a CPU-readable staging texture
                newDescription.BindFlags      = SharpDX.Direct3D11.BindFlags.None;
                newDescription.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.Read;
                newDescription.OptionFlags    = SharpDX.Direct3D11.ResourceOptionFlags.None;
                newDescription.Usage          = SharpDX.Direct3D11.ResourceUsage.Staging;

                // Re-generate the debug texture by copying the new texture's description
                m_pDebugTexture = new SharpDX.Direct3D11.Texture2D(m_pDevice, newDescription);
            }

            // Copy the texture to our debug texture
            m_pDevice.ImmediateContext.CopyResource(texture, m_pDebugTexture);

            // Map the debug texture's resource 0 for read mode
            SharpDX.DataStream data;
            SharpDX.DataBox    dbox = m_pDevice.ImmediateContext.MapSubresource(m_pDebugTexture, 0, 0, SharpDX.Direct3D11.MapMode.Read, SharpDX.Direct3D11.MapFlags.None, out data);

            // Create a bitmap that's the same size as the debug texture
            Bitmap b = new Bitmap(m_pDebugTexture.Description.Width, m_pDebugTexture.Description.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);

            // Lock the bitmap data to get access to the native bitmap pointer
            System.Drawing.Imaging.BitmapData bd = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);

            // Use the native pointers to do a native-to-native memory copy from the mapped subresource to the bitmap data
            // WARNING: This might totally blow up if you're using a different color format than B8G8R8A8_UNorm, I don't know how planar formats are structured as D3D textures!
            //
            // You can use Win32 CopyMemory to do the below copy if need be, but you have to do it in a loop to respect the Stride and RowPitch parameters in case the texture width
            // isn't on an aligned byte boundary.
            MediaFoundation.MFExtern.MFCopyImage(bd.Scan0, bd.Stride, dbox.DataPointer, dbox.RowPitch, bd.Width * 4, bd.Height);

            /// Unlock the bitmap
            b.UnlockBits(bd);

            // Unmap the subresource mapping, ignore the SharpDX.DataStream because we don't need it.
            m_pDevice.ImmediateContext.UnmapSubresource(m_pDebugTexture, 0);
            data = null;

            // Save the bitmap to the desired filename
            b.Save(filename, imageFormat);
            b.Dispose();
            b = null;
        }
Ejemplo n.º 10
0
        public byte[] GetPixelBytes(int left, int top, int width, int height)
        {
            if (width <= 0 || height <= 0)
            {
                return(new byte[] { });
            }
            var device      = _texture.Device;
            var description =
                new SharpDX.Direct3D11.Texture2DDescription()
            {
                Width             = width,
                Height            = height,
                Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                ArraySize         = 1,
                MipLevels         = 1,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage             = SharpDX.Direct3D11.ResourceUsage.Staging,
                BindFlags         = SharpDX.Direct3D11.BindFlags.None,
                CpuAccessFlags    = SharpDX.Direct3D11.CpuAccessFlags.Read,
                OptionFlags       = SharpDX.Direct3D11.ResourceOptionFlags.None
            };

            byte[] result = new byte[width * height * 4];
            using (var staging = new SharpDX.Direct3D11.Texture2D(device, description))
            {
                var textureWidth  = _texture.Description.Width;
                var textureHeight = _texture.Description.Height;
                var srcX0         = Math.Max(0, left);
                var srcY0         = Math.Max(0, top);
                var srcX1         = Math.Min(textureWidth, Math.Max(0, left + width));
                var srcY1         = Math.Min(textureHeight, Math.Max(0, top + height));
                if (srcX1 <= srcX0 || srcY1 <= srcY0)
                {
                    return(new byte[] { });
                }
                var region = new SharpDX.Direct3D11.ResourceRegion(srcX0, srcY0, 0, srcX1, srcY1, 1);
                var dstX0  = Math.Max(0, -left);
                var dstY0  = Math.Max(0, -top);
                device.ImmediateContext.CopySubresourceRegion(_texture, 0, region, staging, 0, dstX0, dstY0);
                var box = device.ImmediateContext.MapSubresource(
                    staging, 0, SharpDX.Direct3D11.MapMode.Read, SharpDX.Direct3D11.MapFlags.None);
                for (int i = 0; i < height; ++i)
                {
                    Marshal.Copy(box.DataPointer + i * box.RowPitch, result, i * width * 4, width * 4);
                }
                device.ImmediateContext.UnmapSubresource(staging, 0);
            }
            return(result);
        }
Ejemplo n.º 11
0
 public void ProcessFrame(ref FrameData data, DeviceContextProxy context)
 {
     if (sharedTexture == null || sharedDescription.Width != data.Frame.Description.Width || sharedDescription.Height != data.Frame.Description.Height)
     {
         RemoveAndDispose(ref sharedTexture);
         sharedDescription = new Texture2DDescription()
         {
             BindFlags      = BindFlags.ShaderResource,
             CpuAccessFlags = CpuAccessFlags.None, Format = data.Frame.Description.Format, Width = data.Frame.Description.Width, Height = data.Frame.Description.Height,
             MipLevels      = 1, Usage = ResourceUsage.Default, SampleDescription = new SampleDescription(1, 0), OptionFlags = ResourceOptionFlags.None, ArraySize = 1
         };
         sharedTexture = Collect(new Texture2D(context.DeviceContext.Device, sharedDescription));
     }
     context.DeviceContext.CopyResource(data.Frame, sharedTexture);
 }
Ejemplo n.º 12
0
        private void InitGrabber()
        {
            try
            {
                this.pixelFormat = PixelFormat.Format32bppRgb;
                boundsRect       = new System.Drawing.Rectangle(0, 0, WIDTH, HEIGHT);

                uint numAdapter = 0;   // # of graphics card adapter
                uint numOutput  = 0;   // # of output device (i.e. monitor)

                // create device and factory
                dx11Device  = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware);
                dx11Factory = new Factory1();
                dx11Output  = new Output1(dx11Factory.Adapters1[numAdapter].Outputs[numOutput].NativePointer);

                // creating CPU-accessible texture resource
                dx11Texture2Ddescr = new SharpDX.Direct3D11.Texture2DDescription();
                dx11Texture2Ddescr.CpuAccessFlags            = SharpDX.Direct3D11.CpuAccessFlags.Read;
                dx11Texture2Ddescr.BindFlags                 = SharpDX.Direct3D11.BindFlags.None;
                dx11Texture2Ddescr.Format                    = SharpDX.DXGI.Format.B8G8R8A8_UNorm;
                dx11Texture2Ddescr.Height                    = HEIGHT;
                dx11Texture2Ddescr.Width                     = WIDTH;
                dx11Texture2Ddescr.OptionFlags               = SharpDX.Direct3D11.ResourceOptionFlags.None;
                dx11Texture2Ddescr.MipLevels                 = 1;
                dx11Texture2Ddescr.ArraySize                 = 1;
                dx11Texture2Ddescr.SampleDescription.Count   = 1;
                dx11Texture2Ddescr.SampleDescription.Quality = 0;
                dx11Texture2Ddescr.Usage                     = SharpDX.Direct3D11.ResourceUsage.Staging;
                dx11ScreenTexture = new SharpDX.Direct3D11.Texture2D(dx11Device, dx11Texture2Ddescr);

                // duplicate output stuff

                dx11DuplicatedOutput = dx11Output.DuplicateOutput(dx11Device);
            }
            catch (SharpDX.SharpDXException dxe)
            {
                string error = "Directx 11 initializer error.\n" + dxe.Message;
                LdpLog.Error(error);
                MessageBox.Show(error, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                string error = "Directx 11 initializer error.\n" + ex.Message;
                LdpLog.Error(error);
                MessageBox.Show(error, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Ejemplo n.º 13
0
        // グラフィック

        /// <summary>
        ///		画像ファイルからシェーダリソースビューを作成して返す。
        /// </summary>
        /// <remarks>
        ///		(参考: http://qiita.com/oguna/items/c516e09ee57d931892b6 )
        /// </remarks>
        public static (SharpDX.Direct3D11.ShaderResourceView srv, Size2F viewSize, SharpDX.Direct3D11.Texture2D texture) CreateShaderResourceViewFromFile(
            SharpDX.Direct3D11.Device d3dDevice,
            SharpDX.Direct3D11.BindFlags bindFlags,
            VariablePath 画像ファイルパス)
        {
            var 出力 = (
                srv : (SharpDX.Direct3D11.ShaderResourceView)null,
                viewSize : new Size2F(0, 0),
                texture : (SharpDX.Direct3D11.Texture2D)null);

            using (var image = new System.Drawing.Bitmap(画像ファイルパス.数なしパス))
            {
                var 画像の矩形 = new System.Drawing.Rectangle(0, 0, image.Width, image.Height);

                using (var bitmap = image.Clone(画像の矩形, System.Drawing.Imaging.PixelFormat.Format32bppArgb))
                {
                    var ロック領域       = bitmap.LockBits(画像の矩形, System.Drawing.Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat);
                    var dataBox     = new[] { new DataBox(ロック領域.Scan0, bitmap.Width * 4, bitmap.Height) };
                    var textureDesc = new SharpDX.Direct3D11.Texture2DDescription()
                    {
                        ArraySize         = 1,
                        BindFlags         = bindFlags,
                        CpuAccessFlags    = SharpDX.Direct3D11.CpuAccessFlags.None,
                        Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                        Height            = bitmap.Height,
                        Width             = bitmap.Width,
                        MipLevels         = 1,
                        OptionFlags       = SharpDX.Direct3D11.ResourceOptionFlags.None,
                        SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                        Usage             = SharpDX.Direct3D11.ResourceUsage.Default
                    };
                    var texture = new SharpDX.Direct3D11.Texture2D(d3dDevice, textureDesc, dataBox);
                    bitmap.UnlockBits(ロック領域);
                    出力.srv     = new SharpDX.Direct3D11.ShaderResourceView(d3dDevice, texture);
                    出力.texture = texture;
                }

                出力.viewSize = new Size2F(画像の矩形.Width, 画像の矩形.Height);
            }

            return(出力);
        }
Ejemplo n.º 14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="device"></param>
        /// <param name="w"></param>
        /// <param name="h"></param>
        /// <param name="flags"></param>
        /// <param name="format"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static SharpDX.Direct3D11.Texture2D CreateTexture2D(this SharpDX.Direct3D11.Device device,
                                                                   int w, int h,
                                                                   SharpDX.Direct3D11.BindFlags flags = SharpDX.Direct3D11.BindFlags.RenderTarget | SharpDX.Direct3D11.BindFlags.ShaderResource,
                                                                   Format format = Format.B8G8R8A8_UNorm,
                                                                   SharpDX.Direct3D11.ResourceOptionFlags options = SharpDX.Direct3D11.ResourceOptionFlags.Shared)
        {
            var colordesc = new SharpDX.Direct3D11.Texture2DDescription
            {
                BindFlags         = flags,
                Format            = format,
                Width             = w,
                Height            = h,
                MipLevels         = 1,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = SharpDX.Direct3D11.ResourceUsage.Default,
                OptionFlags       = options,
                CpuAccessFlags    = SharpDX.Direct3D11.CpuAccessFlags.None,
                ArraySize         = 1
            };

            return(new SharpDX.Direct3D11.Texture2D(device, colordesc));
        }
Ejemplo n.º 15
0
        public BackBuffer(Dx10Device device10, Dx11ChainedDevice device11)
        {
            try
            {
                _device10 = device10;
                _device11 = device11;

                _backBuffer = Resource.FromSwapChain <Texture2D>(device11.SwapChain, 0);
                _renderView = new RenderTargetView(device11.Device, _backBuffer);

                Texture2DDescription descriptor = _backBuffer.Description;
                {
                    descriptor.MipLevels         = 1;
                    descriptor.ArraySize         = 1;
                    descriptor.Format            = Format.B8G8R8A8_UNorm;
                    descriptor.SampleDescription = new SampleDescription(1, 0);
                    descriptor.Usage             = SharpDX.Direct3D11.ResourceUsage.Default;
                    descriptor.BindFlags         = SharpDX.Direct3D11.BindFlags.RenderTarget | SharpDX.Direct3D11.BindFlags.ShaderResource;
                    descriptor.CpuAccessFlags    = SharpDX.Direct3D11.CpuAccessFlags.None;
                    descriptor.OptionFlags       = SharpDX.Direct3D11.ResourceOptionFlags.SharedKeyedmutex;
                };

                _textureD3D11 = new Texture2D(device11.Device, descriptor);

                _factory2D = new Factory(FactoryType.MultiThreaded);

                using (SharpDX.DXGI.Resource sharedResource = _textureD3D11.QueryInterface <SharpDX.DXGI.Resource>())
                    using (SharpDX.Direct3D10.Texture2D backBuffer10 = device10.Device.OpenSharedResource <SharpDX.Direct3D10.Texture2D>(sharedResource.SharedHandle))
                    {
                        _surface        = backBuffer10.QueryInterface <Surface>();
                        _renderTarget2D = new RenderTarget(_factory2D, _surface, GetRenderTargetProperties());
                    }
            }
            catch
            {
                Dispose();
                throw;
            }
        }
Ejemplo n.º 16
0
        private void InitializeComposeTexture(SizeInt32 size)
        {
            var description = new SharpDX.Direct3D11.Texture2DDescription
            {
                Width             = size.Width,
                Height            = size.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                SampleDescription = new SharpDX.DXGI.SampleDescription()
                {
                    Count   = 1,
                    Quality = 0
                },
                Usage          = SharpDX.Direct3D11.ResourceUsage.Default,
                BindFlags      = SharpDX.Direct3D11.BindFlags.ShaderResource | SharpDX.Direct3D11.BindFlags.RenderTarget,
                CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None,
                OptionFlags    = SharpDX.Direct3D11.ResourceOptionFlags.None
            };

            _composeTexture          = new SharpDX.Direct3D11.Texture2D(_d3dDevice, description);
            _composeRenderTargetView = new SharpDX.Direct3D11.RenderTargetView(_d3dDevice, _composeTexture);
        }
Ejemplo n.º 17
0
        public Dx11ScreenCapture()
        {
            // create device and factory
            device  = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware);
            factory = new Factory1();
            // creating CPU-accessible texture resource
            texdes = new SharpDX.Direct3D11.Texture2DDescription();
            texdes.CpuAccessFlags            = SharpDX.Direct3D11.CpuAccessFlags.Read;
            texdes.BindFlags                 = SharpDX.Direct3D11.BindFlags.None;
            texdes.Format                    = Format.B8G8R8A8_UNorm;
            texdes.Height                    = factory.Adapters1[numAdapter].Outputs[numOutput].Description.DesktopBounds.Height;
            texdes.Width                     = factory.Adapters1[numAdapter].Outputs[numOutput].Description.DesktopBounds.Width;
            texdes.OptionFlags               = SharpDX.Direct3D11.ResourceOptionFlags.None;
            texdes.MipLevels                 = 1;
            texdes.ArraySize                 = 1;
            texdes.SampleDescription.Count   = 1;
            texdes.SampleDescription.Quality = 0;
            texdes.Usage                     = SharpDX.Direct3D11.ResourceUsage.Staging;
            screenTexture                    = new SharpDX.Direct3D11.Texture2D(device, texdes);

            // duplicate output stuff
            output           = new Output1(factory.Adapters1[numAdapter].Outputs[numOutput].NativePointer);
            duplicatedOutput = output.DuplicateOutput(device);
        }
Ejemplo n.º 18
0
        private async void MainToggleButton_Checked(object sender, RoutedEventArgs e)
        {
            // Select what we want to capture
            var picker = new GraphicsCapturePicker();
            var item   = await picker.PickSingleItemAsync();

            if (item != null)
            {
                // Get a temporary file to save our gif to
                var file = await GetTempFileAsync();

                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    // Get the various d3d objects we'll need
                    var d3dDevice = Direct3D11Helpers.CreateSharpDXDevice(_device);

                    // Create our encoder
                    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.GifEncoderId, stream);

                    // Write the application block
                    // http://www.vurdalakov.net/misc/gif/netscape-looping-application-extension
                    var containerProperties = encoder.BitmapContainerProperties;
                    await containerProperties.SetPropertiesAsync(new[]
                    {
                        new KeyValuePair <string, BitmapTypedValue>("/appext/application", new BitmapTypedValue(PropertyValue.CreateUInt8Array(Encoding.ASCII.GetBytes("NETSCAPE2.0")), PropertyType.UInt8Array)),
                        // The first value is the size of the block, which is the fixed value 3.
                        // The second value is the looping extension, which is the fixed value 1.
                        // The third and fourth values comprise an unsigned 2-byte integer (little endian).
                        //     The value of 0 means to loop infinitely.
                        // The final value is the block terminator, which is the fixed value 0.
                        new KeyValuePair <string, BitmapTypedValue>("/appext/data", new BitmapTypedValue(PropertyValue.CreateUInt8Array(new byte[] { 3, 1, 0, 0, 0 }), PropertyType.UInt8Array)),
                    });

                    // Setup Windows.Graphics.Capture
                    var itemSize  = item.Size;
                    var framePool = Direct3D11CaptureFramePool.CreateFreeThreaded(
                        _device,
                        DirectXPixelFormat.B8G8R8A8UIntNormalized,
                        1,
                        itemSize);
                    var session = framePool.CreateCaptureSession(item);

                    // We need a blank texture (background) and a texture that will hold the frame we'll be encoding
                    var description = new SharpDX.Direct3D11.Texture2DDescription
                    {
                        Width             = itemSize.Width,
                        Height            = itemSize.Height,
                        MipLevels         = 1,
                        ArraySize         = 1,
                        Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                        SampleDescription = new SharpDX.DXGI.SampleDescription()
                        {
                            Count   = 1,
                            Quality = 0
                        },
                        Usage          = SharpDX.Direct3D11.ResourceUsage.Default,
                        BindFlags      = SharpDX.Direct3D11.BindFlags.ShaderResource | SharpDX.Direct3D11.BindFlags.RenderTarget,
                        CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None,
                        OptionFlags    = SharpDX.Direct3D11.ResourceOptionFlags.None
                    };
                    var gifTexture       = new SharpDX.Direct3D11.Texture2D(d3dDevice, description);
                    var renderTargetView = new SharpDX.Direct3D11.RenderTargetView(d3dDevice, gifTexture);

                    // Encode frames as they arrive. Because we created our frame pool using
                    // Direct3D11CaptureFramePool::CreateFreeThreaded, this lambda will fire on a different thread
                    // than our current one. If you'd like the callback to fire on your thread, create the frame pool
                    // using Direct3D11CaptureFramePool::Create and make sure your thread has a DispatcherQueue and you
                    // are pumping messages.
                    TimeSpan lastTimeStamp = TimeSpan.MinValue;
                    var      frameCount    = 0;
                    framePool.FrameArrived += async(s, a) =>
                    {
                        using (var frame = s.TryGetNextFrame())
                        {
                            var contentSize = frame.ContentSize;
                            var timeStamp   = frame.SystemRelativeTime;
                            using (var sourceTexture = Direct3D11Helpers.CreateSharpDXTexture2D(frame.Surface))
                            {
                                var width  = Math.Clamp(contentSize.Width, 0, itemSize.Width);
                                var height = Math.Clamp(contentSize.Height, 0, itemSize.Height);

                                var region = new SharpDX.Direct3D11.ResourceRegion(0, 0, 0, width, height, 1);

                                d3dDevice.ImmediateContext.ClearRenderTargetView(renderTargetView, new SharpDX.Mathematics.Interop.RawColor4(0, 0, 0, 1));
                                d3dDevice.ImmediateContext.CopySubresourceRegion(sourceTexture, 0, region, gifTexture, 0);
                            }

                            if (lastTimeStamp == TimeSpan.MinValue)
                            {
                                lastTimeStamp = timeStamp;
                            }
                            var timeStampDelta = timeStamp - lastTimeStamp;
                            lastTimeStamp = timeStamp;
                            var milliseconds = timeStampDelta.TotalMilliseconds;
                            // Use 10ms units
                            var frameDelay = milliseconds / 10;

                            if (frameCount > 0)
                            {
                                await encoder.GoToNextFrameAsync();
                            }

                            // Write our frame delay
                            await encoder.BitmapProperties.SetPropertiesAsync(new[]
                            {
                                new KeyValuePair <string, BitmapTypedValue>("/grctlext/Delay", new BitmapTypedValue(PropertyValue.CreateUInt16((ushort)frameDelay), PropertyType.UInt16)),
                            });

                            // Write the frame to our image
                            var gifSurface = Direct3D11Helpers.CreateDirect3DSurfaceFromSharpDXTexture(gifTexture);
                            var copy       = await SoftwareBitmap.CreateCopyFromSurfaceAsync(gifSurface);

                            encoder.SetSoftwareBitmap(copy);
                            frameCount++;
                        }
                    };

                    session.StartCapture();

                    await _semaphore.WaitAsync();

                    session.Dispose();
                    framePool.Dispose();
                    await Task.Delay(1000);

                    await encoder.FlushAsync();

                    var newFile = await PickGifAsync();

                    if (newFile == null)
                    {
                        await file.DeleteAsync();

                        return;
                    }
                    await file.MoveAndReplaceAsync(newFile);

                    await Launcher.LaunchFileAsync(newFile);
                }
            }
        }
Ejemplo n.º 19
0
 private void ScreenSize_Updated(ViewportF viewport, SharpDX.Direct3D11.Texture2DDescription newBackBuffer)
 {
     RefreshSize(viewport);
 }
        /// <summary>
        /// Creates device-based resources to store a constant buffer, cube
        /// geometry, and vertex and pixel shaders. In some cases this will also
        /// store a geometry shader.
        /// </summary>
        public async void CreateDeviceDependentResourcesAsync()
        {
            ReleaseDeviceDependentResources();

            usingVprtShaders = deviceResources.D3DDeviceSupportsVprt;

            var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;

            // On devices that do support the D3D11_FEATURE_D3D11_OPTIONS3::
            // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature
            // we can avoid using a pass-through geometry shader to set the render
            // target array index, thus avoiding any overhead that would be
            // incurred by setting the geometry shader stage.
            var vertexShaderFileName = usingVprtShaders ? "Content\\Shaders\\VPRTVertexShader.cso" : "Content\\Shaders\\VertexShader.cso";

            // Load the compiled vertex shader.
            var vertexShaderByteCode = await DirectXHelper.ReadDataAsync(await folder.GetFileAsync(vertexShaderFileName));

            // After the vertex shader file is loaded, create the shader and input layout.
            vertexShader = this.ToDispose(new SharpDX.Direct3D11.VertexShader(
                                              deviceResources.D3DDevice,
                                              vertexShaderByteCode));

            //TODO: Change VertexDesc to use new structure: VertexPositionTextureCoordinates
            SharpDX.Direct3D11.InputElement[] vertexDesc =
            {
                new SharpDX.Direct3D11.InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float,  0, 0, SharpDX.Direct3D11.InputClassification.PerVertexData, 0),
                new SharpDX.Direct3D11.InputElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32B32_Float, 12, 0, SharpDX.Direct3D11.InputClassification.PerVertexData, 0),
            };


            inputLayout = this.ToDispose(new SharpDX.Direct3D11.InputLayout(
                                             deviceResources.D3DDevice,
                                             vertexShaderByteCode,
                                             vertexDesc));

            if (!usingVprtShaders)
            {
                // Load the compiled pass-through geometry shader.
                var geometryShaderByteCode = await DirectXHelper.ReadDataAsync(await folder.GetFileAsync("Content\\Shaders\\GeometryShader.cso"));

                // After the pass-through geometry shader file is loaded, create the shader.
                geometryShader = this.ToDispose(new SharpDX.Direct3D11.GeometryShader(
                                                    deviceResources.D3DDevice,
                                                    geometryShaderByteCode));
            }

            // Load the compiled pixel shader.
            var pixelShaderByteCode = await DirectXHelper.ReadDataAsync(await folder.GetFileAsync("Content\\Shaders\\PixelShader.cso"));

            // After the pixel shader file is loaded, create the shader.
            pixelShader = this.ToDispose(new SharpDX.Direct3D11.PixelShader(
                                             deviceResources.D3DDevice,
                                             pixelShaderByteCode));

            //TODO: Use a photo editing app to create a texture, like GIMP2 with DDS Plugin, make sure photo width & height divisible by 4, for a cube must be an exact square
            //used Gimp 2 with DDS Plugin to create a 2000x2000 image and export at .dds file.
            //in the export options I used BC3_UNorm format, along with automatic MIP levels
            string textureName2 = "Content\\Textures\\nuwaupian_holding_fire3.dds";

            //TODO: Create the SamplerState
            var samplerStateDescription = new SharpDX.Direct3D11.SamplerStateDescription();

            samplerStateDescription.Filter      = SharpDX.Direct3D11.Filter.MinMagMipLinear;
            samplerStateDescription.AddressU    = SharpDX.Direct3D11.TextureAddressMode.Wrap;
            samplerStateDescription.AddressV    = SharpDX.Direct3D11.TextureAddressMode.Wrap;
            samplerStateDescription.AddressW    = SharpDX.Direct3D11.TextureAddressMode.Wrap;
            samplerStateDescription.BorderColor = new SharpDX.Mathematics.Interop.RawColor4(0f, 0f, 0f, 1f);

            samplerState = new SharpDX.Direct3D11.SamplerState(deviceResources.D3DDevice, samplerStateDescription);

            //TODO: Use the TextureLoader class to create a bitmap source from a .DDS texture file
            //Retreived TextureLoader from DirectXTK or DirectText Tool
            var bitmapSource2 = TextureLoader.LoadBitmap(new SharpDX.WIC.ImagingFactory2(), textureName2);

            //TODO: Create a Texture Description to describe the texture you'll be using or converting to
            var textDesc = new SharpDX.Direct3D11.Texture2DDescription()
            {
                Width             = bitmapSource2.Size.Width,
                Height            = bitmapSource2.Size.Height,
                ArraySize         = 6,
                BindFlags         = SharpDX.Direct3D11.BindFlags.ShaderResource,
                Usage             = SharpDX.Direct3D11.ResourceUsage.Default,
                CpuAccessFlags    = SharpDX.Direct3D11.CpuAccessFlags.None,
                Format            = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
                MipLevels         = 1,
                OptionFlags       = SharpDX.Direct3D11.ResourceOptionFlags.TextureCube,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
            };

            //TODO: Create Shader Resource View
            var shaderResourceDesc = new SharpDX.Direct3D11.ShaderResourceViewDescription()
            {
                Format      = textDesc.Format,
                Dimension   = SharpDX.Direct3D.ShaderResourceViewDimension.TextureCube,
                TextureCube = new SharpDX.Direct3D11.ShaderResourceViewDescription.TextureCubeResource()
                {
                    MipLevels = textDesc.MipLevels, MostDetailedMip = 0
                }
            };

            //TODO: Create 6 pointers for the 6 sides of the cube, each pointing to an 2000x2000 image you want to display
            IntPtr[] ptrImages = new IntPtr[6];

            //TODO: Get the Stride of each image - stride is the size of 1 row pixels
            int stride = bitmapSource2.Size.Width * 4;

            //TODO: for each of the 6 pointers, create a buffer to hold the pixels using the DataStream object,
            using (var buffer = new SharpDX.DataStream(bitmapSource2.Size.Height * stride, true, true))
            {
                //TODO: for each of the 6 data streams, copy the pixels into a buffer
                // Copy the content of the WIC to the buffer
                bitmapSource2.CopyPixels(stride, buffer);

                //TODO: for each of the 6 pointers get the IntPtr to the buffers, taking care not get rid of the buffers, pointers, or datastreams before we can create the texture cube
                ptrImages[0] = buffer.DataPointer;


                using (var buffer1 = new SharpDX.DataStream(bitmapSource2.Size.Height * stride, true, true))
                {
                    // Copy the content of the WIC to the buffer
                    bitmapSource2.CopyPixels(stride, buffer1);
                    ptrImages[1] = buffer1.DataPointer;


                    using (var buffer2 = new SharpDX.DataStream(bitmapSource2.Size.Height * stride, true, true))
                    {
                        // Copy the content of the WIC to the buffer
                        bitmapSource2.CopyPixels(stride, buffer2);
                        ptrImages[2] = buffer2.DataPointer;

                        using (var buffer3 = new SharpDX.DataStream(bitmapSource2.Size.Height * stride, true, true))
                        {
                            // Copy the content of the WIC to the buffer
                            bitmapSource2.CopyPixels(stride, buffer3);
                            ptrImages[3] = buffer3.DataPointer;

                            using (var buffer4 = new SharpDX.DataStream(bitmapSource2.Size.Height * stride, true, true))
                            {
                                // Copy the content of the WIC to the buffer
                                bitmapSource2.CopyPixels(stride, buffer4);
                                ptrImages[4] = buffer4.DataPointer;

                                using (var buffer5 = new SharpDX.DataStream(bitmapSource2.Size.Height * stride, true, true))
                                {
                                    // Copy the content of the WIC to the buffer
                                    bitmapSource2.CopyPixels(stride, buffer5);
                                    ptrImages[5] = buffer5.DataPointer;


                                    //TODO: create a DataBox of the 6 pixel buffers. The DataBox is the typed array which we described in the TextureDescription and ShaderResource Description to hold the 6 sides
                                    var dataRects = new SharpDX.DataBox[] { new SharpDX.DataBox(ptrImages[0], stride, 0),
                                                                            new SharpDX.DataBox(ptrImages[1], stride, 0),
                                                                            new SharpDX.DataBox(ptrImages[2], stride, 0),
                                                                            new SharpDX.DataBox(ptrImages[3], stride, 0),
                                                                            new SharpDX.DataBox(ptrImages[4], stride, 0),
                                                                            new SharpDX.DataBox(ptrImages[5], stride, 0) };

                                    //TODO: Now create the TextureCube
                                    var texture2D = new SharpDX.Direct3D11.Texture2D(deviceResources.D3DDevice, textDesc, dataRects);

                                    //TODO: Now create the TextureShaderResourceView - which will be used in the PixelShader, after this point we can release all the buffers
                                    textureResource = new SharpDX.Direct3D11.ShaderResourceView(deviceResources.D3DDevice, texture2D, shaderResourceDesc);
                                }
                            }
                        }
                    }
                }
            }

            //TODO: Change to VertexPositionCoordinate
            // Load mesh vertices. Each vertex has a position and a color.
            // Note that the cube size has changed from the default DirectX app
            // template. Windows Holographic is scaled in meters, so to draw the
            // cube at a comfortable size we made the cube width 0.2 m (20 cm).
            VertexPositionCoordinate[] cubeVertices =
            {
                new VertexPositionCoordinate(new Vector3(-0.1f, -0.1f, -0.1f), new Vector3(0.0f, 0.0f, 0.0f)),
                new VertexPositionCoordinate(new Vector3(-0.1f, -0.1f,  0.1f), new Vector3(0.0f, 0.0f, 1.0f)),
                new VertexPositionCoordinate(new Vector3(-0.1f,  0.1f, -0.1f), new Vector3(0.0f, 1.0f, 0.0f)),
                new VertexPositionCoordinate(new Vector3(-0.1f,  0.1f,  0.1f), new Vector3(0.0f, 1.0f, 1.0f)),
                new VertexPositionCoordinate(new Vector3(0.1f,  -0.1f, -0.1f), new Vector3(1.0f, 0.0f, 0.0f)),
                new VertexPositionCoordinate(new Vector3(0.1f,  -0.1f,  0.1f), new Vector3(1.0f, 0.0f, 1.0f)),
                new VertexPositionCoordinate(new Vector3(0.1f,   0.1f, -0.1f), new Vector3(1.0f, 1.0f, 0.0f)),
                new VertexPositionCoordinate(new Vector3(0.1f,   0.1f,  0.1f), new Vector3(1.0f, 1.0f, 1.0f)),
            };

            vertexBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create(
                                              deviceResources.D3DDevice,
                                              SharpDX.Direct3D11.BindFlags.VertexBuffer,
                                              cubeVertices));

            // Load mesh indices. Each trio of indices represents
            // a triangle to be rendered on the screen.
            // For example: 0,2,1 means that the vertices with indexes
            // 0, 2 and 1 from the vertex buffer compose the
            // first triangle of this mesh.
            ushort[] cubeIndices =
            {
                2, 1, 0, // -x
                2, 3, 1,

                6, 4, 5, // +x
                6, 5, 7,

                0, 1, 5, // -y
                0, 5, 4,

                2, 6, 7, // +y
                2, 7, 3,

                0, 4, 6, // -z
                0, 6, 2,

                1, 3, 7, // +z
                1, 7, 5,
            };

            indexCount = cubeIndices.Length;

            indexBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create(
                                             deviceResources.D3DDevice,
                                             SharpDX.Direct3D11.BindFlags.IndexBuffer,
                                             cubeIndices));

            // Create a constant buffer to store the model matrix.
            modelConstantBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create(
                                                     deviceResources.D3DDevice,
                                                     SharpDX.Direct3D11.BindFlags.ConstantBuffer,
                                                     ref modelConstantBufferData));

            // Once the cube is loaded, the object is ready to be rendered.
            loadingComplete = true;
        }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            // Get a capture item that represents the primary monitor
            var monitor = MonitorFromWindow(GetDesktopWindow(), MONITOR_DEFAULTTOPRIMARY);
            var item    = CaptureHelper.CreateItemForMonitor(monitor);
            var size    = item.Size;

            // Setup D3D
            var device     = Direct3D11Helper.CreateDevice();
            var d3dDevice  = Direct3D11Helper.CreateSharpDXDevice(device);
            var d3dContext = d3dDevice.ImmediateContext;

            // Create our staging texture
            var description = new SharpDX.Direct3D11.Texture2DDescription
            {
                Width             = size.Width,
                Height            = size.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                SampleDescription = new SharpDX.DXGI.SampleDescription()
                {
                    Count   = 1,
                    Quality = 0
                },
                Usage          = SharpDX.Direct3D11.ResourceUsage.Staging,
                BindFlags      = SharpDX.Direct3D11.BindFlags.None,
                CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.Read,
                OptionFlags    = SharpDX.Direct3D11.ResourceOptionFlags.None
            };
            var stagingTexture = new SharpDX.Direct3D11.Texture2D(d3dDevice, description);

            // Setup capture
            var framePool = Direct3D11CaptureFramePool.CreateFreeThreaded(
                device,
                DirectXPixelFormat.B8G8R8A8UIntNormalized,
                1,
                size);
            var session = framePool.CreateCaptureSession(item);

            var imageNum = 0;
            var endEvent = new ManualResetEvent(false);

            framePool.FrameArrived += (sender, a) =>
            {
                using (var frame = sender.TryGetNextFrame())
                    using (var bitmap = Direct3D11Helper.CreateSharpDXTexture2D(frame.Surface))
                    {
                        // Copy to our staging texture
                        d3dContext.CopyResource(bitmap, stagingTexture);

                        // Map our texture and get the bits
                        var mapped       = d3dContext.MapSubresource(stagingTexture, 0, SharpDX.Direct3D11.MapMode.Read, SharpDX.Direct3D11.MapFlags.None);
                        var source       = mapped.DataPointer;
                        var sourceStride = mapped.RowPitch;

                        // Allocate some memory to hold our copy
                        var bytes = new byte[size.Width * size.Height * 4]; // 4 bytes per pixel
                        unsafe
                        {
                            fixed(byte *bytesPointer = bytes)
                            {
                                var dest       = (IntPtr)bytesPointer;
                                var destStride = size.Width * 4;

                                for (int i = 0; i < size.Height; i++)
                                {
                                    SharpDX.Utilities.CopyMemory(dest, source, destStride);

                                    source = IntPtr.Add(source, sourceStride);
                                    dest   = IntPtr.Add(dest, destStride);
                                }
                            }
                        }

                        // Don't forget to unmap when you're done!
                        d3dContext.UnmapSubresource(stagingTexture, 0);

                        // Encode it
                        // NOTE: Waiting here will stall the capture
                        EncodeBytesAsync($"image{imageNum}.png", size.Width, size.Height, bytes).Wait();

                        imageNum++;
                        if (imageNum > 10)
                        {
                            framePool.Dispose();
                            session.Dispose();
                            endEvent.Set();
                        }
                    }
            };

            // Start the capture and wait
            session.StartCapture();
            endEvent.WaitOne();
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Creates a Direct 3D 11 textured based off the top mip of this Texture2D export
        /// </summary>
        /// <param name="device">Device to render texture from/to ?</param>
        /// <param name="description">Direct3D description of the texture</param>
        /// <returns></returns>
        public static SharpDX.Direct3D11.Texture2D generatePreviewTexture(this Texture2D t2d, SharpDX.Direct3D11.Device device, out SharpDX.Direct3D11.Texture2DDescription description, Texture2DMipInfo info = null, byte[] imageBytes = null)
        {
            if (info == null)
            {
                info = new Texture2DMipInfo();
                info = t2d.Mips.FirstOrDefault(x => x.storageType != StorageTypes.empty);
            }
            if (info == null)
            {
                description = new SharpDX.Direct3D11.Texture2DDescription();
                return(null);
            }


            Debug.WriteLine($"Generating preview texture for Texture2D {info.Export.FullPath} of format {t2d.TextureFormat}");
            if (imageBytes == null)
            {
                imageBytes = t2d.GetImageBytesForMip(info, t2d.Export.Game, true);
            }
            int width  = (int)info.width;
            int height = (int)info.height;
            var bmp    = Image.convertRawToBitmapARGB(imageBytes, info.width, info.height, Image.getPixelFormatType(t2d.TextureFormat));

            // Convert compressed image data to an A8R8G8B8 System.Drawing.Bitmap

            /* DDSFormat format;
             * const Format dxformat = Format.B8G8R8A8_UNorm;
             * switch (texFormat)
             * {
             *  case "DXT1":
             *      format = DDSFormat.DXT1;
             *      break;
             *  case "DXT5":
             *      format = DDSFormat.DXT5;
             *      break;
             *  case "V8U8":
             *      format = DDSFormat.V8U8;
             *      break;
             *  case "G8":
             *      format = DDSFormat.G8;
             *      break;
             *  case "A8R8G8B8":
             *      format = DDSFormat.ARGB;
             *      break;
             *  case "NormalMap_HQ":
             *      format = DDSFormat.ATI2;
             *      break;
             *  default:
             *      throw new FormatException("Unknown texture format: " + texFormat);
             * }
             *
             * byte[] compressedData = extractRawData(info, pccRef);
             * Bitmap bmp = DDSImage.ToBitmap(compressedData, format, width, height); */

            // Load the decompressed data into an array
            System.Drawing.Imaging.BitmapData data = bmp.LockBits(new System.Drawing.Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            var pixels = new byte[data.Stride * data.Height];

            System.Runtime.InteropServices.Marshal.Copy(data.Scan0, pixels, 0, pixels.Length);
            bmp.UnlockBits(data);

            // Create description of texture
            description.Width     = width;
            description.Height    = height;
            description.MipLevels = 1;
            description.ArraySize = 1;
            description.Format    = SharpDX.DXGI.Format.B8G8R8A8_UNorm;
            description.SampleDescription.Count   = 1;
            description.SampleDescription.Quality = 0;
            description.Usage          = SharpDX.Direct3D11.ResourceUsage.Default;
            description.BindFlags      = SharpDX.Direct3D11.BindFlags.ShaderResource | SharpDX.Direct3D11.BindFlags.RenderTarget;
            description.CpuAccessFlags = 0;
            description.OptionFlags    = SharpDX.Direct3D11.ResourceOptionFlags.GenerateMipMaps;

            // Set up the texture data
            int stride = width * 4;

            SharpDX.DataStream ds = new SharpDX.DataStream(height * stride, true, true);
            ds.Write(pixels, 0, height * stride);
            ds.Position = 0;
            // Create texture
            SharpDX.Direct3D11.Texture2D tex = new SharpDX.Direct3D11.Texture2D(device, description, new SharpDX.DataRectangle(ds.DataPointer, stride));
            ds.Dispose();

            return(tex);
        }
Ejemplo n.º 23
0
        private void _スワップチェーンに依存するグラフィックリソースを作成する()
        {
            using (var backbufferTexture2D = this.SwapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0))   // D3D 用
                using (var backbufferSurface = this.SwapChain.GetBackBuffer <SharpDX.DXGI.Surface>(0))         // D2D 用
                {
                    // ※正確には、「スワップチェーン」というより、「スワップチェーンが持つバックバッファ」に依存するリソース。

                    // D3D 関連

                    #region " バックバッファに対するD3Dレンダーターゲットビューを作成する。"
                    //----------------
                    this.D3DRenderTargetView = new SharpDX.Direct3D11.RenderTargetView(this.D3DDevice, backbufferTexture2D);
                    //----------------
                    #endregion

                    #region " バックバッファに対する深度ステンシル、深度ステンシルビュー、深度ステンシルステートを作成する。"
                    //----------------
                    var depthStencilDesc = new SharpDX.Direct3D11.Texture2DDescription()
                    {
                        Width             = backbufferTexture2D.Description.Width,
                        Height            = backbufferTexture2D.Description.Height,
                        MipLevels         = 1,
                        ArraySize         = 1,
                        Format            = SharpDX.DXGI.Format.D32_Float, // Depthのみのフォーマット
                        SampleDescription = backbufferTexture2D.Description.SampleDescription,
                        Usage             = SharpDX.Direct3D11.ResourceUsage.Default,
                        BindFlags         = SharpDX.Direct3D11.BindFlags.DepthStencil,
                        CpuAccessFlags    = SharpDX.Direct3D11.CpuAccessFlags.None, // CPUからはアクセスしない
                        OptionFlags       = SharpDX.Direct3D11.ResourceOptionFlags.None,
                    };
                    this.D3DDepthStencil = new SharpDX.Direct3D11.Texture2D(this.D3DDevice, depthStencilDesc);

                    var depthStencilViewDesc = new SharpDX.Direct3D11.DepthStencilViewDescription()
                    {
                        Format    = depthStencilDesc.Format,
                        Dimension = SharpDX.Direct3D11.DepthStencilViewDimension.Texture2D,
                        Flags     = SharpDX.Direct3D11.DepthStencilViewFlags.None,
                        Texture2D = new SharpDX.Direct3D11.DepthStencilViewDescription.Texture2DResource()
                        {
                            MipSlice = 0,
                        },
                    };
                    this.D3DDepthStencilView = new SharpDX.Direct3D11.DepthStencilView(this.D3DDevice, this.D3DDepthStencil, depthStencilViewDesc);

                    var depthSencilStateDesc = new SharpDX.Direct3D11.DepthStencilStateDescription()
                    {
                        IsDepthEnabled   = this._深度ステンシルを使う,                      // 深度テストあり?
                        DepthWriteMask   = SharpDX.Direct3D11.DepthWriteMask.All, // 書き込む
                        DepthComparison  = SharpDX.Direct3D11.Comparison.Less,    // 手前の物体を描画
                        IsStencilEnabled = false,                                 // ステンシルテストなし。
                        StencilReadMask  = 0,                                     // ステンシル読み込みマスク。
                        StencilWriteMask = 0,                                     // ステンシル書き込みマスク。
                                                                                  // 面が表を向いている場合のステンシル・テストの設定
                        FrontFace = new SharpDX.Direct3D11.DepthStencilOperationDescription()
                        {
                            FailOperation      = SharpDX.Direct3D11.StencilOperation.Keep, // 維持
                            DepthFailOperation = SharpDX.Direct3D11.StencilOperation.Keep, // 維持
                            PassOperation      = SharpDX.Direct3D11.StencilOperation.Keep, // 維持
                            Comparison         = SharpDX.Direct3D11.Comparison.Never,      // 常に失敗
                        },
                        // 面が裏を向いている場合のステンシル・テストの設定
                        BackFace = new SharpDX.Direct3D11.DepthStencilOperationDescription()
                        {
                            FailOperation      = SharpDX.Direct3D11.StencilOperation.Keep, // 維持
                            DepthFailOperation = SharpDX.Direct3D11.StencilOperation.Keep, // 維持
                            PassOperation      = SharpDX.Direct3D11.StencilOperation.Keep, // 維持
                            Comparison         = SharpDX.Direct3D11.Comparison.Always,     // 常に成功
                        },
                    };
                    this.D3DDepthStencilState = new SharpDX.Direct3D11.DepthStencilState(this.D3DDevice, depthSencilStateDesc);
                    //----------------
                    #endregion

                    #region " バックバッファに対するビューポートを作成する。"
                    //----------------
                    this.D3DViewPort[0] = new SharpDX.Mathematics.Interop.RawViewportF()
                    {
                        X        = 0.0f,
                        Y        = 0.0f,
                        Width    = (float)backbufferTexture2D.Description.Width,
                        Height   = (float)backbufferTexture2D.Description.Height,
                        MinDepth = 0.0f,
                        MaxDepth = 1.0f,
                    };
                    //----------------
                    #endregion

                    // D2D 関連

                    #region " バックバッファとメモリを共有する、既定のD2Dレンダーターゲットビットマップを作成する。"
                    //----------------
                    this.D2DRenderBitmap = new SharpDX.Direct2D1.Bitmap1( // このビットマップは、
                        this.D2DDeviceContext,
                        backbufferSurface,                                // このDXGIサーフェスとメモリを共有する。
                        new SharpDX.Direct2D1.BitmapProperties1()
                    {
                        PixelFormat   = new SharpDX.Direct2D1.PixelFormat(backbufferSurface.Description.Format, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                        BitmapOptions = SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw,
                    });

                    this.D2DDeviceContext.Target = this.D2DRenderBitmap;
                    //----------------
                    #endregion
                }

            if (null == this.UIFramework)
            {
                this.UIFramework = new UI.Framework();
            }
            this.UIFramework.活性化する();
            this.UIFramework.Root.可視 = false;
        }
Ejemplo n.º 24
0
		public void GetData<T>(int level, Rectangle? rect, T[] data, int startIndex, int elementCount) where T : struct
        {
            if (data == null || data.Length == 0)
                throw new ArgumentException("data cannot be null");
            if (data.Length < startIndex + elementCount)
                throw new ArgumentException("The data passed has a length of " + data.Length + " but " + elementCount + " pixels have been requested.");

#if IOS

            // Reading back a texture from GPU memory is unsupported
            // in OpenGL ES 2.0 and no work around has been implemented.           
            throw new NotSupportedException("OpenGL ES 2.0 does not support texture reads.");

#elif ANDROID

            Rectangle r;
            if (rect != null)
            {
                r = rect.Value;
            }
            else
            {
                r = new Rectangle(0, 0, Width, Height);
            }
            			
			// Get the Color values
			if (typeof(T) == typeof(uint))
			{
				Color[] colors = new Color[elementCount];
				GetData<Color>(level, rect, colors, startIndex, elementCount);
				uint[] final = data as uint[];
				for (int i = 0; i < final.Length; i++)
				{
					final[i] = (uint)
					(
						// use correct xna byte order (and remember to convert it yourself as needed)
						colors[i].A << 24 |
						colors[i].B << 16 |
						colors[i].G << 8 |
						colors[i].R
					);
				}
			}
            // Get the Color values
            else if ((typeof(T) == typeof(Color)))
            {
				byte[] imageInfo = GetTextureData(0);

                int rWidth = r.Width;
                int rHeight = r.Height;
                
                // Loop through and extract the data but we need to load it 
                var dataRowColOffset = 0;
                var sz = 0;
                var pixelOffset = 0;
                for (int y = r.Top; y < rHeight; y++)
                {
                    for (int x = r.Left; x < rWidth; x++)
                    {
                        var result = new Color(0, 0, 0, 0);
                        dataRowColOffset = ((y * r.Width) + x);
                        switch (Format)
                        {
                            case SurfaceFormat.Color: //kTexture2DPixelFormat_RGBA8888
                            case SurfaceFormat.Dxt3:
                                sz = 4;
                                pixelOffset = dataRowColOffset * sz;
                                result.R = imageInfo[pixelOffset];
                                result.G = imageInfo[pixelOffset + 1];
                                result.B = imageInfo[pixelOffset + 2];
                                result.A = imageInfo[pixelOffset + 3];
                                break;
                            case SurfaceFormat.Bgra4444: //kTexture2DPixelFormat_RGBA4444
                                //								sz = 2;
                                //								pos = ((y * imageSize.Width) + x) * sz;
                                //								pixelOffset = new IntPtr (imageData.ToInt64 () + pos);
                                //	
                                //								Marshal.Copy (pixelOffset, pixel, 0, 4);	
                                //	
                                //								result.R = pixel [0];
                                //								result.G = pixel [1];
                                //								result.B = pixel [2];
                                //								result.A = pixel [3];
                                sz = 2;
                                pixelOffset = dataRowColOffset * sz;
                                result.R = imageInfo[pixelOffset];
                                result.G = imageInfo[pixelOffset + 1];
                                result.B = imageInfo[pixelOffset + 2];
                                result.A = imageInfo[pixelOffset + 3];
                                break;
                            case SurfaceFormat.Bgra5551: //kTexture2DPixelFormat_RGB5A1
                                //								sz = 2;
                                //								pos = ((y * imageSize.Width) + x) * sz;
                                //								pixelOffset = new IntPtr (imageData.ToInt64 () + pos);
                                //								Marshal.Copy (pixelOffset, pixel, 0, 4);	
                                //	
                                //								result.R = pixel [0];
                                //								result.G = pixel [1];
                                //								result.B = pixel [2];
                                //								result.A = pixel [3];
                                sz = 2;
                                pixelOffset = dataRowColOffset * sz;
                                result.R = imageInfo[pixelOffset];
                                result.G = imageInfo[pixelOffset + 1];
                                result.B = imageInfo[pixelOffset + 2];
                                result.A = imageInfo[pixelOffset + 3];
                                break;
                            case SurfaceFormat.Alpha8:  // kTexture2DPixelFormat_A8 
                                //								sz = 1;
                                //								pos = ((y * imageSize.Width) + x) * sz;
                                //								pixelOffset = new IntPtr (imageData.ToInt64 () + pos);								
                                //								Marshal.Copy (pixelOffset, pixel, 0, 4);	
                                //	
                                //								result.A = pixel [0];
                                sz = 1;
                                pixelOffset = dataRowColOffset * sz;
                                result.A = imageInfo[pixelOffset];
                                break;
                            default:
                                throw new NotSupportedException("Texture format");
                        }
                        data[dataRowColOffset] = (T)(object)result;
                    }                    
                }
            }
            else
            {
                throw new NotImplementedException("GetData not implemented for type.");
            }
#elif PSM
            Rectangle r;
            if (rect.HasValue)
            {
                r = rect.Value;
            }
            else
            {
                r = new Rectangle(0, 0, Width, Height);
            }
            
            int rWidth = r.Width;
            int rHeight = r.Height;
            
            var sz = 4;         
            
            // Loop through and extract the data but we need to load it 
            var dataRowColOffset = 0;
            
            var pixelOffset = 0;
            var result = new Color(0, 0, 0, 0);
            
            byte[] imageInfo = new byte[(rWidth * rHeight) * sz];
            
            ImageRect old_scissor = GraphicsDevice.Context.GetScissor();
            ImageRect old_viewport = GraphicsDevice.Context.GetViewport();
            FrameBuffer old_frame_buffer = GraphicsDevice.Context.GetFrameBuffer();

            ColorBuffer color_buffer = new ColorBuffer(rWidth, rHeight, PixelFormat.Rgba);
            FrameBuffer frame_buffer = new FrameBuffer();
            frame_buffer.SetColorTarget(color_buffer);
             
            GraphicsDevice.Context.SetFrameBuffer(frame_buffer);

            GraphicsDevice.Context.SetTexture(0, this._texture2D);
            GraphicsDevice.Context.ReadPixels(imageInfo, PixelFormat.Rgba, 0, 0, rWidth, rHeight);

            GraphicsDevice.Context.SetFrameBuffer(old_frame_buffer);
            GraphicsDevice.Context.SetScissor(old_scissor);
            GraphicsDevice.Context.SetViewport(old_viewport);
            
            for (int y = r.Top; y < rHeight; y++)
            {
                for (int x = r.Left; x < rWidth; x++)
                {
                    dataRowColOffset = ((y * r.Width) + x);
                    
                    pixelOffset = dataRowColOffset * sz;
                    result.R = imageInfo[pixelOffset];
                    result.G = imageInfo[pixelOffset + 1];
                    result.B = imageInfo[pixelOffset + 2];
                    result.A = imageInfo[pixelOffset + 3];
                    
                    data[dataRowColOffset] = (T)(object)result;
                }
            }

#elif DIRECTX

            // Create a temp staging resource for copying the data.
            // 
            // TODO: We should probably be pooling these staging resources
            // and not creating a new one each time.
            //
            var desc = new SharpDX.Direct3D11.Texture2DDescription();
            desc.Width = width;
            desc.Height = height;
            desc.MipLevels = 1;
            desc.ArraySize = 1;
            desc.Format = SharpDXHelper.ToFormat(_format);
            desc.BindFlags = SharpDX.Direct3D11.BindFlags.None;
            desc.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.Read;
            desc.SampleDescription.Count = 1;
            desc.SampleDescription.Quality = 0;
            desc.Usage = SharpDX.Direct3D11.ResourceUsage.Staging;
            desc.OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None;

		    var d3dContext = GraphicsDevice._d3dContext;
            using (var stagingTex = new SharpDX.Direct3D11.Texture2D(GraphicsDevice._d3dDevice, desc))
                lock (d3dContext)
                {
                    // Copy the data from the GPU to the staging texture.
                    int elementsInRow;
                    int rows;
                    if (rect.HasValue)
                    {
                        elementsInRow = rect.Value.Width;
                        rows = rect.Value.Height;
                        d3dContext.CopySubresourceRegion(GetTexture(), level, new SharpDX.Direct3D11.ResourceRegion(rect.Value.Left, rect.Value.Top, 0, rect.Value.Right, rect.Value.Bottom, 1), stagingTex, 0, 0, 0, 0);
                    }
                    else
                    {
                        elementsInRow = width;
                        rows = height;
                        d3dContext.CopySubresourceRegion(GetTexture(), level, null, stagingTex, 0, 0, 0, 0);
                    }

                    // Copy the data to the array.
                    SharpDX.DataStream stream;
                    var databox = d3dContext.MapSubresource(stagingTex, 0, SharpDX.Direct3D11.MapMode.Read, SharpDX.Direct3D11.MapFlags.None, out stream);

                    // Some drivers may add pitch to rows.
                    // We need to copy each row separatly and skip trailing zeros.
                    var currentIndex = startIndex;
                    var elementSize = SharpDX.Utilities.SizeOf<T>();
                    for (var row = 0; row < rows; row++)
                    {
                        stream.ReadRange(data, currentIndex, elementsInRow);
                        stream.Seek(databox.RowPitch - (elementSize * elementsInRow), SeekOrigin.Current);
                        currentIndex += elementsInRow;
                    }
                    stream.Dispose();
                }

#else

			GL.BindTexture(TextureTarget.Texture2D, this.glTexture);

			if (glFormat == (GLPixelFormat)All.CompressedTextureFormats) {
				throw new NotImplementedException();
			} else {
				if (rect.HasValue) {
					var temp = new T[this.width*this.height];
					GL.GetTexImage(TextureTarget.Texture2D, level, this.glFormat, this.glType, temp);
					int z = 0, w = 0;

					for(int y= rect.Value.Y; y < rect.Value.Y+ rect.Value.Height; y++) {
						for(int x=rect.Value.X; x < rect.Value.X + rect.Value.Width; x++) {
							data[z*rect.Value.Width+w] = temp[(y*width)+x];
							w++;
						}
						z++;
					}
				} else {
					GL.GetTexImage(TextureTarget.Texture2D, level, this.glFormat, this.glType, data);
				}
			}

#endif
        }
Ejemplo n.º 25
0
        public VRRenderer(SharpDX.Direct3D11.Device d3d11Device, SharpDX.Direct3D11.Device unityDevice, VRRig rig)
        {
            instance = this;


            this.rig      = rig;
            device        = d3d11Device;
            unityRenderer = unityDevice;

            bounds      = new VRTextureBounds_t();
            bounds.vMin = bounds.uMin = 0;
            bounds.vMax = bounds.uMax = 1;

            var w           = rig.leftTexture.Description.Width;
            var h           = rig.leftTexture.Description.Height;
            var description = new SharpDX.Direct3D11.Texture2DDescription()
            {
                Width  = (int)w,
                Height = (int)h,

                MipLevels = 1,
                ArraySize = 1,

                SampleDescription = new SampleDescription()
                {
                    Count = 1
                },

                BindFlags      = SharpDX.Direct3D11.BindFlags.ShaderResource | SharpDX.Direct3D11.BindFlags.RenderTarget,
                CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None,
                Format         = Format.R8G8B8A8_UNorm,
                OptionFlags    = SharpDX.Direct3D11.ResourceOptionFlags.Shared,
                Usage          = SharpDX.Direct3D11.ResourceUsage.Default
            };

            System.Diagnostics.Trace.WriteLine("Creating D3D11 Textures");

            leftVRTexture  = new SharpDX.Direct3D11.Texture2D(d3d11Device, description);
            rightVRTexture = new SharpDX.Direct3D11.Texture2D(d3d11Device, description);

            leftEye = new Texture_t()
            {
                eColorSpace = EColorSpace.Gamma,
                eType       = ETextureType.DirectX,
                handle      = leftVRTexture.NativePointer
            };
            rightEye = new Texture_t()
            {
                eColorSpace = EColorSpace.Gamma,
                eType       = ETextureType.DirectX,
                handle      = rightVRTexture.NativePointer
            };


            var sharedHandleLeft  = leftVRTexture.QueryInterface <Resource>().SharedHandle;
            var sharedHandleRight = rightVRTexture.QueryInterface <Resource>().SharedHandle;

            leftHandle  = unityRenderer.OpenSharedResource <SharpDX.Direct3D11.Texture2D>(sharedHandleLeft);
            rightHandle = unityRenderer.OpenSharedResource <SharpDX.Direct3D11.Texture2D>(sharedHandleRight);

            var viewDesc = new SharpDX.Direct3D11.ShaderResourceViewDescription()
            {
                Format    = Format.R8G8B8A8_UNorm,
                Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D,
                Texture2D = new SharpDX.Direct3D11.ShaderResourceViewDescription.Texture2DResource()
                {
                    MipLevels       = 1,
                    MostDetailedMip = 0
                }
            };
            var leftView  = new SharpDX.Direct3D11.ShaderResourceView(unityDevice, leftHandle, viewDesc);
            var rightView = new SharpDX.Direct3D11.ShaderResourceView(unityDevice, rightHandle, viewDesc);

            leftUnityTexture  = Texture2D.CreateExternalTexture(w, h, TextureFormat.ARGB32, false, false, leftView.NativePointer);
            rightUnityTexture = Texture2D.CreateExternalTexture(w, h, TextureFormat.ARGB32, false, false, rightView.NativePointer);
        }
Ejemplo n.º 26
0
        private void PlatformGetData <T>(int level, Rectangle?rect, T[] data, int startIndex, int elementCount) where T : struct
        {
            // Create a temp staging resource for copying the data.
            //
            // TODO: We should probably be pooling these staging resources
            // and not creating a new one each time.
            //
            var desc = new SharpDX.Direct3D11.Texture2DDescription();

            desc.Width                     = width;
            desc.Height                    = height;
            desc.MipLevels                 = 1;
            desc.ArraySize                 = 1;
            desc.Format                    = SharpDXHelper.ToFormat(_format);
            desc.BindFlags                 = SharpDX.Direct3D11.BindFlags.None;
            desc.CpuAccessFlags            = SharpDX.Direct3D11.CpuAccessFlags.Read;
            desc.SampleDescription.Count   = 1;
            desc.SampleDescription.Quality = 0;
            desc.Usage                     = SharpDX.Direct3D11.ResourceUsage.Staging;
            desc.OptionFlags               = SharpDX.Direct3D11.ResourceOptionFlags.None;

            var d3dContext = GraphicsDevice._d3dContext;

            using (var stagingTex = new SharpDX.Direct3D11.Texture2D(GraphicsDevice._d3dDevice, desc))
                lock (d3dContext)
                {
                    // Copy the data from the GPU to the staging texture.
                    int elementsInRow;
                    int rows;
                    if (rect.HasValue)
                    {
                        elementsInRow = rect.Value.Width;
                        rows          = rect.Value.Height;
                        d3dContext.CopySubresourceRegion(GetTexture(), level, new SharpDX.Direct3D11.ResourceRegion(rect.Value.Left, rect.Value.Top, 0, rect.Value.Right, rect.Value.Bottom, 1), stagingTex, 0, 0, 0, 0);
                    }
                    else
                    {
                        elementsInRow = width;
                        rows          = height;
                        d3dContext.CopySubresourceRegion(GetTexture(), level, null, stagingTex, 0, 0, 0, 0);
                    }

                    // Copy the data to the array.
                    SharpDX.DataStream stream;
                    var databox = d3dContext.MapSubresource(stagingTex, 0, SharpDX.Direct3D11.MapMode.Read, SharpDX.Direct3D11.MapFlags.None, out stream);

                    var elementSize = _format.GetSize();
                    var rowSize     = elementSize * elementsInRow;
                    if (rowSize == databox.RowPitch)
                    {
                        stream.ReadRange(data, startIndex, elementCount);
                    }
                    else
                    {
                        // Some drivers may add pitch to rows.
                        // We need to copy each row separatly and skip trailing zeros.
                        stream.Seek(startIndex, SeekOrigin.Begin);

                        for (var row = 0; row < rows; row++)
                        {
                            int i;
                            for (i = row * rowSize; i < (row + 1) * rowSize; i++)
                            {
                                data[i] = stream.Read <T>();
                            }

                            if (i >= elementCount)
                            {
                                break;
                            }

                            stream.Seek(databox.RowPitch - rowSize, SeekOrigin.Current);
                        }
                    }

                    stream.Dispose();
                }
        }
Ejemplo n.º 27
0
		public void GetData<T>(int level, Rectangle? rect, T[] data, int startIndex, int elementCount) where T : struct
        {
#if IOS 
			throw new NotImplementedException();
#elif ANDROID
			if (data == null)
            {
                throw new ArgumentException("data cannot be null");
            }

            if (data.Length < startIndex + elementCount)
            {
                throw new ArgumentException("The data passed has a length of " + data.Length + " but " + elementCount + " pixels have been requested.");
            }

            Rectangle r;
            if (rect != null)
            {
                r = rect.Value;
            }
            else
            {
                r = new Rectangle(0, 0, Width, Height);
            }
            			
			// Get the Color values
			if (typeof(T) == typeof(uint))
			{
				Color[] colors = new Color[elementCount];
				GetData<Color>(level, rect, colors, startIndex, elementCount);
				uint[] final = data as uint[];
				for (int i = 0; i < final.Length; i++)
				{
					final[i] = (uint)
					(
						colors[i].R << 24 |
						colors[i].G << 16 |
						colors[i].B << 8 |
						colors[i].A
					);
				}
			}
            // Get the Color values
            else if ((typeof(T) == typeof(Color)))
            {
				byte[] imageInfo = GetTextureData(0);

                int rWidth = r.Width;
                int rHeight = r.Height;
                
                // Loop through and extract the data but we need to load it 
                var dataRowColOffset = 0;
                var sz = 0;
                var pixelOffset = 0;
                for (int y = r.Top; y < rHeight; y++)
                {
                    for (int x = r.Left; x < rWidth; x++)
                    {
                        var result = new Color(0, 0, 0, 0);
                        dataRowColOffset = ((y * r.Width) + x);
                        switch (Format)
                        {
                            case SurfaceFormat.Color: //kTexture2DPixelFormat_RGBA8888
                            case SurfaceFormat.Dxt3:
                                sz = 4;
                                pixelOffset = dataRowColOffset * sz;
                                result.R = imageInfo[pixelOffset];
                                result.G = imageInfo[pixelOffset + 1];
                                result.B = imageInfo[pixelOffset + 2];
                                result.A = imageInfo[pixelOffset + 3];
                                break;
                            case SurfaceFormat.Bgra4444: //kTexture2DPixelFormat_RGBA4444
                                //								sz = 2;
                                //								pos = ((y * imageSize.Width) + x) * sz;
                                //								pixelOffset = new IntPtr (imageData.ToInt64 () + pos);
                                //	
                                //								Marshal.Copy (pixelOffset, pixel, 0, 4);	
                                //	
                                //								result.R = pixel [0];
                                //								result.G = pixel [1];
                                //								result.B = pixel [2];
                                //								result.A = pixel [3];
                                sz = 2;
                                pixelOffset = dataRowColOffset * sz;
                                result.R = imageInfo[pixelOffset];
                                result.G = imageInfo[pixelOffset + 1];
                                result.B = imageInfo[pixelOffset + 2];
                                result.A = imageInfo[pixelOffset + 3];
                                break;
                            case SurfaceFormat.Bgra5551: //kTexture2DPixelFormat_RGB5A1
                                //								sz = 2;
                                //								pos = ((y * imageSize.Width) + x) * sz;
                                //								pixelOffset = new IntPtr (imageData.ToInt64 () + pos);
                                //								Marshal.Copy (pixelOffset, pixel, 0, 4);	
                                //	
                                //								result.R = pixel [0];
                                //								result.G = pixel [1];
                                //								result.B = pixel [2];
                                //								result.A = pixel [3];
                                sz = 2;
                                pixelOffset = dataRowColOffset * sz;
                                result.R = imageInfo[pixelOffset];
                                result.G = imageInfo[pixelOffset + 1];
                                result.B = imageInfo[pixelOffset + 2];
                                result.A = imageInfo[pixelOffset + 3];
                                break;
                            case SurfaceFormat.Alpha8:  // kTexture2DPixelFormat_A8 
                                //								sz = 1;
                                //								pos = ((y * imageSize.Width) + x) * sz;
                                //								pixelOffset = new IntPtr (imageData.ToInt64 () + pos);								
                                //								Marshal.Copy (pixelOffset, pixel, 0, 4);	
                                //	
                                //								result.A = pixel [0];
                                sz = 1;
                                pixelOffset = dataRowColOffset * sz;
                                result.A = imageInfo[pixelOffset];
                                break;
                            default:
                                throw new NotSupportedException("Texture format");
                        }
                        data[dataRowColOffset] = (T)(object)result;
                    }                    
                }
            }
            else
            {
                throw new NotImplementedException("GetData not implemented for type.");
            }
#elif PSM
            throw new NotImplementedException();
#elif DIRECTX

            // Create a temp staging resource for copying the data.
            // 
            // TODO: We should probably be pooling these staging resources
            // and not creating a new one each time.
            //
            var desc = new SharpDX.Direct3D11.Texture2DDescription();
            desc.Width = width;
            desc.Height = height;
            desc.MipLevels = 1;
            desc.ArraySize = 1;
            desc.Format = SharpDXHelper.ToFormat(format);
            desc.BindFlags = SharpDX.Direct3D11.BindFlags.None;
            desc.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.Read;
            desc.SampleDescription.Count = 1;
            desc.SampleDescription.Quality = 0;
            desc.Usage = SharpDX.Direct3D11.ResourceUsage.Staging;
            desc.OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None;

		    var d3dContext = GraphicsDevice._d3dContext;
            using (var stagingTex = new SharpDX.Direct3D11.Texture2D(GraphicsDevice._d3dDevice, desc))
                lock (d3dContext)
                {
                    // Copy the data from the GPU to the staging texture.
                    if (rect.HasValue)
                    {
                        // TODO: Need to deal with subregion copies!
                        throw new NotImplementedException();
                    }
                    else
                        d3dContext.CopySubresourceRegion(_texture, level, null, stagingTex, 0, 0, 0, 0);

                    // Copy the data to the array.
                    SharpDX.DataStream stream;
                    d3dContext.MapSubresource(stagingTex, 0, SharpDX.Direct3D11.MapMode.Read, SharpDX.Direct3D11.MapFlags.None, out stream);
                    stream.ReadRange(data, startIndex, elementCount);
                    stream.Dispose();
                }

#else

			GL.BindTexture(TextureTarget.Texture2D, this.glTexture);

			if (rect.HasValue) {
				throw new NotImplementedException();
			}

			if (glFormat == (GLPixelFormat)All.CompressedTextureFormats) {
				throw new NotImplementedException();
			} else {
				GL.GetTexImage(TextureTarget.Texture2D, level, this.glFormat, this.glType, data);
			}

#endif
        }
Ejemplo n.º 28
0
		internal Texture2D(GraphicsDevice graphicsDevice, int width, int height, bool mipmap, SurfaceFormat format, bool renderTarget)
		{
            if (graphicsDevice == null)
                throw new ArgumentNullException("Graphics Device Cannot Be Null");

            this.GraphicsDevice = graphicsDevice;
            this.width = width;
            this.height = height;
            this.format = format;
            this.levelCount = 1;

            if (mipmap)
            {
                int size = Math.Max(this.width, this.height);
                while (size > 1)
                {
                    size = size / 2;
                    this.levelCount++;
                }
            }

#if DIRECTX

            // TODO: Move this to SetData() if we want to make Immutable textures!
            var desc = new SharpDX.Direct3D11.Texture2DDescription();
            desc.Width = width;
            desc.Height = height;
            desc.MipLevels = levelCount;
            desc.ArraySize = 1;
            desc.Format = SharpDXHelper.ToFormat(format);
            desc.BindFlags = SharpDX.Direct3D11.BindFlags.ShaderResource;
            desc.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None;
            desc.SampleDescription.Count = 1;
            desc.SampleDescription.Quality = 0;
            desc.Usage = SharpDX.Direct3D11.ResourceUsage.Default;
            desc.OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None;

            if (renderTarget)
                desc.BindFlags |= SharpDX.Direct3D11.BindFlags.RenderTarget;

            _texture = new SharpDX.Direct3D11.Texture2D(graphicsDevice._d3dDevice, desc);

#elif PSM
			_texture2D = new Sce.PlayStation.Core.Graphics.Texture2D(width, height, mipmap, PSSHelper.ToFormat(format));
#else

            this.glTarget = TextureTarget.Texture2D;
            
            Threading.BlockOnUIThread(() =>
            {
                // Store the current bound texture.
                var prevTexture = GraphicsExtensions.GetBoundTexture2D();

                GenerateGLTextureIfRequired();

                format.GetGLFormat(out glInternalFormat, out glFormat, out glType);

                if (glFormat == (GLPixelFormat)All.CompressedTextureFormats)
                {
                    var imageSize = 0;
                    switch (format)
                    {
                        case SurfaceFormat.RgbPvrtc2Bpp:
                        case SurfaceFormat.RgbaPvrtc2Bpp:
                            imageSize = (Math.Max(this.width, 8) * Math.Max(this.height, 8) * 2 + 7) / 8;
                            break;
                        case SurfaceFormat.RgbPvrtc4Bpp:
                        case SurfaceFormat.RgbaPvrtc4Bpp:
                            imageSize = (Math.Max(this.width, 16) * Math.Max(this.height, 8) * 4 + 7) / 8;
                            break;
                        case SurfaceFormat.Dxt1:
                            imageSize = ((this.width + 3) / 4) * ((this.height + 3) / 4) * 8 * 1;
                            break;
                        case SurfaceFormat.Dxt3:
                        case SurfaceFormat.Dxt5:
                            imageSize = ((this.width + 3) / 4) * ((this.height + 3) / 4) * 16 * 1;
                            break;
                        default:
                            throw new NotImplementedException();
                    }

                    GL.CompressedTexImage2D(TextureTarget.Texture2D, 0, glInternalFormat,
                                            this.width, this.height, 0,
                                            imageSize, IntPtr.Zero);
                    GraphicsExtensions.CheckGLError();
                }
                else
                {
                    GL.TexImage2D(TextureTarget.Texture2D, 0,
#if IOS || ANDROID
                        (int)glInternalFormat,
#else				           
					    glInternalFormat,
#endif
                        this.width, this.height, 0,
                        glFormat, glType, IntPtr.Zero);
                    GraphicsExtensions.CheckGLError();
                }

                // Restore the bound texture.
                GL.BindTexture(TextureTarget.Texture2D, prevTexture);
                GraphicsExtensions.CheckGLError();
            });
#endif
        }
        private void InitGrabber()
        {
            try
            {
                this.pixelFormat = PixelFormat.Format32bppRgb;
                boundsRect = new System.Drawing.Rectangle(0, 0, WIDTH, HEIGHT);

                uint numAdapter = 0;   // # of graphics card adapter
                uint numOutput = 0;    // # of output device (i.e. monitor)

                // create device and factory
                dx11Device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware);
                dx11Factory = new Factory1();
                dx11Output = new Output1(dx11Factory.Adapters1[numAdapter].Outputs[numOutput].NativePointer);

                // creating CPU-accessible texture resource
                dx11Texture2Ddescr = new SharpDX.Direct3D11.Texture2DDescription();
                dx11Texture2Ddescr.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.Read;
                dx11Texture2Ddescr.BindFlags = SharpDX.Direct3D11.BindFlags.None;
                dx11Texture2Ddescr.Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm;
                dx11Texture2Ddescr.Height = HEIGHT;
                dx11Texture2Ddescr.Width = WIDTH;
                dx11Texture2Ddescr.OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None;
                dx11Texture2Ddescr.MipLevels = 1;
                dx11Texture2Ddescr.ArraySize = 1;
                dx11Texture2Ddescr.SampleDescription.Count = 1;
                dx11Texture2Ddescr.SampleDescription.Quality = 0;
                dx11Texture2Ddescr.Usage = SharpDX.Direct3D11.ResourceUsage.Staging;
                dx11ScreenTexture = new SharpDX.Direct3D11.Texture2D(dx11Device, dx11Texture2Ddescr);

                // duplicate output stuff

                dx11DuplicatedOutput = dx11Output.DuplicateOutput(dx11Device);
            }
            catch (SharpDX.SharpDXException dxe)
            {
                string error = "Directx 11 initializer error.\n" + dxe.Message;
                LdpLog.Error(error);
                MessageBox.Show(error, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                string error = "Directx 11 initializer error.\n" + ex.Message;
                LdpLog.Error(error);
                MessageBox.Show(error, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        /// <summary>
        /// Creates a <see cref="SharpDX.Direct3D11.Texture2D"/> from a WIC <see cref="SharpDX.WIC.BitmapSource"/>
        /// </summary>
        /// <param name="device">The Direct3D11 device</param>
        /// <param name="bitmapSource">The WIC bitmap source</param>
        /// <returns>A Texture2D</returns>
        public static SharpDX.Direct3D11.Texture2D CreateTexture2DFromBitmap(SharpDX.Direct3D11.Device device, SharpDX.WIC.BitmapSource bitmapSource, SharpDX.Direct3D11.Texture2DDescription textDesc)
        {
            // Allocate DataStream to receive the WIC image pixels
            int stride = bitmapSource.Size.Width * 4;

            using (var buffer = new SharpDX.DataStream(bitmapSource.Size.Height * stride, true, true))
            {
                // Copy the content of the WIC to the buffer
                bitmapSource.CopyPixels(stride, buffer);
                return(new SharpDX.Direct3D11.Texture2D(device, textDesc, new SharpDX.DataRectangle(buffer.DataPointer, stride)));
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Adds the provided texture to the current manager
        /// </summary>
        /// <param name="texture">The tiled texture that needs to be managed</param>
        /// <param name="filePath">The filepath from where to load the texture data</param>
        /// <returns>The shader resource view for the created residency texture</returns>
        public SharpDX.Toolkit.Graphics.Texture2DBase ManageTexture(SharpDX.Toolkit.Graphics.TextureCube texture, string filePath)
        {
            // assume the diffuse texture has the BC1_Unorm format - store a path to it
            if (texture.Description.Format == Format.BC1_UNorm)
            {
                _diffuseFilepath = filePath;
            }

            var resource = new ManagedTiledResource {
                Texture = texture
            };

            var subresourceTilings = texture.Description.MipLevels * texture.Description.ArraySize;

            resource.SubresourceTilings = new SharpDX.Direct3D11.SubResourceTiling[subresourceTilings];

            var device2 = _graphicsDeviceManager.GetDevice2();

            device2.GetResourceTiling(texture,
                                      out resource.TotalTiles,
                                      out resource.PackedMipDescription,
                                      out resource.TileShape,
                                      ref subresourceTilings,
                                      0,
                                      resource.SubresourceTilings);

            if (subresourceTilings != texture.Description.MipLevels * texture.Description.ArraySize)
            {
                throw new ApplicationException("Unexpected value - subresourceTilings has changed");
            }

            resource.Loader = new TileLoader(filePath, resource.SubresourceTilings, false);

            var device = _graphicsDeviceManager.GraphicsDevice;

            var tiling = resource.SubresourceTilings[0];

            var size = Math.Max(tiling.WidthInTiles, tiling.HeightInTiles);

            var description = new SharpDX.Direct3D11.Texture2DDescription
            {
                Width             = size,
                Height            = size,
                MipLevels         = 1,
                ArraySize         = 6,
                BindFlags         = SharpDX.Direct3D11.BindFlags.ShaderResource,
                Format            = Format.R8_UNorm,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = SharpDX.Direct3D11.ResourceUsage.Default,
                OptionFlags       = SharpDX.Direct3D11.ResourceOptionFlags.TextureCube
            };

            resource.ResidencyTexture = ToDispose(SharpDX.Toolkit.Graphics.Texture2D.New(device, description));

            for (var face = 0; face < 6; face++)
            {
                resource.Residency[face] = new byte[tiling.WidthInTiles * tiling.HeightInTiles];
                Set(resource.Residency[face], (byte)0xff);
            }

            _managedTiledResources.Add(resource);

            return(resource.ResidencyTexture);
        }
Ejemplo n.º 32
0
        protected Texture2D(GraphicsDevice graphicsDevice, int width, int height, bool mipmap, SurfaceFormat format, SurfaceType type, bool shared)
		{
            if (graphicsDevice == null)
                throw new ArgumentNullException("Graphics Device Cannot Be Null");

            this.GraphicsDevice = graphicsDevice;
            this.width = width;
            this.height = height;
            this._format = format;
            this._levelCount = mipmap ? CalculateMipLevels(width, height) : 1;

            // Texture will be assigned by the swap chain.
		    if (type == SurfaceType.SwapChainRenderTarget)
		        return;

#if DIRECTX
            // TODO: Move this to SetData() if we want to make Immutable textures!
            var desc = new SharpDX.Direct3D11.Texture2DDescription();
            desc.Width = width;
            desc.Height = height;
            desc.MipLevels = _levelCount;
            desc.ArraySize = 1;
            desc.Format = SharpDXHelper.ToFormat(format);
            desc.BindFlags = SharpDX.Direct3D11.BindFlags.ShaderResource;
            desc.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None;
            desc.SampleDescription.Count = 1;
            desc.SampleDescription.Quality = 0;
            desc.Usage = SharpDX.Direct3D11.ResourceUsage.Default;
            desc.OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None;

            if (type == SurfaceType.RenderTarget)
            {
                desc.BindFlags |= SharpDX.Direct3D11.BindFlags.RenderTarget;
                if (mipmap)
                {
                    // Note: XNA 4 does not have a method Texture.GenerateMipMaps() 
                    // because generation of mipmaps is not supported on the Xbox 360.
                    // TODO: New method Texture.GenerateMipMaps() required.
                    desc.OptionFlags |= SharpDX.Direct3D11.ResourceOptionFlags.GenerateMipMaps;
                }
            }

            if (shared)
                desc.OptionFlags |= SharpDX.Direct3D11.ResourceOptionFlags.Shared;

            _texture = new SharpDX.Direct3D11.Texture2D(graphicsDevice._d3dDevice, desc);

#elif PSM
            PixelBufferOption option = PixelBufferOption.None;
            if (type == SurfaceType.RenderTarget)
			    option = PixelBufferOption.Renderable;
            _texture2D = new Sce.PlayStation.Core.Graphics.Texture2D(width, height, mipmap, PSSHelper.ToFormat(format),option);
#else

            this.glTarget = TextureTarget.Texture2D;
            
            Threading.BlockOnUIThread(() =>
            {
                // Store the current bound texture.
                var prevTexture = GraphicsExtensions.GetBoundTexture2D();

                GenerateGLTextureIfRequired();

                format.GetGLFormat(out glInternalFormat, out glFormat, out glType);

                if (glFormat == (GLPixelFormat)All.CompressedTextureFormats)
                {
                    var imageSize = 0;
                    switch (format)
                    {
                        case SurfaceFormat.RgbPvrtc2Bpp:
                        case SurfaceFormat.RgbaPvrtc2Bpp:
                            imageSize = (Math.Max(this.width, 8) * Math.Max(this.height, 8) * 2 + 7) / 8;
                            break;
                        case SurfaceFormat.RgbPvrtc4Bpp:
                        case SurfaceFormat.RgbaPvrtc4Bpp:
                            imageSize = (Math.Max(this.width, 16) * Math.Max(this.height, 8) * 4 + 7) / 8;
                            break;
                        case SurfaceFormat.Dxt1:
                        case SurfaceFormat.Dxt1a:
                        case SurfaceFormat.Dxt3:
                        case SurfaceFormat.Dxt5:
                            imageSize = ((this.width + 3) / 4) * ((this.height + 3) / 4) * format.Size();
                            break;
                        default:
                            throw new NotImplementedException();
                    }

                    GL.CompressedTexImage2D(TextureTarget.Texture2D, 0, glInternalFormat,
                                            this.width, this.height, 0,
                                            imageSize, IntPtr.Zero);
                    GraphicsExtensions.CheckGLError();
                }
                else
                {
                    GL.TexImage2D(TextureTarget.Texture2D, 0,
#if IOS || ANDROID
                        (int)glInternalFormat,
#else				           
					    glInternalFormat,
#endif
                        this.width, this.height, 0,
                        glFormat, glType, IntPtr.Zero);
                    GraphicsExtensions.CheckGLError();
                }

                // Restore the bound texture.
                GL.BindTexture(TextureTarget.Texture2D, prevTexture);
                GraphicsExtensions.CheckGLError();
            });
#endif
        }