I'm trying to create an off-screen bitmap to draw on it and to draw it with Direct2D1.RenderTarget.DrawBitmap then. So I create Texture2D and get the Bitmap from it. But I receive the error
[D2DERR_UNSUPPORTED_PIXEL_FORMAT/UnsupportedPixelFormat]
in last string of code. Please help me to understand, what have i done wrong here?
m_texture = new Texture2D(
context.Device,
new Texture2DDescription() {
ArraySize = 1,
BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
CpuAccessFlags = CpuAccessFlags.None,
Format = Format.B8G8R8A8_UNorm,
Height = bitmapSize.Height,
Width = bitmapSize.Width,
MipLevels = 1,
OptionFlags = ResourceOptionFlags.None,
SampleDescription = new SampleDescription() {
Count = 1,
Quality = 0
},
Usage = ResourceUsage.Default
}
);
m_surface = m_texture.QueryInterface<Surface>();
using (SharpDX.Direct2D1.Factory factory = new SharpDX.Direct2D1.Factory()) {
m_renderTarget = new RenderTarget(
factory,
m_surface,
new RenderTargetProperties() {
DpiX = 0.0f, // default dpi
DpiY = 0.0f, // default dpi
MinLevel = SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT,
Type = RenderTargetType.Hardware,
Usage = RenderTargetUsage.None,
PixelFormat = new SharpDX.Direct2D1.PixelFormat(
Format.Unknown,
AlphaMode.Premultiplied
)
}
);
}
m_bitmap = new SharpDX.Direct2D1.Bitmap(m_renderTarget, m_surface);
public static SharpDX.Direct2D1.Bitmap GetBitmapFromSRV(SharpDX.Direct3D11.ShaderResourceView srv, RenderTarget renderTarger)
{
using (var texture = srv.ResourceAs<Texture2D>())
using (var surface = texture.QueryInterface<Surface>())
{
var bitmap = new SharpDX.Direct2D1.Bitmap(renderTarger, surface, new SharpDX.Direct2D1.BitmapProperties(new SharpDX.Direct2D1.PixelFormat(
Format.R8G8B8A8_UNorm,
SharpDX.Direct2D1.AlphaMode.Premultiplied)));
return bitmap;
}
}
Related
we apply a d2dcontext effect gaussianblureffect to a JPG file 4000*3000 32bit , sharpdx takes 270ms , c++ dx version takes 6ms, seems that the graphic accelerate was not functional. the sharpdx code is below.
enter var desc = new SwapChainDescription()
{
BufferCount = 1,
ModeDescription = new ModeDescription(Width, Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
IsWindowed = true,
OutputHandle = this.Handle,
SampleDescription = new SampleDescription(1, 0),
SwapEffect = SwapEffect.Discard,
Usage = Usage.RenderTargetOutput
};
// Create Device and SwapChain
SharpDX.Direct3D11.Device.CreateWithSwapChain(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.BgraSupport,
new[] { SharpDX.Direct3D.FeatureLevel.Level_10_0 }, desc, out _device, out _swapChain);
// Ignore all windows events
SharpDX.DXGI.Factory factory = _swapChain.GetParent<SharpDX.DXGI.Factory>();
factory.MakeWindowAssociation(this.Handle, WindowAssociationFlags.IgnoreAll);//改这个换渲染的
Factory2D = new SharpDX.Direct2D1.Factory();
_backBuffer = Texture2D.FromSwapChain<Texture2D>(_swapChain, 0);
_backBufferView = new RenderTargetView(_device, _backBuffer);
_d3DDeviceContext = _device.ImmediateContext;
_d3DDeviceContext.OutputMerger.SetRenderTargets(_backBufferView);
_d3DDeviceContext.ClearRenderTargetView(_backBufferView, ColorToRaw4(SharpDX.Color.Gray));
using (var surface = BackBuffer.QueryInterface<Surface>())//texture2d
using (var dxgiDevice = _device.QueryInterface<dxgi.Device>())//d3d11
{
//这里设置了RenderTarget2D的工厂,绘图表面为FORM1(前边有配置)
RenderTarget2D = new RenderTarget(Factory2D, surface, new RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));
RenderTarget2D2 = new RenderTarget(Factory2D, surface, new RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));
d2dDevice = new d2.Device(dxgiDevice); // initialize the D2D device
d2dContext = new d2.DeviceContext(d2dDevice, d2.DeviceContextOptions.EnableMultithreadedOptimizations);// initialize the DeviceContext - it will be the D2D render target and will allow all rendering operations
// d2dContext = new d2.DeviceContext(surface);
var d2PixelFormat = new d2.PixelFormat(dxgi.Format.R8G8B8A8_UNorm, d2.AlphaMode.Premultiplied);
var d2dBitmapProps = new d2.BitmapProperties1(d2PixelFormat, 96, 96, d2.BitmapOptions.Target | d2.BitmapOptions.CannotDraw);
d2dContext.Target = new d2.Bitmap1(d2dContext, surface, d2dBitmapProps);
sen();
} here
thanks
I have some code that uses System.Windows.Forms.DataVisualization.Charting; to generate a chart and create a bitmap image
private Bitmap GetTargetGradingImage(int sessionsTrained, int target, int height, int width)
{
const string TargetSeries = "TargetSeries";
var chart = new Chart
{
Height = height,
Width = width
};
chart.ChartAreas.Add(new ChartArea()
{
Name = "ChartArea1"
});
chart.Series.Clear();
chart.Series.Add(new Series()
{
Name = TargetSeries,
IsVisibleInLegend = true,
ChartType = SeriesChartType.Column,
Color = Color.Green
});
chart.Series[TargetSeries].ChartArea = chart.ChartAreas[0].Name;
string[] XPointMember = new string[2];
int[] YPointMember = new int[2];
XPointMember[0] = "Sessions";
YPointMember[0] = sessionsTrained;
XPointMember[1] = "Target";
YPointMember[1] = target;
chart.Series[TargetSeries].Points.DataBindXY(XPointMember, YPointMember);
chart.Invalidate();
var bitmap = new Bitmap(chart.Size.Width, chart.Size.Height, PixelFormat.Format32bppArgb);
chart.DrawToBitmap(bitmap, chart.Bounds);
//chart.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Size.Width, bitmap.Size.Height));
return bitmap;
}
This works fine on my dev system but not when published to an Azure website. The images are blank.
The images are being used for inclusion in html emails.
Any ideas?
Cracked it.
Didn't need the chart.DrawToBitmap bit at all
This works
using (var chartImage = new MemoryStream())
{
chart.SaveImage(chartImage, ChartImageFormat.Png);
targetBuf = Convert.ToBase64String(chartImage.ToArray());
}
This gives me a Base64 encoded string that I can use in an img tag
I'm trying to write simple DirectX 11 app using C# and SharpDX. I wanted to test basic drawing but when i run the program, i will get entire form filled with red color. When i change the vertices its drawing unwanted shapes. Clear color works.
I tried changing some properties but nothing helps.
Here is the code:
private Vector3[] Vertices = new Vector3[]
{
new Vector3(-0.5f, 0.5f, 0), new Vector3(0.5f, 0.5f, 0), new Vector3(0, -0.5f, 0)
};
private D3D11.Buffer VertexBuffer;
public Game()
{
RenderForm = new RenderForm("Test Form");
RenderForm.ClientSize = new Size(Width, Height);
RenderForm.AllowUserResizing = false;
InitDeviceResources();
InitShaders();
InitVertexBuffer();
}
public void Run()
{
RenderLoop.Run(RenderForm, RenderCallback);
}
private void InitVertexBuffer()
{
VertexBuffer = D3D11.Buffer.Create<Vector3>(Device, BindFlags.VertexBuffer, Vertices);
}
private void InitShaders()
{
using (ShaderBytecode vertexShaderBytecode = ShaderBytecode.CompileFromFile("vertexShader.hlsl", "main", "vs_4_0", ShaderFlags.Debug))
{
InputSignature = ShaderSignature.GetInputSignature(vertexShaderBytecode);
VertexShader = new VertexShader(Device, vertexShaderBytecode);
}
using (ShaderBytecode pixelShaderBytecode = ShaderBytecode.CompileFromFile("pixelShader.hlsl", "main", "ps_4_0", ShaderFlags.Debug))
{
PixelShader = new PixelShader(Device, pixelShaderBytecode);
}
Context.VertexShader.Set(VertexShader);
Context.PixelShader.Set(PixelShader);
Context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
InputLayout = new InputLayout(Device, InputSignature, InputElements);
Context.InputAssembler.InputLayout = InputLayout;
}
private void InitDeviceResources()
{
ModeDescription backBufferDesc = new ModeDescription(Width, Height, new Rational(60, 1), Format.B8G8R8A8_UNorm);
SwapChainDescription swapChainDesc = new SwapChainDescription()
{
BufferCount = 1,
IsWindowed = true,
OutputHandle = RenderForm.Handle,
ModeDescription = backBufferDesc,
SampleDescription = new SampleDescription(1, 0),
Usage = Usage.RenderTargetOutput
};
D3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out Device, out SwapChain);
Context = Device.ImmediateContext;
Viewport = new Viewport(0, 0, Width, Height);
Context.Rasterizer.SetViewport(Viewport);
using (Texture2D backBuffer = SwapChain.GetBackBuffer<Texture2D>(0))
{
RenderTarget = new RenderTargetView(Device, backBuffer);
}
}
private void RenderCallback()
{
Draw();
}
private void Draw()
{
Context.OutputMerger.SetRenderTargets(RenderTarget);
Context.ClearRenderTargetView(RenderTarget, new Color4(0, 0, 1, 1));
Context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(VertexBuffer, Utilities.SizeOf<Vector3>(), 0));
Context.Draw(Vertices.Count(), 0);
SwapChain.Present(1, PresentFlags.None);
}
I finally solved this. There must be Format.R32G32B32_Float instead of Format.R32G32B32A32_Float
I try to capture desktop screenshot using SharpDX. My application is able to capture screenshot but without labels in Windows Explorer.
I tryed 2 solutions but without change. I tried find in documentation any information, but without change.
Here is mi code:
public void SCR()
{
uint numAdapter = 0; // # of graphics card adapter
uint numOutput = 0; // # of output device (i.e. monitor)
// create device and factory
var device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware);
var factory = new Factory1();
// creating CPU-accessible texture resource
var texdes = new SharpDX.Direct3D11.Texture2DDescription
{
CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.Read,
BindFlags = SharpDX.Direct3D11.BindFlags.None,
Format = Format.B8G8R8A8_UNorm,
Height = factory.Adapters1[numAdapter].Outputs[numOutput].Description.DesktopBounds.Height,
Width = factory.Adapters1[numAdapter].Outputs[numOutput].Description.DesktopBounds.Width,
OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None,
MipLevels = 1,
ArraySize = 1
};
texdes.SampleDescription.Count = 1;
texdes.SampleDescription.Quality = 0;
texdes.Usage = SharpDX.Direct3D11.ResourceUsage.Staging;
var screenTexture = new SharpDX.Direct3D11.Texture2D(device, texdes);
// duplicate output stuff
var output = new Output1(factory.Adapters1[numAdapter].Outputs[numOutput].NativePointer);
var duplicatedOutput = output.DuplicateOutput(device);
SharpDX.DXGI.Resource screenResource = null;
SharpDX.DataStream dataStream;
Surface screenSurface;
var i = 0;
var miliseconds = 2500000;
while (true)
{
i++;
// try to get duplicated frame within given time
try
{
SharpDX.DXGI.OutputDuplicateFrameInformation duplicateFrameInformation;
duplicatedOutput.AcquireNextFrame(miliseconds, out duplicateFrameInformation, out screenResource);
}
catch (SharpDX.SharpDXException e)
{
if (e.ResultCode.Code == SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code)
{
// this has not been a successful capture
// thanks #Randy
// keep retrying
continue;
}
else
{
throw e;
}
}
device.ImmediateContext.CopyResource(screenResource.QueryInterface<SharpDX.Direct3D11.Resource>(), screenTexture);
screenSurface = screenTexture.QueryInterface<Surface>();
// screenSurface.Map(SharpDX.DXGI.MapFlags.Read, out dataStream);
int width = output.Description.DesktopBounds.Width;
int height = output.Description.DesktopBounds.Height;
var boundsRect = new System.Drawing.Rectangle(0, 0, width, height);
var mapSource = device.ImmediateContext.MapSubresource(screenTexture, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.None);
using (var bitmap = new System.Drawing.Bitmap(width, height, PixelFormat.Format32bppArgb))
{
// Copy pixels from screen capture Texture to GDI bitmap
var bitmapData = bitmap.LockBits(boundsRect, ImageLockMode.WriteOnly, bitmap.PixelFormat);
var sourcePtr = mapSource.DataPointer;
var destinationPtr = bitmapData.Scan0;
for (int y = 0; y < height; y++)
{
// Copy a single line
Utilities.CopyMemory(destinationPtr, sourcePtr, width * 4);
// Advance pointers
sourcePtr = IntPtr.Add(sourcePtr, mapSource.RowPitch);
destinationPtr = IntPtr.Add(destinationPtr, bitmapData.Stride);
}
// Release source and dest locks
bitmap.UnlockBits(bitmapData);
device.ImmediateContext.UnmapSubresource(screenTexture, 0);
bitmap.Save(string.Format(#"d:\scr\{0}.png", i));
}
// var image = FromByte(ToByte(dataStream));
//var image = getImageFromDXStream(1920, 1200, dataStream);
//image.Save(string.Format(#"d:\scr\{0}.png", i));
// dataStream.Close();
//screenSurface.Unmap();
screenSurface.Dispose();
screenResource.Dispose();
duplicatedOutput.ReleaseFrame();
}
}
After few hours of research and googling i found working solution:
From:
PixelFormat.Format32bppArgb
To:
PixelFormat.Format32bppRgb
I'm trying to save a user-generated Texture2D to disk, but it looks like the standard ways of accomplishing this aren't available when targeting DirectX11.1 / Win8.1 / Metro. ToStream/FromStream are absent, and the DX11 methods for writing a texture to disk are absent as well.
Any ideas or suggestions?
Here's the general solution I ended up with. Getting a DataStream through mapping a texture resource is what got me on the right track.
General flow is create a texture with CpuAccessFlags.Read, then CopyResource from the source texture to the new texture, then read data from the new texture into a WIC Bitmap.
public static class Texture2DExtensions
{
public static void Save(this Texture2D texture, IRandomAccessStream stream, DeviceManager deviceManager)
{
var textureCopy = new Texture2D(deviceManager.DeviceDirect3D, new Texture2DDescription
{
Width = (int)texture.Description.Width,
Height = (int)texture.Description.Height,
MipLevels = 1,
ArraySize = 1,
Format = texture.Description.Format,
Usage = ResourceUsage.Staging,
SampleDescription = new SampleDescription(1, 0),
BindFlags = BindFlags.None,
CpuAccessFlags = CpuAccessFlags.Read,
OptionFlags = ResourceOptionFlags.None
});
deviceManager.ContextDirect3D.CopyResource(texture, textureCopy);
DataStream dataStream;
var dataBox = deviceManager.ContextDirect3D.MapSubresource(
textureCopy,
0,
0,
MapMode.Read,
SharpDX.Direct3D11.MapFlags.None,
out dataStream);
var dataRectangle = new DataRectangle
{
DataPointer = dataStream.DataPointer,
Pitch = dataBox.RowPitch
};
var bitmap = new Bitmap(
deviceManager.WICFactory,
textureCopy.Description.Width,
textureCopy.Description.Height,
PixelFormat.Format32bppBGRA,
dataRectangle);
using (var s = stream.AsStream())
{
s.Position = 0;
using (var bitmapEncoder = new PngBitmapEncoder(deviceManager.WICFactory, s))
{
using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder))
{
bitmapFrameEncode.Initialize();
bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height);
var pixelFormat = PixelFormat.FormatDontCare;
bitmapFrameEncode.SetPixelFormat(ref pixelFormat);
bitmapFrameEncode.WriteSource(bitmap);
bitmapFrameEncode.Commit();
bitmapEncoder.Commit();
}
}
}
deviceManager.ContextDirect3D.UnmapSubresource(textureCopy, 0);
textureCopy.Dispose();
bitmap.Dispose();
}
}