Why should I do manual double buffering? - c#

I am working on a game in C# (either 2.0 or 3.5 havn't decided yet). The game will be played on a map with a hexagonal grid. I appreciate that the UI for this map should use double buffering (lots of layers, so slow drawing). I know that I can enable double buffering through a style, or create my own buffer and handle it myself. Most recomendations I find on the web are to handle it yourself. I am wondering why? Obviously this allows me to avoid the assumptions that are inherent in the control double buffering, but I do not know what those assumptions are.
Again, I am not looking for code to explain how to double buffer my control, but rather why I would build this myself instead of using the double buffering style and allowing the CLR/Control class to handle it?

From MS:
For graphically intensive applications
such as animation, you can sometimes
improve performance by using a
dedicated BufferedGraphicsContext
instead of the BufferedGraphicsContext
provided by the
BufferedGraphicsManager. This enables
you to create and manage graphics
buffers individually, without
incurring the performance overhead of
managing all the other buffered
graphics associated with your
application, though the memory
consumed by the application will be
greater.
EDIT: I also found this article from Bob Powell which may be helpful:
Manual double buffering can be useful
if you don't want the system so make
assumptions for you such as whether
the background is opaque or
transparent or perhaps if you want to
create a more complex buffering
system. There are a few simple rules
that you need to follow to get manual
double buffering right.
First, don’t create a new back-buffer
every draw cycle. Only create or
destroy the bitmap when the window's
client size changes. Second, only
create a bitmap of the size you need.
Clearing pixels takes time and so if
there are more pixels than you need,
you're just wasting processor cycles.
Lastly, use the simplest draw method
to copy the bitmap to the screen.
DrawImageUnscaled is the way to go
here.
EDIT: Another reason is that you may want the application to control buffering, not the controls themselves.
Source: Pro .NET 2.0 Windows Forms and custom controls in C#.

In WFA, double-buffering slows performance without completely eliminating flicker in custom graphics areas. For built-in GUI elements, like if you create a game built out of ImageButtons and Labels, the built-in double-buffered mode is great at hiding the redrawing of the control tree. However, there are a couple major problems with using it for a custom drawing area:
The draw buffer created when you just set up the application to draw double-buffered is used to draw the whole window and all child controls, not just your custom drawing area, so you add the overhead of redrawing every GUI element on the back buffer before page-flipping.
If anything invalidates the control, the Paint method is called. You may not be finished drawing when that happens and so you'll get an incomplete image shown to the user (not good in real-time graphics).
By keeping the basic window GUI single-buffered, but creating an area on which you control the buffering, both of these problems are minimized.
Double-buffering methods can be as simple as creating a Bitmap object as a back-buffer and drawing it to the draw area when you're good and ready, or setting up a seperate BufferedGraphicsContext to manage buffering of your custom draw area.

Related

Hardware Acceleration in MFC

I am currently developing a software that involves real-time rendering of performance metrics in graph and chart forms. I need to acquire data, process data and render an image as fast as possible. My backend is in C++, and I am at a point where I have to make a choice regarding the front end.
Given my backend is in C++, I was inclined to go with MFC. The other alternative is to go with WPF C# for frontend and interop with my C++ backend. I read recently that WPF provides for hardware acceleration, this should help me achieve a high frame rate. Does MFC hardware accelerate its graphics too? Does hardware acceleration even matter?
Given WPF's hardware acceleration, does that make WPF the most efficient alternative for graphics in my case?
WPF provides hardware acceleration using DirectX 9 I believe. However for line graphs the limiting factor is the amount of interface elements. We are creating a program in WPF that displays sEMG data real-time using Telerik charts. These can be configured to use direct2d acceleration under the hood which cranks up the performance a bit if you have a lot of datapoints. It's still jerky though because you cannot control the render thread of WPF.
It kind of depends on the amount of features you need in the graph. If the priority is to have silky smooth real-time display don't go with WPF.
Visual Studio 2010 added classes to MFC to support using Direct2D rendering from MFC programs.
To use Direct2D, you start by calling EnableD2DSupport() in your View's OnCreate (technically, I suppose it doesn't have to be in OnCreate, but that's the usual place). Then you'll receive AFX_WM_DRAW2D messages when the D2D display context needs updating, so you'll normally want to add a handler for that, and respond to it by rendering your content as needed.
Another possibility to consider would be to use an existing control to draw your graphs. There are quite a few around, including some that are free with quite liberal licensing. Just for example, CodeProject has a number of Charting controls, a few of which use D2D for their drawing, and quite a few more that don't.
Honestly, I'd be a little surprised at charts having information being updated fast enough for drawing speed to make a huge difference as a rule though. In most typical cases, the real limit will be the user's ability to comprehend what you're drawing. A user simply can't watch 100 different graphs each being updated at (say) 60 Hz, and have much hope of deriving much real meaning from most of them. In most cases, the real challenge isn't to draw more data faster, but to provide better ways for the user to focus on the few things they can follow at a time, and (for example) draw their attention to important changes when needed.

EndDraw() takes 80 % of working time in Direct2D

I face one critical Performance problem in my Direct2D application. I make use of Direct2D to draw my graph using PathGeometry to get better performance and to achieve the clean rendering in Windows 8.1.
While creating the DeviceResources, i create the PathGeometry using the Factory interface. Then i set the Graph points to draw my graph in the output surface. Finally rendered ImageSource will be used as the source for my Image element in the XAML.
I just followed the below sample link to achieve my scenario.
http://code.msdn.microsoft.com/windowsapps/XAML-SurfaceImageSource-58f7e4d5
The above sample helped me a lot to get the ImageSource output from the Direct2D and finally used across the XAML/C# app.
Lets come to my problem. I use more than 24 graphs in the single Page of my Windows Store application. This graph allows the user to manipulate in Left and Right position and also allows to scale to the particular zoom level.
Hence whenever user tries to manipulate the graph , i just set the Translation and Scaling matrix to the TransformedPathGeometry instead of creating the new one for each and every time.
ID2D1TransformedGeometry *m_pTransformedGeometry;
pFactory->CreateTransformedGeometry(graphgeometry, combinedMatrix, &m_pTransformedGeometry);
Finally i draw the TransformedGeometry using the DrawGeometry method.
I checked my application using the Performance analysis tool in the VisualStudio2013. I could see that in the particular peek level, It takes more than 80% of running time to call the m_d2deviceContext->EndDraw() method. I attached the below screen shot to get more idea in this performance output.
Is there any way to increase this performance considerably ?
Could you please anyone help me in this ?
Regards,
David C
THere is a difference between slow performance and time spend.
If your draw method does more work than other parts, can mean that this method is slow but it also can mean that your other parts don't need a lot of cpu.
88.2% tells you only that you spend more time drawing that stuff than doing other stuff.
Use an timer to determine if your draw is slow.
"i just set the Translation and Scaling matrix to the
TransformedPathGeometry instead of creating the new one for each and
every time."
I hope you use world transform? Else you overwrite the pointer without releasing it before, providing a memory leak. You cannot change the matrix of a geometry directly, you have to recreate it each time, or if you can, you apply the transform to the entire world.

C# PictureBox control flickering / performance issues

I am currently working in Windows Form Apps and am making what will essentially be a map editor for a game. The way i have gone about this is by having a central TabControl where each TabPage contains a custom PictureBox control and all the other UI controls are around this central TabControl. The PictureBox uses its Paint event to draw everything that is placed on the map, and therefore draws multiple images of many sizes, rotations and scales etc to the single PictureBox. This has all gone well so far. The TabPage is essentially used as a view window for the PictureBox and is of size (1280x720).
The problem is with the scale to which the maps are being produced. The avg (and also maximum) map size on screen is around 19200x10800px and can be made up of hundreds of items at any one point. When drawing just a backdrop image of size 19200x10800px the PictureBox starts to flicker when it redraws and makes the program unusable. As the map is so big you are able to pan around them and this is where the flickering really shows. Also i do not want to use a 19200x10800px image source if possible for the sake of file sizes and the scaled image quality isn't an issue at all.
I have done heaps of reading on why this might be and feel like I have tried everything up until this point. So far ive tried:
Having the background image only 1920x1080 and scaling it up by 10x
Starting with a 1920x1080 image, programatically resizing it and drawing this image
Slicing the background into multiple segments (i tried many different amounts) and drawing only the ones that the view window can see (tried this for both a small(1080p) and large(10800p) images)
Using graphics clipping so that only the things on screen would be drawn
Used Double Buffering on both the picturebox and the form that the picturebox is on
Converting the image at initialisation to an "optimised bitmap" with faster formatting and then drawing the bitmap
I've probably tried a couple other things along with minor optimisations but its taken me so long ive forgotten the rest. From what i've read its most likely something to do with the control redrawing too slowly for some sort of performance reason or a limitation with picturebox's, however exactly what is going on i cannot tell due to lack of experience with form apps controls.
Currently to draw the background in the Paint event i have either:
g.DrawImage(image, new Rectangle(0, 0, (int)(image.Size.Width * levelScale), (int)(image.Size.Height * levelScale)));
or
g.ScaleTransform(levelScale, levelScale);
g.DrawImage(image, new Rectangle(0, 0, (int)(image.Size.Width), (int)(image.Size.Height)));
Where g is the Graphics object.
Have I hit the limit of Win form apps capabilities or is there something i may be missing?
Any and all help appreciated,
Thanks in advance.
Just for formality I though id answer my own question just in case anyone else would like to know the outcome.
Based off the overwhelming consensus that winforms was just not made to do the things I was trying to do with it I decided I had to move to some other platform. Suggested to me was WPF, DirectX and OpenGL but after some extensive searching around I found what I think is the optimal solution.
In order to utilise the power of DirectX hardware acceleration MS has made it so that you can embed XNA graphics devices into a winforms application. Essentially you can create custom controls that run in the normal winform style that have access to a much higher caliber of graphics control. In this manner (with a bit of extra work) I have replaced the picturebox I was using with a custom graphics control which handles all of the drawing. This has worked very well, and on the up side i havent had to take too much of a hit to my development time.
For those looking for more info refer to this question which has further links that should help. Once again thanks to all those who gave their advice!
This is a quoted answer from the URL at the bottom. There are code examples at the link at the bottom. Hope this is helpful; not sure if you tried this yet and maybe it'll help you get a little more juice out of the existing picturebox control. As explain in the other answers, it sounds like you will be forced to a more powerful solution in the near future regardless (DirectX/OpenGL or WPF)
** Partial quote from http://social.msdn.microsoft.com/Forums/en-US/68ecd1f6-2eeb-45ce-a881-24c62145ab0e/c-picturebox-problems
"I'd guess the real problem is that it takes too long to redraw the images. GDI+ is pretty slow, it doesn't use any video hardware acceleration. To speed it up, be sure to avoid rescaling the drawing and to use the Format32PArgb format. It is about 10 times faster than any other format. Load the images into a Bitmap with the right format first."
If you have a LOT of items (Maybe realized as controls), forget about the standard event mechanism of Windows Forms. Some time ago, i've written a logic gate editor/simulator which supported lots of thousands of gates in the editor and was really fast. There, I've used the canvas and draw the gates as custom "images" instead of putting them as controls. You'll have to write a custom GetUnderlyingGate function which resolves the current gate / tile (Is your editor a tilemap editor?) from a coordinate array. Also, there were some visible area optimizations.
Maybe, when i'm back home, I'll upload some sourcecode and notify you.

Best way to constantly draw large numbers of bitmaps in WPF?

I am stumped by this very simple problem. I am making a tile-based game engine and need to be able to allow a user to edit the map using a WPF User Interface. Naively, I had assumed that I could simply constantly update a good old fashioned "buffered" System.Drawing.Graphics.Bitmap using Graphics.FromImage. I would draw onto the bitmap the tiles that make up the map, and then blit the buffer Bitmap to the screen. However, from my thorough research I now believe that it isn't that easy at all.
Rather than bore you with what I've found out so far (that either doesn't work, or is incredibly slow), may I ask very simply, what is the best way for continuously drawing large numbers of bitmaps efficiently via a WPF UI?
I will accept such suggestions as "go back to Windows Forms". If that's the case, then I am going to be very dissapointed with WPF!
The WriteableBitmap class is a high-performance WPF-compatible bitmap that allows direct access to its bits. This MSDN documentation page contains a fairly thorough example of using it.
Freezable can make a big difference to performance when dealing with Bitmaps, you can then also load the buffer using a background thread to stop the UI locking up.
This tutorial covers the basics

How to eliminate tearing from animation?

I'm running an animation in a WinForms app at 18.66666... frames per second (it's synced with music at 140 BPM, which is why the frame rate is weird). Each cel of the animation is pre-calculated, and the animation is driven by a high-resolution multimedia timer. The animation itself is smooth, but I am seeing a significant amount of "tearing", or artifacts that result from cels being caught partway through a screen refresh.
When I take the set of cels rendered by my program and write them out to an AVI file, and then play the AVI file in Windows Media Player, I do not see any tearing at all. I assume that WMP plays the file smoothly because it uses DirectX (or something else) and is able to synchronize the rendering with the screen's refresh activity. It's not changing the frame rate, as the animation stays in sync with the audio.
Is this why WMP is able to render the animation without tearing, or am I missing something? Is there any way I can use DirectX (or something else) in order to enable my program to be aware of where the current scan line is, and if so, is there any way I can use that information to eliminate tearing without actually using DirectX for displaying the cels? Or do I have to fully use DirectX for rendering in order to deal with this problem?
Update: forgot a detail. My app renders each cell onto a PictureBox using Graphics.DrawImage. Is this significantly slower than using BitBlt, such that I might eliminate at least some of the tearing by using BitBlt?
Update 2: the effect I'm seeing is definitely not flicker (which is different from tearing). My panel is double-buffered, sets the control styles for AllPaintingInWmPaint, UserPaint, OptimizedDoubleBuffer etc., overrides onPaintBackGround and so on. All these are necessary to eliminate flicker, but the tearing problem remains. It is especially pronounced when the animation has very fast-moving objects or objects that change from light to dark very quickly. When objects are slow-moving and don't change color rapidly, the tearing effect is much less noticeable (because consecutive cels are always very similar to each other).
Tearing occurs when your image update is not in sync with the refresh rate of the monitor. The monitor shows part of the previous image, part of the new image. When the objects in the image move fast, the effect is quite noticeable.
It isn't fixable in Windows Forms, you can't get to the video adapter's v-sync signal. You can in a DirectX app.
I tried the double buffering idea on the project I'm working on at the moment, but I didn't get very good results with it. In the end, I created the following:
A System.Drawing.Bitmap for my offscreen buffer. Decode the animation into this bitmap.
A UserControl the same size as the image in (1) and where the OnPaintBackground method was empty (no drawing, no call to base class) and the OnPaint did a Graphics.DrawImage to copy the offscreen image to the screen.
Now, you've got a weird animation rate so the tearing is almost certainly to do with a mismatch between screen update rate and screen refresh rate. You are updating the screen midway through the screen's refresh so the screen is drawing the old frame at the top of the screen and the new frame at the bottom of the screen. If you can synchronise the frame rate with the display refresh rate, the tearing should disappear.
You would better to use directx (or opengl) for such tasks. But if you want to use only winforms use DoubleBuffered property.
Double buffer it.
You can enable double buffering using windows styles or, whats probably easier, is to draw to a picture from offscreen and then swap them.
If this doesnt work then the best thing to do is bitblit and double buffer.
Essentially its the same.
Have a reference to two bitmaps, one is the screen, the other is the buffer.
You draw to the buffer first, then blit that entire thing to the screen.
This way you only ever write live data to the buffer. The sceen simply shows something you made earlier (blue peter style)
Tearing is an artifact from a frame being drawn on top of another. The only safe ways of avoiding it is to a) wait from vsync or b) draw behind the beam (this is rather tricky). Double buffer alone doesn't guarantee against tearing since you can have double buffer but still draw having the vsync off. Some cards might also have vsync wait option "forced off". You need to check the documentation regarding vsync and how to check where it is. This is the only safe way to do it. Also, keep in mind that this will lock your framerate.

Categories

Resources