Skip to content

Instantly share code, notes, and snippets.

@MSDN-WhiteKnight
Created June 8, 2020 03:49
Show Gist options
  • Save MSDN-WhiteKnight/98bb797d91fbee010dca6236c3949f33 to your computer and use it in GitHub Desktop.
Save MSDN-WhiteKnight/98bb797d91fbee010dca6236c3949f33 to your computer and use it in GitHub Desktop.
Direct3D example
#include <windows.h>
#include <windowsx.h>
#include <stdio.h>
#include <d3d9.h>
#pragma comment (lib, "d3d9.lib")
LPDIRECT3D9 d3d;
LPDIRECT3DDEVICE9 device;
const int W = 1200, H = 800;
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
void Initialize(HWND hWnd)
{
d3d = Direct3DCreate9(D3D_SDK_VERSION);
D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory(&d3dpp, sizeof(d3dpp));
d3dpp.Windowed = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.hDeviceWindow = hWnd;
d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8;
d3dpp.BackBufferWidth = W;
d3dpp.BackBufferHeight = H;
d3d->CreateDevice(D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL,
hWnd,
D3DCREATE_SOFTWARE_VERTEXPROCESSING,
&d3dpp,
&device);
printf("Hello world\n");
}
void Cleanup()
{
device->Release();
d3d->Release();
}
void Draw(void)
{
IDirect3DSurface9 *surface = nullptr;
device->CreateOffscreenPlainSurface(W, H, D3DFMT_A8R8G8B8, D3DPOOL_SYSTEMMEM, &surface, nullptr);
IDirect3DSurface9 *buffer = nullptr;
device->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &buffer);
HDC targetdc = NULL;
surface->GetDC(&targetdc);
HWND srcwnd = GetConsoleWindow();
HDC scrdc = GetDC(srcwnd);
BOOL res = BitBlt(targetdc, 0, 0, W, H, scrdc, 0, 0, SRCCOPY);
ReleaseDC(srcwnd, scrdc);
surface->ReleaseDC(targetdc);
device->UpdateSurface(surface, NULL, buffer, NULL);
device->Present(NULL, NULL, NULL, NULL);
}
DWORD t=0;
int c=0;
int main()
{
HWND hWnd;
WNDCLASSEX wc;
ZeroMemory(&wc, sizeof(WNDCLASSEX));
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WndProc;
wc.hInstance = GetModuleHandle(NULL);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
wc.lpszClassName = L"WindowClass";
RegisterClassEx(&wc);
hWnd = CreateWindowEx(NULL,
L"WindowClass",
L"Direct3D Test",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0,
W, H,
NULL,
NULL,
GetModuleHandle(NULL),
NULL);
ShowWindow(hWnd, SW_SHOW);
Initialize(hWnd);
MSG msg;
while (TRUE)
{
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if (msg.message == WM_QUIT) break;
DWORD t1 = GetTickCount();
Draw();
DWORD t2 = GetTickCount();
t += t2 - t1;
c++;
if(c==50) printf("%f\n", t/(float)c);
}
Cleanup();
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_DESTROY:
{
PostQuitMessage(0);
return 0;
} break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment