Guest User

Untitled

a guest
May 22nd, 2018
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. public bool Initialize(SharpDX.Direct3D11.Device device, string fileName)
  2. {
  3. try
  4. {
  5. using (var texture = LoadFromFile(device, new SharpDX.WIC.ImagingFactory(), fileName))
  6. {
  7. ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription()
  8. {
  9. Format = texture.Description.Format,
  10. Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D,
  11. };
  12. srvDesc.Texture2D.MostDetailedMip = 0;
  13. srvDesc.Texture2D.MipLevels = -1;
  14.  
  15. TextureResource = new ShaderResourceView(device, texture, srvDesc);
  16. device.ImmediateContext.GenerateMips(TextureResource);
  17. }
  18. // TextureResource = ShaderResourceView.FromFile(device, fileName);
  19. return true;
  20. }
  21. catch
  22. {
  23. return false;
  24. }
  25. }
  26.  
  27. public Texture2D LoadFromFile(SharpDX.Direct3D11.Device device, ImagingFactory factory, string fileName)
  28. {
  29. using (var bs = LoadBitmap(factory, fileName))
  30. return CreateTexture2DFromBitmapSource(device, bs);
  31. }
  32.  
  33. public BitmapSource LoadBitmap(ImagingFactory factory, string filename)
  34. {
  35. var bitmapDecoder = new SharpDX.WIC.BitmapDecoder(
  36. factory,
  37. filename,
  38. SharpDX.WIC.DecodeOptions.CacheOnDemand
  39. );
  40.  
  41. var result = new SharpDX.WIC.FormatConverter(factory);
  42.  
  43. result.Initialize(
  44. bitmapDecoder.GetFrame(0),
  45. SharpDX.WIC.PixelFormat.Format32bppPRGBA,
  46. SharpDX.WIC.BitmapDitherType.None,
  47. null,
  48. 0.0,
  49. SharpDX.WIC.BitmapPaletteType.Custom);
  50.  
  51. return result;
  52. }
  53.  
  54. public Texture2D CreateTexture2DFromBitmapSource(SharpDX.Direct3D11.Device device, BitmapSource bitmapSource)
  55. {
  56. // Allocate DataStream to receive the WIC image pixels
  57. int stride = bitmapSource.Size.Width * 4;
  58. using (var buffer = new SharpDX.DataStream(bitmapSource.Size.Height * stride, true, true))
  59. {
  60. // Copy the content of the WIC to the buffer
  61. bitmapSource.CopyPixels(stride, buffer);
  62. return new SharpDX.Direct3D11.Texture2D(device, new SharpDX.Direct3D11.Texture2DDescription()
  63. {
  64. Width = bitmapSource.Size.Width,
  65. Height = bitmapSource.Size.Height,
  66. ArraySize = 1,
  67. BindFlags = SharpDX.Direct3D11.BindFlags.ShaderResource | BindFlags.RenderTarget,
  68. Usage = SharpDX.Direct3D11.ResourceUsage.Default,
  69. CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None,
  70. Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
  71. MipLevels = 1,
  72. OptionFlags = ResourceOptionFlags.GenerateMipMaps, // ResourceOptionFlags.GenerateMipMap
  73. SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
  74. }, new SharpDX.DataRectangle(buffer.DataPointer, stride));
  75. }
  76. }
Add Comment
Please, Sign In to add comment