-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWindow.cpp
More file actions
448 lines (391 loc) · 12.6 KB
/
Window.cpp
File metadata and controls
448 lines (391 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
#include "Window.h"
#include <sstream>
#include "resource.h"
#include "imgui/imgui_impl_win32.h"
extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
// Window Class Stuff
Window::WindowClass Window::WindowClass::wndClass;
Window::WindowClass::WindowClass() noexcept
:
hInst(GetModuleHandle(nullptr))
{
WNDCLASSEX wc = { 0 };
wc.cbSize = sizeof(wc);
wc.style = CS_OWNDC;
wc.lpfnWndProc = HandleMsgSetup;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = GetInstance();
wc.hIcon = static_cast<HICON>(LoadImage(GetInstance(), MAKEINTRESOURCE(IDI_ICON2), IMAGE_ICON, 32, 32, 0)); // load resource image icon with 32x32 size, in bitmap
wc.hCursor = nullptr;
wc.hbrBackground = nullptr;
wc.lpszMenuName = nullptr;
wc.lpszClassName = GetName();
wc.hIconSm = static_cast<HICON>(LoadImage(GetInstance(), MAKEINTRESOURCE(IDI_ICON2), IMAGE_ICON, 16, 16, 0)); // 16x16 small icon
RegisterClassEx(&wc);
}
Window::WindowClass::~WindowClass()
{
UnregisterClass(wndClassName, GetInstance());
}
const char* Window::WindowClass::GetName() noexcept
{
return wndClassName;
}
HINSTANCE Window::WindowClass::GetInstance() noexcept
{
return wndClass.hInst;
}
// Window Stuff
Window::Window(int width, int height, const char* name):
width (width),
height (height)
{
// calculate window size based on desired client region size
RECT wr;
wr.left = 100;
wr.right = width + wr.left;
wr.top = 100;
wr.bottom = height + wr.top;
if (AdjustWindowRect(&wr, WS_CAPTION | WS_MINIMIZEBOX | WS_SYSMENU, FALSE) == 0) // specify size of WINDOW from the CLIENT window size (wr)
throw SFWND_LAST_EXCEPT();
// create window & get hWnd
hWnd = CreateWindow(
WindowClass::GetName(), name,
WS_CAPTION | WS_MINIMIZEBOX | WS_SYSMENU,
CW_USEDEFAULT, CW_USEDEFAULT, wr.right - wr.left, wr.bottom - wr.top, // let windows decide initial window position
nullptr, nullptr, WindowClass::GetInstance(), this // pass pointer to class instance (to save the custom window class in message callback setup)
);
if (hWnd == nullptr)
throw SFWND_LAST_EXCEPT();
// show window
ShowWindow(hWnd, SW_SHOWDEFAULT);
// init imgui impl
ImGui_ImplWin32_Init(hWnd); // if future projects use multiple windows, need to modify this to handle multiple windows
// create graphics object after handle initialized
pGfx = std::make_unique<Graphics>(hWnd, width, height);
// register raw input device for mouse (for relative movement and high precision)
RAWINPUTDEVICE rid;
rid.usUsagePage = 0x01;
rid.usUsage = 0x02; // mouse usage
rid.dwFlags = 0;
rid.hwndTarget = nullptr; // capture input regardless of focus
if (RegisterRawInputDevices(&rid, 1, sizeof(rid)) == FALSE)
throw SFWND_LAST_EXCEPT();
}
Window::~Window() {
ImGui_ImplWin32_Shutdown();
DestroyWindow(hWnd);
}
void Window::SetTitle(const std::string& title)
{
if (SetWindowText(hWnd, title.c_str()) == 0)
throw SFWND_LAST_EXCEPT();
}
void Window::EnableCursor() noexcept
{
cursorEnabled = true;
ShowCursor();
EnableImGuiMouse();
FreeCursor();
}
void Window::DisableCursor() noexcept
{
cursorEnabled = false;
HideCursor();
DisableImGuiMouse();
ConfineCursor();
SetCursorToClientCenter();
}
void Window::ConfineCursor() noexcept
{
RECT rect;
GetClientRect(hWnd, &rect);
MapWindowPoints(hWnd, nullptr, reinterpret_cast<POINT*>(&rect), 2); // map client rect to screen rect
ClipCursor(&rect); // confine cursor to client region
}
void Window::FreeCursor() noexcept
{
ClipCursor(nullptr); // free cursor from confinement
}
void Window::RecenterCursor() noexcept
{
SetCursorToClientCenter();
}
POINT Window::GetClientCenter() const noexcept
{
RECT rect;
GetClientRect(hWnd, &rect);
POINT center;
center.x = (rect.left + rect.right) / 2;
center.y = (rect.top + rect.bottom) / 2;
ClientToScreen(hWnd, ¢er);
return center;
}
void Window::SetCursorToClientCenter() noexcept
{
const POINT center = GetClientCenter();
SetCursorPos(center.x, center.y);
RECT rect;
GetClientRect(hWnd, &rect);
mouse.x = (rect.left + rect.right) / 2;
mouse.y = (rect.top + rect.bottom) / 2;
}
void Window::ShowCursor() noexcept
{
while (::ShowCursor(TRUE) < 0); // show cursor until it is shown (counter is positive)
}
void Window::HideCursor() noexcept
{
while (::ShowCursor(FALSE) >= 0);
}
void Window::EnableImGuiMouse() noexcept
{
ImGui::GetIO().ConfigFlags &= ~ImGuiConfigFlags_NoMouse;
}
void Window::DisableImGuiMouse() noexcept
{
ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_NoMouse;
}
// Using PeekMessage instead of GetMessage (which blocks until new message) to allow loop continue without any user actions
std::optional<int> Window::ProcessMessages()
{
MSG msg;
// While queue has message, remove from queue and dispatch them
while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) {
if (msg.message == WM_QUIT)
return msg.wParam; // if quit message, return arg for PostQuitMessage
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return {}; // return empty optional if not quitting app
}
Graphics& Window::Gfx()
{
if (!pGfx)
throw SFWND_NOGFX_EXCEPT();
return *pGfx;
}
// Message handling
LRESULT WINAPI Window::HandleMsgSetup(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept // inital static window procedure handler (defined in CreateWindow), sets up the pointer of each instance
{
if (msg == WM_NCCREATE) { // when window is first created
const CREATESTRUCTW* const pCreate = reinterpret_cast<CREATESTRUCTW*> (lParam); // lParam contains CREATESTRUCTW, which has the pointer to custom window class we set on CreatWindow of constructor
Window* const pWnd = static_cast<Window*>(pCreate->lpCreateParams); // cast void pointer into window class pointer
SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pWnd)); // set winapi-side custom user data to pointer of window class
SetWindowLongPtr(hWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(&Window::HandleMsgThunk)); // set message procedure (callback) to non-setup function since setup is done
return pWnd->HandleMsg(hWnd, msg, wParam, lParam);
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
LRESULT WINAPI Window::HandleMsgThunk(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept // default static window procedure handler, retrieves info of class instance and let their handler do stuff (basically invokes the member function)
{
Window* const pWnd = reinterpret_cast<Window*>(GetWindowLongPtr(hWnd, GWLP_USERDATA)); // retrieve the instance pointer stored earlier as custom user data
return pWnd->HandleMsg(hWnd, msg, wParam, lParam);
}
LRESULT Window::HandleMsg(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept
{
ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam);
const auto imio = ImGui::GetIO();
switch (msg) {
case WM_CLOSE:
PostQuitMessage(0);
return 0; // only post quit message, as window destruction is handled by destructor
// ----------- Keyboard Message Handling ----------- //
case WM_KEYDOWN:
case WM_SYSKEYDOWN: //SYSKEY handling to hande the ALT(VK_MENU) key, thanks bill gates for the intuitive interface
// stifle keyboard message when imgui is using keyboard input
if (imio.WantCaptureKeyboard)
break;
if (!(lParam & 0x40000000) || kbd.IsAutoRepeatEnabled()) { // bit 30 of lParam is 1 if previously held down (autorepeat),
kbd.OnKeyPressed(static_cast<unsigned char>(wParam));
}
break;
case WM_KEYUP:
case WM_SYSKEYUP:
// stifle keyboard message when imgui is using keyboard input
if (imio.WantCaptureKeyboard)
break;
kbd.OnKeyReleased(static_cast<unsigned char>(wParam));
break;
case WM_CHAR: // both standard messages and WM_CHAR is sent when a ASCII-correspondant key is pressed
// stifle keyboard message when imgui is using keyboard input
if (imio.WantCaptureKeyboard)
break;
kbd.OnChar(static_cast<unsigned char>(wParam));
break;
case WM_KILLFOCUS: // if user un-focuses window, clear the key states
kbd.ClearState();
break;
// ----------- End Keyboard Message Handling ----------- //
case WM_ACTIVATE: // if user minimizes window, log the event to mouse buffer and release mouse capture (if any)
if (!cursorEnabled)
{
if (wParam & WA_ACTIVE)
{
ConfineCursor();
HideCursor();
}
else
{
FreeCursor();
ShowCursor();
}
}
break;
// ---------- Mouse message Handling ---------- //
case WM_MOUSEMOVE: {
// stifle mouse message when imgui is using mouse input
if (imio.WantCaptureMouse)
break;
const POINTS pt = MAKEPOINTS(lParam);
// if Mouse is in client region, we log the entry to buffer and capture the mouse to handle it
if (pt.x >= 0 && pt.x < width && pt.y >= 0 && pt.y < height) {
mouse.OnMouseMove(pt.x, pt.y);
if (!mouse.IsInWindow()) {
SetCapture(hWnd);
mouse.OnMouseEnter();
}
}
// if mouse is outside client region, we log the exit and maintain capture if button is held down
else {
if (wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON))
mouse.OnMouseMove(pt.x, pt.y);
// button released, remove capture and log leave to buffer
else {
ReleaseCapture();
mouse.OnMouseLeave();
}
}
break;
}
case WM_LBUTTONDOWN: {
if (!cursorEnabled)
{
ConfineCursor();
HideCursor();
}
if (imio.WantCaptureMouse)
break;
const POINTS pt = MAKEPOINTS(lParam);
mouse.OnLeftPressed(pt.x, pt.y);
break;
}
case WM_RBUTTONDOWN: {
if (imio.WantCaptureMouse)
break;
const POINTS pt = MAKEPOINTS(lParam);
mouse.OnRightPressed(pt.x, pt.y);
break;
}
case WM_MBUTTONDOWN: {
if (imio.WantCaptureMouse)
break;
const POINTS pt = MAKEPOINTS(lParam);
mouse.OnMiddlePressed(pt.x, pt.y);
break;
}
case WM_LBUTTONUP: {
if (imio.WantCaptureMouse)
break;
const POINTS pt = MAKEPOINTS(lParam);
mouse.OnLeftReleased(pt.x, pt.y);
break;
}
case WM_RBUTTONUP: {
if (imio.WantCaptureMouse)
break;
const POINTS pt = MAKEPOINTS(lParam);
mouse.OnRightReleased(pt.x, pt.y);
break;
}
case WM_MBUTTONUP: {
if (imio.WantCaptureMouse)
break;
const POINTS pt = MAKEPOINTS(lParam);
mouse.OnMiddleReleased(pt.x, pt.y);
break;
}
case WM_MOUSEWHEEL: {
if (imio.WantCaptureMouse)
break;
const POINTS pt = MAKEPOINTS(lParam);
const int delta = GET_WHEEL_DELTA_WPARAM(wParam);
mouse.OnWheelDelta(pt.x, pt.y, delta);
break;
}
// ---------- End Mouse message Handling ---------- //
// ---------- Raw Mouse Input Handling ---------- //
case WM_INPUT: {
if (!mouse.RawEnabled())
break;
if (imio.WantCaptureMouse)
break;
UINT size = 0;
if (GetRawInputData(reinterpret_cast<HRAWINPUT>(lParam), RID_INPUT, nullptr, &size, sizeof(RAWINPUTHEADER)) == -1)
{
break; // bail out if error
}
rawBuffer.resize(size);
if (GetRawInputData(reinterpret_cast<HRAWINPUT>(lParam), RID_INPUT, rawBuffer.data(), &size, sizeof(RAWINPUTHEADER)) != size)
{
break; // bail out if error
}
// process raw input
auto& ri = reinterpret_cast<const RAWINPUT&>(*rawBuffer.data());
if (ri.header.dwType == RIM_TYPEMOUSE && ri.data.mouse.lLastX != 0 || ri.data.mouse.lLastY != 0)
{
mouse.OnRawDelta(ri.data.mouse.lLastX, ri.data.mouse.lLastY);
}
break;
}
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
bool Window::IsCursorEnabled() const noexcept
{
return cursorEnabled;
}
// Exception handling
Window::HrException::HrException(int line, const char* file, HRESULT hr) noexcept:
SmflmException(line, file),
hr (hr)
{}
const char* Window::HrException::what() const noexcept
{
std::ostringstream oss;
oss << GetType() << std::endl
<< "[Error Code]" << GetErrorCode() << std::endl
<< "[Descripton]" << GetErrorString() << std::endl
<< GetOriginString();
whatBuffer = oss.str();
return whatBuffer.c_str();
}
const char* Window::HrException::GetType() const noexcept
{
return "Smflm Window Exception";
}
std::string Window::HrException::TranslateErrorCode(HRESULT hr) noexcept // uses windows-provided macro to format error code into readable message
{
char* pMsgBuf = nullptr;
DWORD nMsgLen = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, hr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPSTR>(&pMsgBuf), 0, nullptr);
// Windows macro formats error code HRESULT hr into string
if (nMsgLen == 0) return "Unidentified Error Code";
std::string errorString = pMsgBuf;
LocalFree(pMsgBuf); // save to string object and deallocate pMsgBuf
return errorString;
}
HRESULT Window::HrException::GetErrorCode() const noexcept
{
return hr;
}
std::string Window::HrException::GetErrorString() const noexcept
{
return TranslateErrorCode(hr);
}
const char* Window::NoGfxException::GetType() const noexcept
{
return "Graphics Exception [Device Removed] (DXGI_ERROR_DEVICE_REMOVED)";
}