public static SharpDX.Direct3D11.Texture2D CreateTex2DFromBitmap(SharpDX.WIC.BitmapSource bsource, GraphicsDevice device) { SharpDX.Direct3D11.Texture2DDescription desc; desc.Width = bsource.Size.Width; desc.Height = bsource.Size.Height; desc.ArraySize = 1; desc.BindFlags = SharpDX.Direct3D11.BindFlags.ShaderResource; desc.Usage = SharpDX.Direct3D11.ResourceUsage.Default; desc.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None; desc.Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm; desc.MipLevels = 1; desc.OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None; desc.SampleDescription.Count = 1; desc.SampleDescription.Quality = 0; SharpDX.Direct3D11.Texture2D dx11Texture; using(SharpDX.DataStream s = new SharpDX.DataStream(bsource.Size.Height * bsource.Size.Width * 4, true, true)) { bsource.CopyPixels(bsource.Size.Width * 4, s); SharpDX.DataRectangle rect = new SharpDX.DataRectangle(s.DataPointer, bsource.Size.Width * 4); dx11Texture = new SharpDX.Direct3D11.Texture2D(device._d3dDevice, desc, rect); } return dx11Texture; }
private SharpDX.WIC.FormatConverter DecodeImage() { var path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path; SharpDX.WIC.BitmapDecoder bitmapDecoder = new SharpDX.WIC.BitmapDecoder( _deviceManager.WICFactory, @"Assets\Nepal.jpg", SharpDX.IO.NativeFileAccess.Read, SharpDX.WIC.DecodeOptions.CacheOnDemand ); SharpDX.WIC.BitmapFrameDecode bitmapFrameDecode = bitmapDecoder.GetFrame(0); SharpDX.WIC.BitmapSource bitmapSource = new SharpDX.WIC.BitmapSource(bitmapFrameDecode.NativePointer); SharpDX.WIC.FormatConverter formatConverter = new SharpDX.WIC.FormatConverter(_deviceManager.WICFactory); //formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA); formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA, SharpDX.WIC.BitmapDitherType.None, null, 0.0f, SharpDX.WIC.BitmapPaletteType.Custom ); imageSize = formatConverter.Size; return(formatConverter); }
public static s.WIC.Bitmap ToBitmap(this s.WIC.BitmapSource bmp, Guid?pixelFormat = null) { using (var converter = new s.WIC.FormatConverter(SDFactory.WicImagingFactory)) { converter.Initialize(bmp, pixelFormat ?? s.WIC.PixelFormat.Format32bppPBGRA); return(new s.WIC.Bitmap(SDFactory.WicImagingFactory, converter, s.WIC.BitmapCreateCacheOption.CacheOnLoad)); } }
/// <summary> /// This doesnt work! SharpDX errors when trying to open a local system file (not relative) /// </summary> /// <param name="assetNativeUri"></param> /// <param name="backgroundImageFormatConverter"></param> /// <param name="backgroundImageSize"></param> public void LoadNativeAsset(string assetNativeUri, out SharpDX.WIC.FormatConverter backgroundImageFormatConverter, out Size2 backgroundImageSize) { var path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path; var nativeFileStream = new SharpDX.IO.NativeFileStream( assetNativeUri, SharpDX.IO.NativeFileMode.Open, SharpDX.IO.NativeFileAccess.Read, SharpDX.IO.NativeFileShare.Read); var r = SharpDX.IO.NativeFile.ReadAllBytes(assetNativeUri); var data = SharpDX.IO.NativeFile.ReadAllBytes(assetNativeUri); using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data)) { if (ms != null) { using (SharpDX.WIC.BitmapDecoder bitmapDecoder = new SharpDX.WIC.BitmapDecoder( _deviceManager.WICFactory, ms, SharpDX.WIC.DecodeOptions.CacheOnDemand )) { using (SharpDX.WIC.BitmapFrameDecode bitmapFrameDecode = bitmapDecoder.GetFrame(0)) { using (SharpDX.WIC.BitmapSource bitmapSource = new SharpDX.WIC.BitmapSource(bitmapFrameDecode.NativePointer)) { SharpDX.WIC.FormatConverter formatConverter = new SharpDX.WIC.FormatConverter(_deviceManager.WICFactory); //formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA); formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA, SharpDX.WIC.BitmapDitherType.None, null, 0.0f, SharpDX.WIC.BitmapPaletteType.Custom ); backgroundImageSize = formatConverter.Size; backgroundImageFormatConverter = formatConverter; } } } } } backgroundImageFormatConverter = null; backgroundImageSize = new Size2(0, 0); }
/// <summary> /// /// </summary> /// <param name="assetUri"></param> /// <param name="backgroundImageFormatConverter"></param> /// <param name="backgroundImageSize"></param> public void LoadAsset(string assetUri, out SharpDX.WIC.FormatConverter backgroundImageFormatConverter, out Size2 backgroundImageSize) { SharpDX.WIC.ImagingFactory2 wicFactory = null; if (_deviceManager == null) { wicFactory = new SharpDX.WIC.ImagingFactory2(); } else if (_deviceManager.WICFactory == null) { wicFactory = new SharpDX.WIC.ImagingFactory2(); } else { wicFactory = _deviceManager.WICFactory; } var path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path; SharpDX.WIC.BitmapDecoder bitmapDecoder = new SharpDX.WIC.BitmapDecoder( wicFactory, assetUri, SharpDX.IO.NativeFileAccess.Read, SharpDX.WIC.DecodeOptions.CacheOnDemand ); SharpDX.WIC.BitmapFrameDecode bitmapFrameDecode = bitmapDecoder.GetFrame(0); SharpDX.WIC.BitmapSource bitmapSource = new SharpDX.WIC.BitmapSource(bitmapFrameDecode.NativePointer); SharpDX.WIC.FormatConverter formatConverter = new SharpDX.WIC.FormatConverter(wicFactory); //formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA); formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA, SharpDX.WIC.BitmapDitherType.None, null, 0.0f, SharpDX.WIC.BitmapPaletteType.Custom ); backgroundImageSize = formatConverter.Size; backgroundImageFormatConverter = formatConverter; }
private SharpDX.WIC.FormatConverter DecodeImage() { var path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path; SharpDX.WIC.BitmapDecoder bitmapDecoder = new SharpDX.WIC.BitmapDecoder( _deviceManager.WICFactory, @"Assets\SydneyOperaHouse002.png", SharpDX.IO.NativeFileAccess.Read, SharpDX.WIC.DecodeOptions.CacheOnDemand ); SharpDX.WIC.BitmapFrameDecode bitmapFrameDecode = bitmapDecoder.GetFrame(0); SharpDX.WIC.BitmapSource bitmapSource = new SharpDX.WIC.BitmapSource(bitmapFrameDecode.NativePointer); SharpDX.WIC.FormatConverter formatConverter = new SharpDX.WIC.FormatConverter(_deviceManager.WICFactory); formatConverter.Initialize(bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA); return(formatConverter); }
public static D3D11.Texture2D CreateTexture2DFromBitmap(D3D11.Device device, SharpDX.WIC.BitmapSource bitmapSource) { // 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 D3D11.Texture2D(device, new D3D11.Texture2DDescription() { Width = bitmapSource.Size.Width, Height = bitmapSource.Size.Height, ArraySize = 1, BindFlags = D3D11.BindFlags.ShaderResource, Usage = D3D11.ResourceUsage.Immutable, CpuAccessFlags = D3D11.CpuAccessFlags.None, Format = Format.R8G8B8A8_UNorm, MipLevels = 1, OptionFlags = D3D11.ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), }, new DataRectangle(buffer.DataPointer, stride))); } }
public Texture2D LoadTexture(System.Drawing.Bitmap b) { System.IO.MemoryStream ms = new System.IO.MemoryStream(); b.Save(ms, System.Drawing.Imaging.ImageFormat.Png); ms.Seek(0, System.IO.SeekOrigin.Begin); SharpDX.WIC.BitmapDecoder decoder = new SharpDX.WIC.BitmapDecoder(ImageFactory, ms, SharpDX.WIC.DecodeOptions.CacheOnDemand); SharpDX.WIC.FormatConverter converter = new SharpDX.WIC.FormatConverter(ImageFactory); converter.Initialize(decoder.GetFrame(0), SharpDX.WIC.PixelFormat.Format32bppPRGBA, SharpDX.WIC.BitmapDitherType.None, null, 0.0, SharpDX.WIC.BitmapPaletteType.Custom); SharpDX.WIC.BitmapSource bitmap = converter; int stride = bitmap.Size.Width * 4; DataStream buffer = new DataStream(bitmap.Size.Height * stride, true, true); bitmap.CopyPixels(stride, buffer); Texture2D texture = new Texture2D(Device, new Texture2DDescription() { Width = bitmap.Size.Width, Height = bitmap.Size.Height, ArraySize = 1, BindFlags = BindFlags.ShaderResource, Usage = ResourceUsage.Immutable, CpuAccessFlags = CpuAccessFlags.None, Format = Format.R8G8B8A8_UNorm, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0) }, new DataRectangle(buffer.DataPointer, stride)); bitmap.Dispose(); buffer.Dispose(); ms.Dispose(); return(texture); }
/// <summary> /// <p>Encodes a bitmap source.</p> /// </summary> /// <param name="bitmapSource"><dd> <p>The bitmap source to encode.</p> </dd></param> /// <remarks> /// <p>If <strong>SetSize</strong> is not called prior to calling <strong>WriteSource</strong>, the size given in <em>prc</em> is used if not <strong><c>null</c></strong>. Otherwise, the size of the <strong><see cref="SharpDX.WIC.BitmapSource"/></strong> given in <em>pIBitmapSource</em> is used. </p><p>If <strong>SetPixelFormat</strong> is not called prior to calling <strong>WriteSource</strong>, the pixel format of the <strong><see cref="SharpDX.WIC.BitmapSource"/></strong> given in <em>pIBitmapSource</em> is used.</p><p>If <strong>SetResolution</strong> is not called prior to calling <strong>WriteSource</strong>, the pixel format of <em>pIBitmapSource</em> is used.</p><p>If <strong>SetPalette</strong> is not called prior to calling <strong>WriteSource</strong>, the target pixel format is indexed, and the pixel format of <em>pIBitmapSource</em> matches the encoder frame's pixel format, then the <em>pIBitmapSource</em> pixel format is used.</p><p>When encoding a GIF image, if the global palette is set and the frame level palette is not set directly by the user or by a custom independent software vendor (ISV) GIF codec, <strong>WriteSource</strong> will use the global palette to encode the frame even when <em>pIBitmapSource</em> has a frame level palette.</p><p><strong>Windows Vista:</strong>The source rect width must match the width set through SetSize. Repeated <strong>WriteSource</strong> calls can be made as long as the total accumulated source rect height is the same as set through SetSize.</p> /// </remarks> /// <include file='..\..\Documentation\CodeComments.xml' path="/comments/comment[@id='IWICBitmapFrameEncode::WriteSource']/*"/> /// <msdn-id>ee690159</msdn-id> /// <unmanaged>HRESULT IWICBitmapFrameEncode::WriteSource([In, Optional] IWICBitmapSource* pIBitmapSource,[In, Optional] WICRect* prc)</unmanaged> /// <unmanaged-short>IWICBitmapFrameEncode::WriteSource</unmanaged-short> public void WriteSource(SharpDX.WIC.BitmapSource bitmapSource) { WriteSource(bitmapSource, IntPtr.Zero); }
/// <summary> /// Initializes a new instance of the <see cref="Bitmap"/> class from a <see cref="BitmapSource"/>. /// </summary> /// <param name="factory">The factory.</param> /// <param name="bitmapSource">The bitmap source.</param> /// <param name="rectangle">The rectangle.</param> /// <msdn-id>ee690294</msdn-id> /// <unmanaged>HRESULT IWICImagingFactory::CreateBitmapFromSourceRect([In, Optional] IWICBitmapSource* pIBitmapSource,[In] unsigned int x,[In] unsigned int y,[In] unsigned int width,[In] unsigned int height,[Out, Fast] IWICBitmap** ppIBitmap)</unmanaged> /// <unmanaged-short>IWICImagingFactory::CreateBitmapFromSourceRect</unmanaged-short> public Bitmap(ImagingFactory factory, SharpDX.WIC.BitmapSource bitmapSource, Rectangle rectangle) : base(IntPtr.Zero) { factory.CreateBitmapFromSourceRect(bitmapSource, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, this); }
/// <summary> /// Initializes a new instance of the <see cref="Bitmap"/> class from a <see cref="BitmapSource"/> /// </summary> /// <param name="factory">The factory.</param> /// <param name="bitmapSource">The bitmap source ref.</param> /// <param name="option">The option.</param> /// <msdn-id>ee690293</msdn-id> /// <unmanaged>HRESULT IWICImagingFactory::CreateBitmapFromSource([In, Optional] IWICBitmapSource* pIBitmapSource,[In] WICBitmapCreateCacheOption option,[Out, Fast] IWICBitmap** ppIBitmap)</unmanaged> /// <unmanaged-short>IWICImagingFactory::CreateBitmapFromSource</unmanaged-short> public Bitmap(ImagingFactory factory, SharpDX.WIC.BitmapSource bitmapSource, SharpDX.WIC.BitmapCreateCacheOption option) : base(IntPtr.Zero) { factory.CreateBitmapFromSource(bitmapSource, option, this); }
/// <summary> /// Initializes this instance with the specified bitmap source and format /// </summary> /// <param name="sourceRef">The source ref.</param> /// <param name="dstFormat">The destination format.</param> /// <returns></returns> public void Initialize(SharpDX.WIC.BitmapSource sourceRef, System.Guid dstFormat) { Initialize(sourceRef, dstFormat, BitmapDitherType.None, null, 0.0, BitmapPaletteType.Custom); }
///// <summary> ///// ///// </summary> ///// <param name="assetUri"></param> ///// <param name="backgroundImageFormatConverter"></param> ///// <param name="backgroundImageSize"></param> //public void LoadAsset( // SharpDX.WIC.ImagingFactory2 wicFactory, // string assetUri, // out SharpDX.WIC.FormatConverter backgroundImageFormatConverter, // out DrawingSize backgroundImageSize) //{ // //var path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path; // SharpDX.WIC.BitmapDecoder bitmapDecoder = new SharpDX.WIC.BitmapDecoder( // wicFactory, // assetUri, // SharpDX.IO.NativeFileAccess.Read, // SharpDX.WIC.DecodeOptions.CacheOnDemand // ); // SharpDX.WIC.BitmapFrameDecode bitmapFrameDecode = bitmapDecoder.GetFrame(0); // SharpDX.WIC.BitmapSource bitmapSource = new SharpDX.WIC.BitmapSource(bitmapFrameDecode.NativePointer); // SharpDX.WIC.FormatConverter formatConverter = new SharpDX.WIC.FormatConverter(wicFactory); // //formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA); // formatConverter.Initialize( // bitmapSource, // SharpDX.WIC.PixelFormat.Format32bppBGRA, // SharpDX.WIC.BitmapDitherType.None, // null, // 0.0f, // SharpDX.WIC.BitmapPaletteType.Custom // ); // backgroundImageSize = formatConverter.Size; // backgroundImageFormatConverter = formatConverter; //} /// <summary> /// Loads bitmap asynchronously and injects into global variables. I need to work out how to NOT make them global /// </summary> /// <param name="assetNativeUri"></param> /// <returns></returns> public async Task<Tuple<SharpDX.WIC.FormatConverter, Size2, Stream>> LoadAssetAsync( SharpDX.WIC.ImagingFactory2 wicFactory, string assetNativeUri, string cacheId, string path = "" ) { if (_listOfAssets.ContainsKey(cacheId)) return _listOfAssets[cacheId]; SharpDX.WIC.FormatConverter _backgroundImageFormatConverter = null; Size2 _backgroundImageSize = new Size2(0, 0); Windows.Storage.StorageFile storageFile = null; if(path == string.Empty) { path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path; storageFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(path + assetNativeUri); } else if (path == "PicturesLibrary") { var assetNativeUriParts = assetNativeUri.Split("\\".ToCharArray()); var foundFolder = await Windows.Storage.KnownFolders.PicturesLibrary.GetFolderAsync(assetNativeUriParts[0]); storageFile = await foundFolder.GetFileAsync(assetNativeUriParts[1]); } else if (path == "PublicPicturesLibrary") { var assetNativeUriParts = assetNativeUri.Split("\\".ToCharArray()); var foundFolder = await Windows.Storage.KnownFolders.PicturesLibrary.GetFolderAsync(assetNativeUriParts[0]); storageFile = await foundFolder.GetFileAsync(assetNativeUriParts[1]); } if (storageFile == null) return null; Stream ms = await storageFile.OpenStreamForReadAsync(); //ras.GetResults().AsStreamForRead()) //var data = SharpDX.IO.NativeFile.ReadAllBytes(assetNativeUri); //using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data)) { if (ms != null) { SharpDX.WIC.BitmapDecoder bitmapDecoder = new SharpDX.WIC.BitmapDecoder( wicFactory, ms, SharpDX.WIC.DecodeOptions.CacheOnDemand ); { using (SharpDX.WIC.BitmapFrameDecode bitmapFrameDecode = bitmapDecoder.GetFrame(0)) { using(SharpDX.WIC.BitmapSource bitmapSource = new SharpDX.WIC.BitmapSource(bitmapFrameDecode.NativePointer)) { SharpDX.WIC.FormatConverter formatConverter = new SharpDX.WIC.FormatConverter(wicFactory); //formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA); formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA, SharpDX.WIC.BitmapDitherType.None, null, 0.0f, SharpDX.WIC.BitmapPaletteType.Custom ); _backgroundImageSize = formatConverter.Size; _backgroundImageFormatConverter = formatConverter; //return Tuple.Create<SharpDX.WIC.FormatConverter, Size2>(_backgroundImageFormatConverter, _backgroundImageSize); } } } } } //ras.Close(); var ret = Tuple.Create<SharpDX.WIC.FormatConverter, Size2, Stream>(_backgroundImageFormatConverter, _backgroundImageSize, ms); _listOfAssets.Add(cacheId, ret); return ret; }
/// <summary> /// <p>Initializes the bitmap clipper with the provided parameters.</p> /// </summary> /// <param name="sourceRef"><dd> <p>he input bitmap source.</p> </dd></param> /// <param name="rectangleRef"><dd> <p>The rectangle of the bitmap source to clip.</p> </dd></param> /// <returns><p>If this method succeeds, it returns <strong><see cref="SharpDX.Result.Ok"/></strong>. Otherwise, it returns an <strong><see cref="SharpDX.Result"/></strong> error code.</p></returns> /// <msdn-id>ee719677</msdn-id> /// <unmanaged>HRESULT IWICBitmapClipper::Initialize([In, Optional] IWICBitmapSource* pISource,[In] const WICRect* prc)</unmanaged> /// <unmanaged-short>IWICBitmapClipper::Initialize</unmanaged-short> public unsafe void Initialize(SharpDX.WIC.BitmapSource sourceRef, RawBox rectangleRef) { Initialize(sourceRef, new IntPtr(&rectangleRef)); }
// Old bitmap is disposed (should be set to null before if it is used in some other place) public void SetBitmapSource(Device dxDevice, SharpDX.WIC.BitmapSource bitmapSource) { this.SetField(ref _texture, null); this.SetField(ref _resourceView, null); this.SetField(ref _bitmap, null); _bitmap = bitmapSource; _texture = TextureLoader.CreateTexture2DFromBitmap(dxDevice, bitmapSource); _resourceView = new ShaderResourceView(dxDevice, _texture, new ShaderResourceViewDescription() { Format = _texture.Description.Format, Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource() { MipLevels = 1, MostDetailedMip = 0 } }); }
// the code below failing due to GC /*public static SharpDX.WIC.BitmapSource LoadBitmap(DirectXContext directXContext, Stream stream) * { * var bitmapDecoder = new SharpDX.WIC.BitmapDecoder( * directXContext.ImagingFactory2, * stream, * SharpDX.WIC.DecodeOptions.CacheOnLoad); * * var formatConverter = new SharpDX.WIC.FormatConverter(directXContext.ImagingFactory2); * * formatConverter.Initialize( * bitmapDecoder.GetFrame(0), * SharpDX.WIC.PixelFormat.Format32bppPRGBA, * SharpDX.WIC.BitmapDitherType.None, * null, * 0.0, * SharpDX.WIC.BitmapPaletteType.Custom); * * return formatConverter; * }*/ public static DirectXResource CreateTexture2DFromBitmap(DirectXContext directXContext, SharpDX.WIC.BitmapSource bitmapSource) { // 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)) { try { // Copy the content of the WIC to the buffer bitmapSource.CopyPixels(stride, buffer); } catch (Exception e) { Core.LogError(e, "Failed to load image into Dx"); } return(directXContext.Pool.Get("loadbitmap", DirectXResource.Desc(bitmapSource.Size.Width, bitmapSource.Size.Height, SharpDX.DXGI.Format.R8G8B8A8_UNorm, SharpDX.Direct3D11.BindFlags.ShaderResource, SharpDX.Direct3D11.ResourceUsage.Immutable), new SharpDX.DataRectangle(buffer.DataPointer, stride))); } }
///// <summary> ///// ///// </summary> ///// <param name="assetUri"></param> ///// <param name="backgroundImageFormatConverter"></param> ///// <param name="backgroundImageSize"></param> //public void LoadAsset( // SharpDX.WIC.ImagingFactory2 wicFactory, // string assetUri, // out SharpDX.WIC.FormatConverter backgroundImageFormatConverter, // out DrawingSize backgroundImageSize) //{ // //var path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path; // SharpDX.WIC.BitmapDecoder bitmapDecoder = new SharpDX.WIC.BitmapDecoder( // wicFactory, // assetUri, // SharpDX.IO.NativeFileAccess.Read, // SharpDX.WIC.DecodeOptions.CacheOnDemand // ); // SharpDX.WIC.BitmapFrameDecode bitmapFrameDecode = bitmapDecoder.GetFrame(0); // SharpDX.WIC.BitmapSource bitmapSource = new SharpDX.WIC.BitmapSource(bitmapFrameDecode.NativePointer); // SharpDX.WIC.FormatConverter formatConverter = new SharpDX.WIC.FormatConverter(wicFactory); // //formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA); // formatConverter.Initialize( // bitmapSource, // SharpDX.WIC.PixelFormat.Format32bppBGRA, // SharpDX.WIC.BitmapDitherType.None, // null, // 0.0f, // SharpDX.WIC.BitmapPaletteType.Custom // ); // backgroundImageSize = formatConverter.Size; // backgroundImageFormatConverter = formatConverter; //} /// <summary> /// Loads bitmap asynchronously and injects into global variables. I need to work out how to NOT make them global /// </summary> /// <param name="assetNativeUri"></param> /// <returns></returns> public async Task <Tuple <SharpDX.WIC.FormatConverter, Size2, Stream> > LoadAssetAsync( SharpDX.WIC.ImagingFactory2 wicFactory, string assetNativeUri, string cacheId, string path = "" ) { if (_listOfAssets.ContainsKey(cacheId)) { return(_listOfAssets[cacheId]); } SharpDX.WIC.FormatConverter _backgroundImageFormatConverter = null; Size2 _backgroundImageSize = new Size2(0, 0); Windows.Storage.StorageFile storageFile = null; if (path == string.Empty) { path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path; storageFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(path + assetNativeUri); } else if (path == "PicturesLibrary") { var assetNativeUriParts = assetNativeUri.Split("\\".ToCharArray()); var foundFolder = await Windows.Storage.KnownFolders.PicturesLibrary.GetFolderAsync(assetNativeUriParts[0]); storageFile = await foundFolder.GetFileAsync(assetNativeUriParts[1]); } else if (path == "PublicPicturesLibrary") { var assetNativeUriParts = assetNativeUri.Split("\\".ToCharArray()); var foundFolder = await Windows.Storage.KnownFolders.PicturesLibrary.GetFolderAsync(assetNativeUriParts[0]); storageFile = await foundFolder.GetFileAsync(assetNativeUriParts[1]); } if (storageFile == null) { return(null); } Stream ms = await storageFile.OpenStreamForReadAsync(); //ras.GetResults().AsStreamForRead()) //var data = SharpDX.IO.NativeFile.ReadAllBytes(assetNativeUri); //using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data)) { if (ms != null) { SharpDX.WIC.BitmapDecoder bitmapDecoder = new SharpDX.WIC.BitmapDecoder( wicFactory, ms, SharpDX.WIC.DecodeOptions.CacheOnDemand ); { using (SharpDX.WIC.BitmapFrameDecode bitmapFrameDecode = bitmapDecoder.GetFrame(0)) { using (SharpDX.WIC.BitmapSource bitmapSource = new SharpDX.WIC.BitmapSource(bitmapFrameDecode.NativePointer)) { SharpDX.WIC.FormatConverter formatConverter = new SharpDX.WIC.FormatConverter(wicFactory); //formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA); formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA, SharpDX.WIC.BitmapDitherType.None, null, 0.0f, SharpDX.WIC.BitmapPaletteType.Custom ); _backgroundImageSize = formatConverter.Size; _backgroundImageFormatConverter = formatConverter; //return Tuple.Create<SharpDX.WIC.FormatConverter, Size2>(_backgroundImageFormatConverter, _backgroundImageSize); } } } } } //ras.Close(); var ret = Tuple.Create <SharpDX.WIC.FormatConverter, Size2, Stream>(_backgroundImageFormatConverter, _backgroundImageSize, ms); _listOfAssets.Add(cacheId, ret); return(ret); }
private async void RenderD3DDto(string assetUrl, RenderDTO rDto) { if (rDto == null) { return; } if (string.IsNullOrEmpty(assetUrl)) { return; } // Setup local variables var d3dDevice = _deviceManager.DeviceDirect3D; var d3dContext = _deviceManager.ContextDirect3D; var d2dDevice = _deviceManager.DeviceDirect2D; var d2dContext = _deviceManager.ContextDirect2D; // Load texture and create sampler //using (var bitmap = TextureLoader.LoadBitmap(_deviceManager.WICFactory, string.IsNullOrEmpty(project.AssetUrl)?"Assets\\Textures\\5.jpg": project.AssetUrl )) //using (var texture2D = TextureLoader.CreateTexture2DFromBitmap(d3dDevice, bitmap)) // rDto.D3DPrimitiveDTO.TextureView = new ShaderResourceView(d3dDevice, texture2D); //Fill D2D THEN push D2D -> D3D var fc = await this.LoadAssetAsync(_deviceManager.WICFactory, assetUrl, Guid.NewGuid().ToString()); //using (SharpDX.WIC.BitmapSource bitmap = TextureLoader.LoadBitmap(_deviceManager.WICFactory, assetUrl)) using (SharpDX.WIC.BitmapSource bitmap = (SharpDX.WIC.BitmapSource)fc.Item1) { d2dContext.Transform = Matrix.Identity; rDto.D3DPrimitiveDTO.Texture2D = AllocateTextureReturnSurface(d3dDevice, new Size2F(bitmap.Size.Width, bitmap.Size.Height)); d2dContext.Target = new SharpDX.Direct2D1.Bitmap1(d2dContext, rDto.D3DPrimitiveDTO.Texture2D.QueryInterface <SharpDX.DXGI.Surface>()); rDto.D3DPrimitiveDTO.TextureView = new ShaderResourceView(d3dDevice, rDto.D3DPrimitiveDTO.Texture2D); d2dContext.BeginDraw(); SharpDX.Direct2D1.Effects.BitmapSource effectBitmapSource = new SharpDX.Direct2D1.Effects.BitmapSource(d2dContext); effectBitmapSource.WicBitmapSource = bitmap; //SharpDX.Direct2D1.Effects.Shadow shadowEffect = new SharpDX.Direct2D1.Effects.Shadow(d2dContext); //shadowEffect.SetInputEffect(0, effectBitmapSource, true); //shadowEffect.BlurStandardDeviation = 10.0f; //d2dContext.DrawImage(shadowEffect); d2dContext.DrawImage(effectBitmapSource); //d2dContext.FillRectangle(new RectangleF(0, bitmap.Size.Height - 90, bitmap.Size.Width, bitmap.Size.Height), new SharpDX.Direct2D1.SolidColorBrush(d2dContext, this.AccentColorLightBy2Degree)); //if (project.Title != null) //{ // SharpDX.DirectWrite.TextFormat tf = new SharpDX.DirectWrite.TextFormat(_deviceManager.FactoryDirectWrite, "segoe ui", 28.0f); // d2dContext.DrawText(project.Title, tf, new RectangleF(10, bitmap.Size.Height - 90 + 10, bitmap.Size.Width, bitmap.Size.Height), new SharpDX.Direct2D1.SolidColorBrush(d2dContext, Color.White)); //} //if (project.Description != null) //{ // SharpDX.DirectWrite.TextFormat tf = new SharpDX.DirectWrite.TextFormat(_deviceManager.FactoryDirectWrite, "segoe ui", 21.0f); // d2dContext.DrawText(project.Description, tf, new RectangleF(10, bitmap.Size.Height - 90 + 40, bitmap.Size.Width, bitmap.Size.Height), new SharpDX.Direct2D1.SolidColorBrush(d2dContext, Color.White)); //} //PathToD2DPathGeometryConverter pathConverter = new PathToD2DPathGeometryConverter(); //if (!string.IsNullOrEmpty(project.PathResource)) //{ // var resourceFound = App.Current.Resources[project.PathResource]; // var pathGeometryCreated = pathConverter.parse((string)resourceFound, _deviceManager.FactoryDirect2D); // var pathGeometryCreatedSize = pathGeometryCreated.GetBounds(); // d2dContext.FillRectangle( // new RectangleF(bitmap.Size.Width - pathGeometryCreatedSize.Width - 20, 0, bitmap.Size.Width, pathGeometryCreatedSize.Height + 20) // , new SharpDX.Direct2D1.SolidColorBrush(d2dContext, this.AccentColor) // ); // d2dContext.Transform = Matrix.Translation(bitmap.Size.Width - pathGeometryCreatedSize.Width - 10, 10, 0); // //d2dContext.StrokeWidth = 2.0f; // d2dContext.FillGeometry(pathGeometryCreated, new SharpDX.Direct2D1.SolidColorBrush(d2dContext, this.AccentColorLightBy2Degree)); // //d2dContext.DrawGeometry(pathGeometryCreated, new SharpDX.Direct2D1.SolidColorBrush(d2dContext, this.AccentColor)); //} d2dContext.EndDraw(); } }
/// <summary> /// <p>Encodes a bitmap source.</p> /// </summary> /// <param name="bitmapSourceRef"><dd> <p>The bitmap source to encode.</p> </dd></param> /// <param name="rectangleRef"><dd> <p>The size rectangle of the bitmap source.</p> </dd></param> /// <remarks> /// <p>If <strong>SetSize</strong> is not called prior to calling <strong>WriteSource</strong>, the size given in <em>prc</em> is used if not <strong><c>null</c></strong>. Otherwise, the size of the <strong><see cref="SharpDX.WIC.BitmapSource"/></strong> given in <em>pIBitmapSource</em> is used. </p><p>If <strong>SetPixelFormat</strong> is not called prior to calling <strong>WriteSource</strong>, the pixel format of the <strong><see cref="SharpDX.WIC.BitmapSource"/></strong> given in <em>pIBitmapSource</em> is used.</p><p>If <strong>SetResolution</strong> is not called prior to calling <strong>WriteSource</strong>, the pixel format of <em>pIBitmapSource</em> is used.</p><p>If <strong>SetPalette</strong> is not called prior to calling <strong>WriteSource</strong>, the target pixel format is indexed, and the pixel format of <em>pIBitmapSource</em> matches the encoder frame's pixel format, then the <em>pIBitmapSource</em> pixel format is used.</p><p>When encoding a GIF image, if the global palette is set and the frame level palette is not set directly by the user or by a custom independent software vendor (ISV) GIF codec, <strong>WriteSource</strong> will use the global palette to encode the frame even when <em>pIBitmapSource</em> has a frame level palette.</p><p><strong>Windows Vista:</strong>The source rect width must match the width set through SetSize. Repeated <strong>WriteSource</strong> calls can be made as long as the total accumulated source rect height is the same as set through SetSize.</p> /// </remarks> /// <include file='..\..\Documentation\CodeComments.xml' path="/comments/comment[@id='IWICBitmapFrameEncode::WriteSource']/*"/> /// <msdn-id>ee690159</msdn-id> /// <unmanaged>HRESULT IWICBitmapFrameEncode::WriteSource([In, Optional] IWICBitmapSource* pIBitmapSource,[In, Optional] WICRect* prc)</unmanaged> /// <unmanaged-short>IWICBitmapFrameEncode::WriteSource</unmanaged-short> public unsafe void WriteSource(SharpDX.WIC.BitmapSource bitmapSourceRef, RawBox rectangleRef) { WriteSource(bitmapSourceRef, new IntPtr(&rectangleRef)); }
/// <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))); } }
/// <summary> /// <p>Encodes a bitmap source.</p> /// </summary> /// <param name="bitmapSourceRef"><dd> <p>The bitmap source to encode.</p> </dd></param> /// <param name="rectangleRef"><dd> <p>The size rectangle of the bitmap source.</p> </dd></param> /// <remarks> /// <p>If <strong>SetSize</strong> is not called prior to calling <strong>WriteSource</strong>, the size given in <em>prc</em> is used if not <strong><c>null</c></strong>. Otherwise, the size of the <strong><see cref="SharpDX.WIC.BitmapSource"/></strong> given in <em>pIBitmapSource</em> is used. </p><p>If <strong>SetPixelFormat</strong> is not called prior to calling <strong>WriteSource</strong>, the pixel format of the <strong><see cref="SharpDX.WIC.BitmapSource"/></strong> given in <em>pIBitmapSource</em> is used.</p><p>If <strong>SetResolution</strong> is not called prior to calling <strong>WriteSource</strong>, the pixel format of <em>pIBitmapSource</em> is used.</p><p>If <strong>SetPalette</strong> is not called prior to calling <strong>WriteSource</strong>, the target pixel format is indexed, and the pixel format of <em>pIBitmapSource</em> matches the encoder frame's pixel format, then the <em>pIBitmapSource</em> pixel format is used.</p><p>When encoding a GIF image, if the global palette is set and the frame level palette is not set directly by the user or by a custom independent software vendor (ISV) GIF codec, <strong>WriteSource</strong> will use the global palette to encode the frame even when <em>pIBitmapSource</em> has a frame level palette.</p><p><strong>Windows Vista:</strong>The source rect width must match the width set through SetSize. Repeated <strong>WriteSource</strong> calls can be made as long as the total accumulated source rect height is the same as set through SetSize.</p> /// </remarks> /// <include file='..\..\Documentation\CodeComments.xml' path="/comments/comment[@id='IWICBitmapFrameEncode::WriteSource']/*"/> /// <msdn-id>ee690159</msdn-id> /// <unmanaged>HRESULT IWICBitmapFrameEncode::WriteSource([In, Optional] IWICBitmapSource* pIBitmapSource,[In, Optional] WICRect* prc)</unmanaged> /// <unmanaged-short>IWICBitmapFrameEncode::WriteSource</unmanaged-short> public unsafe void WriteSource(SharpDX.WIC.BitmapSource bitmapSourceRef, Rectangle rectangleRef) { rectangleRef.MakeXYAndWidthHeight(); WriteSource(bitmapSourceRef, new IntPtr(&rectangleRef)); }
private SharpDX.WIC.FormatConverter DecodeImage() { var path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path; SharpDX.WIC.BitmapDecoder bitmapDecoder = new SharpDX.WIC.BitmapDecoder( _deviceManager.WICFactory, @"Assets\heightmap.png", SharpDX.IO.NativeFileAccess.Read, SharpDX.WIC.DecodeOptions.CacheOnDemand ); SharpDX.WIC.BitmapFrameDecode bitmapFrameDecode = bitmapDecoder.GetFrame(0); SharpDX.WIC.BitmapSource bitmapSource = new SharpDX.WIC.BitmapSource(bitmapFrameDecode.NativePointer); SharpDX.WIC.FormatConverter formatConverter = new SharpDX.WIC.FormatConverter(_deviceManager.WICFactory); //formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA); formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA, SharpDX.WIC.BitmapDitherType.None, null, 0.0f, SharpDX.WIC.BitmapPaletteType.Custom ); return formatConverter; }
/// <summary> /// /// </summary> /// <param name="assetUri"></param> /// <param name="backgroundImageFormatConverter"></param> /// <param name="backgroundImageSize"></param> public void LoadAsset(string assetUri, out SharpDX.WIC.FormatConverter backgroundImageFormatConverter, out Size2 backgroundImageSize) { SharpDX.WIC.ImagingFactory2 wicFactory = null; if (_deviceManager == null) wicFactory = new SharpDX.WIC.ImagingFactory2(); else if (_deviceManager.WICFactory == null) wicFactory = new SharpDX.WIC.ImagingFactory2(); else wicFactory = _deviceManager.WICFactory; var path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path; SharpDX.WIC.BitmapDecoder bitmapDecoder = new SharpDX.WIC.BitmapDecoder( wicFactory, assetUri, SharpDX.IO.NativeFileAccess.Read, SharpDX.WIC.DecodeOptions.CacheOnDemand ); SharpDX.WIC.BitmapFrameDecode bitmapFrameDecode = bitmapDecoder.GetFrame(0); SharpDX.WIC.BitmapSource bitmapSource = new SharpDX.WIC.BitmapSource(bitmapFrameDecode.NativePointer); SharpDX.WIC.FormatConverter formatConverter = new SharpDX.WIC.FormatConverter(wicFactory); //formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA); formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA, SharpDX.WIC.BitmapDitherType.None, null, 0.0f, SharpDX.WIC.BitmapPaletteType.Custom ); backgroundImageSize = formatConverter.Size; backgroundImageFormatConverter = formatConverter; }
public void CreateDeviceDependentResourcesAsync(DeviceResources deviceResources) { byte[] bytes = Convert.FromBase64String(spriteImg); Stream stream = new MemoryStream(bytes); var factory = new SharpDX.WIC.ImagingFactory2(); var bitmapDecoder = new SharpDX.WIC.BitmapDecoder( factory, stream, SharpDX.WIC.DecodeOptions.CacheOnDemand ); var formatConverter = new SharpDX.WIC.FormatConverter(factory); formatConverter.Initialize( bitmapDecoder.GetFrame(0), SharpDX.WIC.PixelFormat.Format32bppPRGBA, SharpDX.WIC.BitmapDitherType.None, null, 0.0, SharpDX.WIC.BitmapPaletteType.Custom); SharpDX.WIC.BitmapSource bitmapSource = formatConverter; imageWidth = bitmapSource.Size.Width; imageHeight = bitmapSource.Size.Height; var height = bitmapSource.Size.Height * Spritesheet.textureScaleFactor; var width = bitmapSource.Size.Width * Spritesheet.textureScaleFactor; BlendStateDescription blendSdesc = new BlendStateDescription(); blendSdesc.IndependentBlendEnable = false; blendSdesc.AlphaToCoverageEnable = false; blendSdesc.RenderTarget[0].IsBlendEnabled = true; blendSdesc.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha; blendSdesc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; blendSdesc.RenderTarget[0].BlendOperation = BlendOperation.Add; blendSdesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; blendSdesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; blendSdesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; blendSdesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; BlendState blendS = new BlendState(deviceResources.D3DDevice, blendSdesc); deviceResources.D3DDeviceContext.OutputMerger.SetBlendState(blendS); // 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). VertexPositionTexture[] cubeVertices = { new VertexPositionTexture(new System.Numerics.Vector3(-1f * width, -1f * height, 0f), new System.Numerics.Vector2(0.0f, 1.0f)), new VertexPositionTexture(new System.Numerics.Vector3(1f * width, -1f * height, 0f), new System.Numerics.Vector2(1.0f, 1.0f)), new VertexPositionTexture(new System.Numerics.Vector3(-1f * width, 1f * height, 0f), new System.Numerics.Vector2(0.0f, 0.0f)), new VertexPositionTexture(new System.Numerics.Vector3(1f * width, 1f * height, 0f), new System.Numerics.Vector2(1.0f, 0.0f)) }; BufferDescription mdescription = new BufferDescription(sizeof(float) * 5 * cubeVertices.Length, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0); vertexBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create( deviceResources.D3DDevice, cubeVertices, mdescription)); //vertexBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create( // deviceResources.D3DDevice, // SharpDX.Direct3D11.BindFlags.VertexBuffer, // cubeVertices, // 0, // ResourceUsage.Dynamic, CpuAccessFlags.Write)); // 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, //back face 2, 0, 1, // -x 2, 1, 3, }; 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)); //Load the image Texture2D texture = TextureLoader.CreateTexture2DFromBitmap(deviceResources.D3DDevice, bitmapSource); textureView = new ShaderResourceView(deviceResources.D3DDevice, texture); deviceResources.D3DDeviceContext.PixelShader.SetShaderResource(0, textureView); //Load the sampler SamplerStateDescription samplerDesc = new SamplerStateDescription(); samplerDesc.AddressU = TextureAddressMode.Wrap; samplerDesc.AddressV = TextureAddressMode.Wrap; samplerDesc.AddressW = TextureAddressMode.Wrap; samplerDesc.ComparisonFunction = Comparison.Never; samplerDesc.Filter = Filter.MinMagMipLinear; samplerDesc.MaximumLod = float.MaxValue; SamplerState sampler = new SamplerState(deviceResources.D3DDevice, samplerDesc); deviceResources.D3DDeviceContext.PixelShader.SetSampler(0, sampler); hasLoaded = true; }
/// <summary> /// <p>Initializes the bitmap clipper with the provided parameters.</p> /// </summary> /// <param name="sourceRef"><dd> <p>he input bitmap source.</p> </dd></param> /// <param name="rectangleRef"><dd> <p>The rectangle of the bitmap source to clip.</p> </dd></param> /// <returns><p>If this method succeeds, it returns <strong><see cref="SharpDX.Result.Ok"/></strong>. Otherwise, it returns an <strong><see cref="SharpDX.Result"/></strong> error code.</p></returns> /// <msdn-id>ee719677</msdn-id> /// <unmanaged>HRESULT IWICBitmapClipper::Initialize([In, Optional] IWICBitmapSource* pISource,[In] const WICRect* prc)</unmanaged> /// <unmanaged-short>IWICBitmapClipper::Initialize</unmanaged-short> public unsafe void Initialize(SharpDX.WIC.BitmapSource sourceRef, Rectangle rectangleRef) { rectangleRef.MakeXYAndWidthHeight(); Initialize(sourceRef, new IntPtr(&rectangleRef)); }