LHTP offers access to numerous third party web pages and content which is available over the Internet. LHTP exercises no control over this content, web pages or sites. You agree that it is your responsibility to review and evaluate any such content, and that any and all risk associated with the use of, or reliance on, such content rests with you. Furthermore, you agree that LHTP shall not be responsible or liable, either directly or indirectly, in any way for any loss or damage of any kind incurred as a result of, or in connection with your use of, or reliance on, any such content.
TITLE :
double buffered graphics using directdraw. LINK :
http://www.codeproject.com/KB/directx/dxsurfacemgr.aspxNEXT :
NEXT INDEXcodeproject: double buffered graphics using directdraw. free source code and programming help var gajshost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3cscript src='" + gajshost + "google-analytics.com/ga.js' type='text/javascript'%3e%3c/script%3e"));if (_gat) { var pagetracker = _gat._gettracker("ua-1735123-1");pagetracker._setdomainname("www.codeproject.com");pagetracker._setsessiontimeout("1200"); // 20 minspagetracker._initdata();pagetracker._trackpageview();}////////6,021,153 members and growing! (20,309 online)email password function join(){document.location.href='/script/membership/modify.aspx';return false;}document.write('');remember me? lost your password? document.write(unescape("%3ca%20href%3d%22http%3a%2f%2fwww.codeproject.com%2fredir.aspx%3fadid%3d9649%26way%3dban%22%20target%3d%22_blank%22%20rel%3d%22nofollow%22%3e%3cimg%20src%3d%22http%3a%2f%2fwww.codeproject.com%2fscript%2fadm%2fserveimg.aspx%3ffile%3d%252fscript%252fadm%252fimages%252fscaleout_banner_0309_codeproject2.gif%26c%3dfalse%26adid%3d9649%22%20alt%3d%22%22%20border%3d%220%22%20width%3d%22728%22%20height%3d%2290%22%3e%3c%2fa%3e"));homearticleslatestsearchmost popularbeginner articlestopic listsubmit an articleupdate an articlearticle competitionmessage boardsasp.netatl / wtl / stlc / c++ / mfcmanaged c++/clic#comhardware & deviceslinq and .net 3.5.net frameworksystem adminsilverlightgeneral databasevisual basicweb developmentwpf / wcf / wfxml / xslgeneral it issuessite bugs / suggestionsthe soapbox 2.0all message boards...job boardlatestsearchpost a jobfaq and pricingcataloglatestsearchpost a catalog itemfaq and pricinghelp!what is 'the code project'?general faqpost a questionsite directoryabout usloungemultimedia »directx »directdraw intermediate double buffered graphics using directdrawby gertruud lawrence this article explains how my class cdxsurfacemgr can be used to facilitate double buffered drawing.vc6nt4, win2k, mfc, directx, vs6, devposted:23 sep 2001views:111,568bookmarked:47 timesannouncementsjava competitionsmart client compfastest server challengemonthly competition chaptersdesktop developmentbutton controlsclipboardcombo & list boxesdialogs and windowsdesktop gadgetsdocument / viewedit controlsfiles and foldersgrid & data controlslist controlsmenusmiscellaneousprintingprogress controlsselection controlsshell and ie programmingsmart clientsplitter windowsstatic & panel controlsstatus bartabs & property pagestoolbars & docking windowstree controlsweb developmentajax and atlasapplications & toolsaspasp.netasp.net controlsatl servercachingcharts, graphs and imagesclient side scriptingcustom controlshtml / cssisapisite & server managementsession statesilverlighttrace and logsuser controlsvalidationview statewap / wmlweb securityweb servicesenterprise systemscontent management servermicrosoft biztalk servermicrosoft exchangeoffice developmentsharepoint servermultimediaaudio and videodirectxgdigdi+general graphicsopengldatabasedatabasesql reporting servicesplatforms, frameworks & librariesatlmfcstlwtlcom / com+.net frameworkwin32/64 sdk & osvista apivista securitycross platformgame developmentmobile developmentwindows cardspacewindows communication foundationwindows presentation foundationwindows workflow foundationlibrarieswindows powershelllinqlanguagesc / c++ languagec++ / clic#msilvbscriptvb.netvb6 interopother .net languagesxmljavageneral programmingalgorithms & recipesbugs & workaroundscollectionscryptography & securitydate and timedlls & assembliesexception handlinglocalisationmacros and add-insprogramming tipsstring handlinginternet / networkthreads, processes & ipcwinhelp / htmlhelpgraphics / designexpressionusabilitydevelopment lifecycledebug tipsdesign and architectureinstallationwork issuestesting and qacode generationgeneral readingbook chaptersbook reviewshardware reviewsinterviewsscrapbookhardware & systemthird party productsproduct showcasesolution centerservicesjob boardproduct catalogfree magazinesfeature zonesproduct showcaseibm developerworkswhitepapers / webcasts.net bug trackingasp.net web hostingdocument.write(unescape("%3ca%20href%3d%22http%3a%2f%2fwww.codeproject.com%2fredir.aspx%3fadid%3d9620%26way%3dban%22%20target%3d%22_blank%22%20rel%3d%22nofollow%22%3e%3cimg%20src%3d%22http%3a%2f%2fwww.codeproject.com%2fscript%2fadm%2fserveimg.aspx%3ffile%3d%252fscript%252fadm%252fimages%252fjob_board_150x80_v2.gif%26c%3dfalse%26adid%3d9620%22%20alt%3d%22%22%20border%3d%220%22%20width%3d%22150%22%20height%3d%2280%22%3e%3c%2fa%3e"));search articlesmessagesjobssearch catalog advanced searchsitemap print report #atd {position: absolute;top: -90px;left: -5000px;z-index: 200;display: none;white-space:nowrap;background-color:white;padding:10px;border: solid 1px #999;}sharevar sociallinks = new social();sociallinks.addtomethod=1;sociallinks.horizontal=false;sociallinks.showname=true;sociallinks.drawlinks("sociallinks", document.location.href, escape(document.title), 100, 0, "smalltext bold", "addto");sociallinks.setupmenu(); discuss email 17 votes for this article.popularity: 5.46rating: 4.43 out of 5 12345download source files - 4 kbdownload demo project - 45 kbintroductionthis article explains how my class cdxsurfacemgr can be used to facilitate double buffered drawing/graphics.double buffered drawingnormally when drawing using the gdi you do all your painting straight into the hdc that's provided by either beginpaint or a cdc (if you are usingmfc). iif you draw a line it immediately appears on the surface of the window you are drawing on. if you draw a lot of graphic items the screen is updated with each item and this can result in flicker or stuttering as the surface is filled with the drawing. double bufferingcan be used to create smooth updates, you build a "frame" of graphics in a non visible place first then copy the whole thing onto the main windows surface.there a lots of ways to implement double buffering, one way is to create acompatible hdcin memory somewhere and draw into that then blit (copy) that memory into the visible windows hdc. my approach uses a subset of directx called directdrawwhich can be used to draw 2d graphics. cdxsurfacemgr is written using the directdraw interfaces supplied in vc6 (ddraw.h/lib) and should work on95/98/me/2k/xp and nt 4.0 (sp3 - i think).using cdxsurfacemgrcreate an instance of cdxsurfacemgr#include "dxsurfacemgr.h"......cdxsurfacemanager_nbp dxmgr_;initialise the instance like soint cmfcdxview::oncreate(lpcreatestruct lpcreatestruct){ if (cview::oncreate(lpcreatestruct) == -1) return -1; // initialise cdxsurfacemgr if(!dxmgr_.initialise(m_hwnd)) return -1; return 0;}this should be done just once, the parameter to the initialise method is the handle to the window you want to draw on.then when handling the wm_paint message (the place you would normally do the drawing) call the beginpaint methodvoid cmfcdxview::ondraw(cdc* pdc){ cmfcdxdoc* pdoc = getdocument(); assert_valid(pdoc); // todo: add draw code for native data here hdc& hdc = dxmgr_.beginpaint(getsyscolor(color_3dface)); if(null !=hdc) { ....the parameter to beginpaint is a colorref that beginpaint will use to fill the background with. beginpaint returns an hdc that that you can then useto draw things with, either via the standard gdi api; ::setbkmode(hdc,transparent); ::textout(hdc,10,10,"please don't call me reg its not my name", 40);or if you are using mfc; cdc* cdc = cdc::fromhandle(hdc); cdc->setbkmode(transparent); cdc->(10,10, cstring("all aboard brendas iron sledge"));note all the usual gdi rules apply - if you select a brush remember to reselect the old one etc.when you have finished drawing, call the endpaint method like so;dxmgr_.endpaint();this will "flip" your drawing onto the main windows surface. and the drawing will instantaneously appear. what cdxsurfacemgr doescdxsurfacemgr creates a primary surface - one that is visible - and a secondary off screensurface that is the same size as the primary one but invisible. when you call beginpaintan hdc attached to the secondary surface is returned; you do all your drawing into this; then endpaint blits(copies) the whole of the secondary surface onto the primary one and it appears on the window. if you have a capable graphics adapter on your machine then the blit is very very fast, if you don't then the operation is obviously not as fast, but still very functional.demosthere are three demos included one that uses wfc and draws rectangles and ellipses moving up and down the screen, one that uses mfc, and draws a few lines and a bit of text, and one that does exactly the same again but is just a win32 program.licensethis article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. if in doubt please contact the author via the discussion board below.a list of licenses authors might use can be found hereabout the author gertruud lawrencelocation: united kingdomother popular directx articles:directx.capture class librarya .net class library for capturing video and audio to avi files.directshow.netdirectshow for dvd and file playback, capture and sample grabberracex - a 2d racing game using directdrawthis is a 2d racing game that uses a directx wrapper library. the game has single player and multiplayer support.unmanaged vista powerhow to access the power of vista and the dwm without wpf and .netlaser gesture recognitiona quick article on setting up a simple, real-time laser gesture recognition application and using it to control windows media player.document.write(unescape("%3ca%20href%3d%22http%3a%2f%2fwww.codeproject.com%2fredir.aspx%3fadid%3d9485%26way%3dban%22%20target%3d%22_blank%22%20rel%3d%22nofollow%22%3e%3cimg%20src%3d%22http%3a%2f%2fwww.codeproject.com%2fscript%2fadm%2fserveimg.aspx%3ffile%3d%252fscript%252fadm%252fimages%252fintersoft_box_march2009.jpg%26c%3dfalse%26adid%3d9485%22%20alt%3d%22%22%20border%3d%220%22%20width%3d%22300%22%20height%3d%22250%22%3e%3c%2fa%3e")); article top sign up to vote for this articleyour reason for this vote:document.write(unescape("%3ca%20href%3d%22http%3a%2f%2fwww.codeproject.com%2fredir.aspx%3fadid%3d7548%26way%3dban%22%20target%3d%22_blank%22%20rel%3d%22nofollow%22%3e%3cimg%20src%3d%22http%3a%2f%2fwww.codeproject.com%2fscript%2fadm%2fserveimg.aspx%3ffile%3d%252fscript%252fadm%252fimages%252fironspeed.2008.09.09.468%2bx%2b60%2bcode%2bis%2bcheap%2bgenerate%2bweb%2bapps.gif%26c%3dfalse%26adid%3d7548%22%20alt%3d%22%22%20border%3d%220%22%20width%3d%22468%22%20height%3d%2260%22%3e%3c%2fa%3e")); you must sign in to use this message board. faq noise tolerancevery highhighmediumlowvery low search messages layoutexpand all messagesthread viewno javascript (slow)no javascript preview per page102550 msgs 1 to 24 of 24 (total in forum: 24) (refresh)firstprevnextalpha supportnesculcas7:16 10 feb '07 can someone explain to me why the alpha (window transparency) is not working with this code.i realy don't understand anything about directdraw, but my guess is that the blt(...) function is doing something wrong. i'm saying this because if this function is not called then the alpha in the window works, my guess is that the second surface does not have the alpha information that exists in the first surface, and when the blt(...) function is called then the alpha information of the first surface is override by the erroneous alpha information of the second surface.anyone knowns any solution to do it? thanksnunosign in·view thread·permalinkworking samplenesculcas14:40 8 feb '07 some one have a working source code sample doing this but without the big memory leak?(another question, this is realy necessary, the implementation of the double buffered graphics in the directx, the directx do not own a mechanism to handle the flicker? its realy necessary to implement some mechanism to avoid the flickering like we must do in gdi?)thanksnuno sign in·view thread·permalinkre: working samplenesculcas5:49 10 feb '07 i find this interesting and i try to resolve the problem myself. the result is in dxsurfacemgr.h if you find any problem or any improvement please inform.nuno sign in·view thread·permalink1.00/5 (1 vote) re: working samplenesculcas7:17 10 feb '07 ok i already found one problem in this code, it doesn't support window transparency. is there anyone that knows a solution to this? sign in·view thread·permalink2.00/5 (1 vote) uuups, did you ever try...a coder21:23 7 apr '05 ... to resize or - simply move - your example application's window???i never saw an application (even if it was a buggy example) that eated up all the available memory in the system so enormously fast!!!lol.or was it intended to demonstrate even that...?sometimes i ask myself, whether some coders here even basicly test the pieces of code they do...how can this happen?a class, which causes such a behavior is probably the worst case possible. even if it tries to create an offscreen context mechanism to speed up things !!!by the way, why to heck it is necessary to recreate the buffer at such simple tasks like moving a window...? even resizing can be designed smart (i.e. only neccessary, if the window resizes to "bigger" ).whatever, i have written "normal" gdi based offscreen contexts, which akt allot faster than your directx example here for some reasons...oh my! sign in·view thread·permalink2.00/5 (1 vote) re: uuups, did you ever try...x-plorer22:39 7 apr '05 i just discovered, that you obviously tried to correct the leak with one of your posts some times ago...but the downloadeble examples are still the old buggy ones...whatever: even your correction is wrong, because there is another bug in the (corrected) code:hdc& beginpaint(colorref backfillcolor = 0){current_hdc_ = null_hdc;if(!isvalid()) return current_hdc_;tbeginpaint::beginpaint(window_);xrect client; ::getclientrect(window_, &client); clienttoscreen(&client); /*// only create new secondary surface if the window has changed sizeif(current_rect_!=client) {secondarysurface_ = createsecondarysurface(client.width(), client.height());if(null==secondarysurface_.p) return current_hdc_;current_rect_ = client;}*/// your fix:// only create new secondary surface if the window has changed sizeif(current_rect_!=client) {secondarysurface_.release();createsecondarysurface(client.width(), client.height(), &secondarysurface_);if(null==secondarysurface_.p) return current_hdc_;current_rect_ = client;}// fill the secondary surface fillclr(secondarysurface_, backfillcolor);// getdc will _lock_ the surface for ussecondarysurface_->getdc(¤t_hdc_);return current_hdc_;}"secondarysurface" will be null under certain circumstances and so crash the application! i discovered this by very fast resizing the applications window to test your posted fix. there may be allot more such or similar things in your code.cheerz. sign in·view thread·permalink2.00/5 (2 votes) huge memory leaks !cnkklau1:26 10 mar '05 my problem is that even the test app mfcdx is leaking resources and very fast! if i move the window on desktop so that it is partially visible ( a part of it is out of screen max coordonates ) it leaks memory (in task manager the amount of memory allocated increases even by 100mb/s!!)any idea why and how to fix it??? hi..sign in·view thread·permalink2.00/5 (1 vote) pull-down menue updatessagi dror1:33 10 may '04 the pull-down menu updates are very slow.it takes time to invalidete the menu from the client screen,and you can still see it for a half a second or so,after the menu has closed itself.i'm using a 64 bit graphic card.can it be a problem of performance,or somthing else? sign in·view thread·permalinkuse in dialog bases appruination13:54 28 aug '03 i am trying to use this in a mfc dialog based app. i initialized the surface manager in my dialogs initdialog function with if(!dxmgr.initialise(m_hwnd))return -1;but this call crashes inside the dxmgr.initialize it crashes at the indicated spot. if(32 == tst) // 32 bit { std::auto_ptr rgbconverter(new crgb32bit);crashes ->rgbconverter_ = rgbconverter;now, i am realativly new to vc++ so i'm thinking its because i am in a dialog based window and not a view. i have been struggling with doulbe buffering for some time now, so any help is greatly appreciated.a bit of background : my app needs to write multiple bitmaps tothe screen in different locatations, and must stretch them when writing. todd. sign in·view thread·permalink2.00/5 (1 vote) cdxsurfacemgr stops working after screen saver has been activatedjohanps4:22 17 jun '03 i have observed the following behaviour on windows 2000 and windows xp pro (don't know about other os:es):first start the little mfcdx sample program. "lock" the computer - i.e. bring up the screen saver manually or just by waiting. then, after "unlocking" again, the mfcdx program doesn't draw anything inside the surface managed by cdxsurfacemgr.anyone have any clues as to how to get around this; obviously i want "my" program using cdxsurfacemgr to continue working after the screen saver has been active for a while...regards / johan sörensen. sign in·view thread·permalink1.00/5 (1 vote) why here not visual basic?niekass3:06 12 jun '03 why not be vb samples? sign in·view thread·permalinkwhy here not visual basic?niekasss2:40 12 jun '03 why not be vb samples? sign in·view thread·permalinkre: why here not visual basic?twink14:57 9 jan '05 obviously because the author chose to use another language, which in most people opinion is a much better one. taking code that uses a library in vc or vb and tranlating to the other isn't that hard a task i often do it as i only find examples in vb (and i use vc) sign in·view thread·permalinksetdibitstodeviceanonymous23:19 1 apr '02 hi,is it possible to use this function with your class??i want to fill an window with data from an bitmap.thank you steffensign in·view thread·permalinkthanks so muchackka11:11 7 jan '02 i have been looking for this for a while now for a programming project. i was trying to do double buffering using a second hdc but it didn't seem to work. thanks again tom moseshttp://userpages.umbc.edu/~tmoses1 sign in·view thread·permalinktheres a leak in my codegerty13:08 29 sep '01 hi all,i have found a leak in my code, in the method cdxsurfacemgr::createsecondarysurface i create a secondary surface which gets addrefed in createsurface dx call, then once again when i return it via the method to the awaiting smart pointer, the first addref isn't released and the surface gets overwritten and a leak results.fix:bool createsecondarysurface(const int width, const int height, idirectdrawsurface** surface){if(null!=primarysurface_.p){cddsurfacedesc dds(ddsd_caps|ddsd_height|ddsd_width, ddscaps_offscreenplain, width, height);hresult hr = directdraw_->createsurface(&dds,surface, null);if(succeeded(hr)){return true;}}return false;}and the call// only create new secondary surface if the window has changed sizeif(current_rect_!=client) {secondarysurface_.release();createsecondarysurface(client.width(), client.height(), &secondarysurface_);if(null==secondarysurface_.p) return current_hdc_;current_rect_ = client;}i shall be updating the code as soon as i can.sorry for any inconveniencesglsign in·view thread·permalink2.00/5 (2 votes) great code... and a questionmatt ashland16:38 25 sep '01 wow, thanks for the great code just a quick question:is there a way to make the secondary surface always 32-bpp regardless of the primary surface format?if this is possible, what's needed so that beginpaint() from the sample code would return an hdc and a dword* to the raw data? that'd be really slick because you could then use gdi and optimized byte-level manipulations side-by-side.thanks again for the code, and for any help.-mattsign in·view thread·permalink1.00/5 (1 vote) re: great code... and a questiongerty12:41 29 sep '01 hi matt,glad you liked the code.i'm afraid you can't set the mode of the desktop when running in cooperative mode, thats why theres a lot of code to convert colours to the various desktop pixel modes available - although its not really used much (see the colour conversion classes in the header).glsign in·view thread·permalinkre: thanks... and a benchmarkmatt ashland4:26 1 oct '01 thanks gerty.i don't want to change the desktop. just wondering if the secondary surface can be created as 32-bit, and then let directx dither it accordingly when it's rendered to the primary surface. any chance?as for benchmarks, this method performs very similarly to the dib drawing api provided by windows (stretchdibits, etc.) until you do stretching. the directx engine will stretch (high quality... with filtering) with almost no overhead. the dib methods fall apart when you do any sizing.however, i still need to render into a dib, flip to the secondary, then stretch to the primary unless i can figure out how to force the secondary buffer into 32-bit mode. lots of my code is mmx that relies on 32-bit buffer alignment.anybody have any ideas?thanks again.-matt sign in·view thread·permalinkatlres.h missingfriedhelm schuetz5:33 25 sep '01 hi,downloaded and extracted the project. tried to compile, but "atlres.h" isn't there.sign in·view thread·permalink1.00/5 (1 vote) re: atlres.h missingmatt ashland18:09 25 sep '01 check out this reply from a codeguru article. it has the link you'll need.http://www.codeguru.com/mfc/comments/23204.shtmlsign in·view thread·permalink2.00/5 (2 votes) re: atlres.h missinggerty12:44 29 sep '01 hi,the code you tried to build uses wtl 3.1 - the other demos use mfc and straight win32, but they don't do very much -sign in·view thread·permalink1.55/5 (5 votes) interesting...j.g. hattingh3:47 25 sep '01 looks interesting, and i was wondering whether you could tell me what the pros and cons are of using this method...tiasign in·view thread·permalink2.00/5 (1 vote) re: interesting...gerty12:57 29 sep '01 i'm not really aware of any cons - i guess you can still find machines with crapy graphics cards in, which may affect performance - my machine has an awfull ati mach 64 something or other , and i still get reasonable performance, mind you i'm not not doing vast amounts of heavy drawing.i found the actual implementation of the double buffering very easy - just a few lines of code really - certainly easier than the various other methods i have tried - creating memory hdcs and blitting via the software, which i can never get to work first time.performance wise i haven't benchmarked the code, it would be interesting to hear from anyone if this method goes any slower/faster than any other method they have.the thing i liked about it was that its simple, its com based - which i like - and it works across just about every version of windows there is, even _nt4_ (with the right service pack that is!)sign in·view thread·permalink2.43/5 (4 votes) last visit: 1:02 30 mar '09 last update: 1:02 30 mar '09 general news question answer joke rant admin permalink | privacy |terms of uselast updated: 23 sep 2001editor: chris maundercopyright 2001 by gertruud lawrenceeverything elsecopyright © codeproject, 1999-2009 web12 |advertise on the code project ////