C++ - Double Buffering in Direct2D - Stack Overflow
C++ - Double Buffering in Direct2D - Stack Overflow
Asked 7 years, 1 month ago Modified 7 years, 1 month ago Viewed 2k times
I'm very new to Direct2D programming and have been following a tutorial. I've adapted the example
given in the tutorial to a slightly more complicated program that bounces a ball off the boundaries of the
0 window.
#include "Graphics.h"
Graphics* graphics;
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
// Exit handler
if (uMsg == WM_DESTROY)
{
PostQuitMessage(0);
return 0;
}
// Set up window
windowClass.cbSize = sizeof(WNDCLASSEX);
windowClass.hbrBackground = (HBRUSH)COLOR_WINDOW;
windowClass.hInstance = hInstance;
windowClass.lpfnWndProc = WindowProc;
windowClass.lpszClassName = "MainWindow";
windowClass.style = CS_HREDRAW | CS_VREDRAW;
RegisterClassEx(&windowClass);
if (!windowHandle)
return -1;
if (!graphics->Init(windowHandle))
{
delete graphics;
return -1;
}
ShowWindow(windowHandle, nCmdShow);
// Message loop
MSG message;
message.message = WM_NULL;
//xSpeed += 0.6f;
x += xSpeed;
ySpeed += 0.2f;
y += ySpeed;
// Redraw ball
graphics->beginDraw();
graphics->endDraw();
}
}
delete graphics;
return 0;
}
#pragma once
#include <Windows.h>
#include <d2d1.h>
class Graphics
{
ID2D1Factory* factory;
ID2D1HwndRenderTarget* renderTarget;
ID2D1SolidColorBrush* brush;
public:
Graphics();
~Graphics();
#include "Graphics.h"
Graphics::Graphics()
{
factory = NULL;
renderTarget = NULL;
brush = NULL;
}
Graphics::~Graphics()
{
if (factory)
factory->Release();
if (renderTarget)
renderTarget->Release();
if (brush)
brush->Release();
}
CHECKRES;
RECT rect;
GetClientRect(windowHandle, &rect);
res = factory->CreateHwndRenderTarget(
D2D1::RenderTargetProperties(),
D2D1::HwndRenderTargetProperties(windowHandle, D2D1::SizeU(rect.right,
rect.bottom)),
&renderTarget
);
CHECKRES;
CHECKRES;
return true;
}
While this program does work fine, there is some minor tearing on the ball's bounce. I have seen this
question which lead me to this MSDN article. Despite reading the article, I do still not fully understand
how to implement double buffering, to hopefully reduce tearing. Can someone provide a concise
example and explanation of the ID2D1RenderTarget::CreateCompatibleRenderTarget , as this high level
Windows programming is quite different from what I'm used to?
Share Improve this question Follow asked Feb 19, 2017 at 19:56
carefulnow1
831 12 30
Check article here. ID2D1HwndRenderTarget objects are double buffered by nature and drawing is done
to the offscreen buffer first and when drawing ends it will be blitted to the screen.
3
Share Improve this answer Follow edited Feb 19, 2017 at 20:10 answered Feb 19, 2017 at 20:02
user4581301 Janne
33.4k 7 34 56 1,705 15 22