Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
469 lines (430 loc) · 17.6 KB
/
Copy pathmain.cpp
File metadata and controls
469 lines (430 loc) · 17.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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
#include <iostream>
#include <windows.h>
#include <WinUser.h>
#include <cstdint>
#include <xinput.h>
#include <math.h>
#include <dsound.h>
#define internal static
#define global_variable static
#define local_persist static
#define Pi32 3.14159265359
typedef uint8_t uint8;
typedef uint16_t uint16;
typedef uint32_t uint32;
typedef uint64_t uint64;
typedef uint32 bool32;
typedef int8_t int8;
typedef int16_t int16;
typedef int32_t int32;
typedef int64_t int64;
typedef float real32;
typedef double real64;
struct win32_offscreen_buffer {
BITMAPINFO Info;
void* Memory;
int Width;
int Height;
int BytesPerPixel;
int Pitch;
};
struct win32_window_dimensions {
int Width;
int Height;
};
struct win32_sound_output {
int ToneHz;
int ToneVolume;
uint32 RunningSampleIndex;
int SamplesPerSecond;
int WavePeriod;
int BytesPerSample;
int SecondaryBufferSize;
};
// global for now.
global_variable bool32 Running;
global_variable win32_offscreen_buffer GlobalBackbuffer;
global_variable LPDIRECTSOUNDBUFFER GlobalSecondaryBuffer;
// XInputGetState
#define X_INPUT_GET_STATE(name) DWORD WINAPI name(DWORD dwUserIndex, XINPUT_STATE *pState)
typedef X_INPUT_GET_STATE(x_input_get_state);
X_INPUT_GET_STATE(XInputGetStateStub) {
return ERROR_DEVICE_NOT_CONNECTED;
}
global_variable x_input_get_state *XInputGetState_ = XInputGetStateStub;
// XInputSetState
#define X_INPUT_SET_STATE(name) DWORD WINAPI name(DWORD dwUserIndex, XINPUT_VIBRATION *pVibration)
typedef X_INPUT_SET_STATE(x_input_set_state);
X_INPUT_SET_STATE(XInputSetStateStub) {
return ERROR_DEVICE_NOT_CONNECTED;
}
global_variable x_input_set_state *XInputSetState_ = XInputSetStateStub;
// DirectSoundCreate
#define DIRECT_SOUND_CREATE(name) HRESULT WINAPI name(LPCGUID pcGuidDevice, LPDIRECTSOUND *ppDS, LPUNKNOWN pUnkOuter);
typedef DIRECT_SOUND_CREATE(direct_sound_create);
internal void Win32FillSoundBuffer(win32_sound_output *SoundOutput, DWORD ByteToLock, DWORD BytesToWrite) {
VOID *Region1;
DWORD Region1Size;
VOID *Region2;
DWORD Region2Size;
if (SUCCEEDED(GlobalSecondaryBuffer->Lock(ByteToLock, BytesToWrite, &Region1, &Region1Size, &Region2, &Region2Size, 0))) {
// assert region1size/region2size valid
// NOTE: buggy
// TODO: collapse these two loops since they are the same
auto SampleOut = (int16 *)Region1;
DWORD Region1SampleCount = Region1Size / SoundOutput->BytesPerSample;
for (DWORD SampleIndex = 0; SampleIndex < Region1SampleCount; ++SampleIndex) {
real32 t = 2.0f * Pi32 * (real32)SoundOutput->RunningSampleIndex / (real32)SoundOutput->WavePeriod;
real32 SineValue = sinf(t);
int16 SampleValue = (int16)(SineValue * SoundOutput->ToneVolume);
*SampleOut++ = SampleValue;
*SampleOut++ = SampleValue;
++SoundOutput->RunningSampleIndex;
}
DWORD Region2SampleCount = Region2Size / SoundOutput->BytesPerSample;
SampleOut = (int16 *)Region2;
for (DWORD SampleIndex = 0; SampleIndex < Region2SampleCount; ++SampleIndex) {
real32 t = 2.0f * Pi32 * (real32)SoundOutput->RunningSampleIndex / (real32)SoundOutput->WavePeriod;
real32 SineValue = sinf(t);
int16 SampleValue = (int16)(SineValue * SoundOutput->ToneVolume);
*SampleOut++ = SampleValue;
*SampleOut++ = SampleValue;
++SoundOutput->RunningSampleIndex;
}
GlobalSecondaryBuffer->Unlock(Region1, Region1Size, Region2, Region2Size);
}
}
internal void Win32LoadXInput() {
HMODULE XInputLibrary = LoadLibraryA("xinput1_4.dll");
if (!XInputLibrary) {
LoadLibraryA("xinput1_3.dll");
}
if (XInputLibrary) {
XInputGetState_ = (x_input_get_state *)GetProcAddress(XInputLibrary, "XInputGetState");
if (!XInputGetState_) {
XInputGetState_ = XInputGetStateStub;
}
XInputSetState_ = (x_input_set_state * )GetProcAddress(XInputLibrary, "XInputSetState");
if (!XInputSetState_) {
XInputSetState_ = XInputSetStateStub;
}
}
}
internal void RenderWeirdGradient(win32_offscreen_buffer *Buffer, int XOffset, int YOffset) {
uint8* Row = (uint8*)Buffer->Memory;
for (int Y = 0; Y < Buffer->Height; ++Y) {
uint32* Pixel = (uint32*)Row;
for (int X = 0; X < Buffer->Width; ++X) {
// Pixel in memory: BB GG RR xx
//BLUE
uint8 Blue = (X + XOffset) ;
uint8 Green = (Y + YOffset);
*Pixel++ = (Green << 8 | Blue);
}
Row += Buffer->Pitch;
}
}
internal win32_window_dimensions Win32GetWindowDimensions(HWND Window) {
RECT Rect;
GetClientRect(Window, &Rect);
win32_window_dimensions Dimensions{};
Dimensions.Width = Rect.right - Rect.left;
Dimensions.Height = Rect.bottom - Rect.top;
return Dimensions;
}
internal void Win32ResizeDIBSection(win32_offscreen_buffer *Buffer, int Width, int Height)
{
if (Buffer->Memory) {
VirtualFree(Buffer->Memory, 0, MEM_RELEASE);
}
Buffer->Width = Width;
Buffer->Height = Height;
Buffer->BytesPerPixel = 4;
// free our DIBSection
// when biheight field is negative this is the clue to windows treat this bitmap as top-down meaning the first three bytes of the iamge are the colour for the top left pixel
Buffer->Info.bmiHeader.biSize = sizeof(Buffer->Info.bmiHeader);
Buffer->Info.bmiHeader.biWidth = Buffer->Width;
Buffer->Info.bmiHeader.biHeight = -Buffer->Height;
Buffer->Info.bmiHeader.biPlanes = 1;
Buffer->Info.bmiHeader.biBitCount = 32;
Buffer->Info.bmiHeader.biCompression = BI_RGB;
//Bullet-proof this maybe don't free first free after then free first if that fails.
int BitmapMemorySize = (Buffer->Width*Buffer->Height) * Buffer->BytesPerPixel;
Buffer->Memory = VirtualAlloc(nullptr, BitmapMemorySize, MEM_COMMIT, PAGE_READWRITE);
Buffer->Pitch = Width*Buffer->BytesPerPixel;
}
internal void Win32DisplayBufferInWindow(HDC DeviceContext, int WindowWidth, int WindowHeight, win32_offscreen_buffer *Buffer, int X, int Y, int Width, int Height)
{
StretchDIBits(DeviceContext,
0, 0, WindowWidth, WindowHeight,
0, 0, Buffer->Width, Buffer->Height,
Buffer->Memory, &Buffer->Info, DIB_RGB_COLORS, SRCCOPY);
}
internal LRESULT CALLBACK Win32MainWindowCallback(HWND Window, UINT Message, WPARAM WParam, LPARAM LParam) {
LRESULT Result = 0;
switch (Message) {
case WM_SIZE:
{
} break;
case WM_CLOSE:
case WM_DESTROY:
{
// handle as an error - recreate window?
Running = false;
} break;
case WM_KEYDOWN:
case WM_KEYUP:
{
uint32 VKCode = WParam;
bool32 WasDown = (LParam & 1 << 30) != 0;
bool32 IsDown = (LParam & 1 << 31) == 0;
if (WasDown != IsDown) {
if (VKCode == 'W') {
OutputDebugStringA("W");
}
else if (VKCode == 'S') {
OutputDebugStringA("S");
}
else if (VKCode == 'A') {
OutputDebugStringA("A");
}
else if (VKCode == 'D') {
OutputDebugStringA("D");
}
else if (VKCode == 'Q') {
OutputDebugStringA("Q");
}
else if (VKCode == 'E') {
OutputDebugStringA("E");
}
else if (VKCode == VK_UP) {
OutputDebugStringA("U");
}
else if (VKCode == VK_LEFT) {
OutputDebugStringA("L");
}
else if (VKCode == VK_RIGHT) {
OutputDebugStringA("R");
}
else if (VKCode == VK_DOWN) {
OutputDebugStringA("D");
}
else if (VKCode == VK_SPACE) {
OutputDebugStringA("SPACE");
}
else if (VKCode == VK_ESCAPE) {
if (IsDown) {
OutputDebugStringA("ESCAPE DOWN");
}
if (WasDown) {
OutputDebugStringA("ESCAPE WAS DOWN");
}
}
bool32 AltKeyWasDown = LParam & (1 << 29);
if (VKCode == VK_F4 && AltKeyWasDown) {
Running = false;
}
}
} break;
case WM_PAINT:
{
PAINTSTRUCT Paint;
win32_window_dimensions Dimensions = Win32GetWindowDimensions(Window);
HDC DeviceContext = BeginPaint(Window, &Paint);
int X = Paint.rcPaint.left;
int Y = Paint.rcPaint.top;
int Width = Paint.rcPaint.right - Paint.rcPaint.left;
int Height = Paint.rcPaint.bottom - Paint.rcPaint.top;
Win32DisplayBufferInWindow(DeviceContext,
Dimensions.Width, Dimensions.Height, &GlobalBackbuffer, X, Y, Width, Height);
EndPaint(Window, &Paint);
}
case WM_ACTIVATEAPP:
{
OutputDebugString(reinterpret_cast<LPCSTR>(L"WM_ACTIVEATEAPP\n"));
} break;
default:
{
Result = DefWindowProc(Window, Message, WParam, LParam);
} break;
}
return Result;
}
internal void Win32InitDSound(HWND Window, int32 BufferSize, int32 SamplesPerSecond) {
HMODULE DSoundLibrary = LoadLibraryA("dsound.dll");
if (DSoundLibrary) {
direct_sound_create *DirectSoundCreate = (direct_sound_create*)GetProcAddress(DSoundLibrary, "DirectSoundCreate");
IDirectSound *DirectSound;
if (DirectSoundCreate && SUCCEEDED(DirectSoundCreate(0, &DirectSound, 0))) {
WAVEFORMATEX WaveFormat = {};
WaveFormat.wFormatTag = WAVE_FORMAT_PCM;
WaveFormat.nChannels = 2;
WaveFormat.nSamplesPerSec = SamplesPerSecond;
WaveFormat.wBitsPerSample = 16;
WaveFormat.nBlockAlign = (WaveFormat.wBitsPerSample * WaveFormat.nChannels) / 8;
WaveFormat.nAvgBytesPerSec = WaveFormat.nSamplesPerSec * WaveFormat.nBlockAlign;
WaveFormat.cbSize = 0;
if (SUCCEEDED(DirectSound->SetCooperativeLevel(Window,DSSCL_PRIORITY))) {
// create a primary buffer
LPDIRECTSOUNDBUFFER PrimaryBuffer;
DSBUFFERDESC BufferDescription = {sizeof(BufferDescription)};
BufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;
BufferDescription.dwSize = sizeof(BufferDescription);
if (SUCCEEDED(DirectSound->CreateSoundBuffer(&BufferDescription, &PrimaryBuffer, 0))) {
if (SUCCEEDED(PrimaryBuffer->SetFormat(&WaveFormat))) {
OutputDebugStringA("Primary buffer format was set\n");
}
else {
OutputDebugStringA("Failed to set primary buffer format\n");
}
}
else {
OutputDebugStringA("Failed to create primary buffer\n");
}
}
else {
OutputDebugStringA("Failed to set cooperative level\n");
}
// create a secondary buffer
DSBUFFERDESC BufferDescription = {};
BufferDescription.lpwfxFormat = &WaveFormat;
BufferDescription.dwBufferBytes = BufferSize;
BufferDescription.dwSize = sizeof(BufferDescription);
if (SUCCEEDED(DirectSound->CreateSoundBuffer(&BufferDescription, &GlobalSecondaryBuffer, 0))) {
OutputDebugStringA("Secondary buffer created successfully.\n");
}
else {
OutputDebugStringA("Failed to create secondary buffer\n");
}
}
else {
OutputDebugStringA("Failed to load DirectSound lib\n");
}
}
else {
OutputDebugStringA("Failed to find DirectSound dll\n");
}
}
int CALLBACK WinMain(HINSTANCE Instance, HINSTANCE PrevInstance, LPSTR CommandLine, int ShowCode)
{
Win32LoadXInput();
WNDCLASSA WindowClass = {};
Win32ResizeDIBSection(&GlobalBackbuffer, 1280, 720);
WindowClass.style = CS_HREDRAW | CS_VREDRAW;
WindowClass.lpfnWndProc = Win32MainWindowCallback;
WindowClass.hInstance = Instance;
WindowClass.lpszClassName = reinterpret_cast<LPCSTR>(L"HandmadeHeroWindowClass");
if (RegisterClass(&WindowClass))
{
HWND Window = CreateWindowEx(
0,
WindowClass.lpszClassName,
reinterpret_cast<LPCSTR>(L"Handmade Hero"),
WS_OVERLAPPEDWINDOW|WS_VISIBLE,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
nullptr,
nullptr,
Instance,
nullptr);
if (Window)
{
int XOffset = 0;
int YOffset = 0;
win32_sound_output SoundOutput = {};
SoundOutput.ToneHz = 256;
SoundOutput.ToneVolume = 1000;
SoundOutput.RunningSampleIndex = 0;
SoundOutput.SamplesPerSecond = 48000;
SoundOutput.WavePeriod = SoundOutput.SamplesPerSecond/ SoundOutput.ToneHz;
SoundOutput.BytesPerSample = sizeof(int16) * 2;
SoundOutput.SecondaryBufferSize = SoundOutput.SamplesPerSecond * SoundOutput.BytesPerSample;
Win32InitDSound(Window, SoundOutput.SecondaryBufferSize, SoundOutput.SamplesPerSecond);
Win32FillSoundBuffer(&SoundOutput, 0, SoundOutput.SecondaryBufferSize);
GlobalSecondaryBuffer->Play(0 ,0, DSBPLAY_LOOPING);
Running = true;
MSG Message;
while (Running) {
while (PeekMessageA(&Message, nullptr, 0, 0, PM_REMOVE)) {
TranslateMessage(&Message);
DispatchMessageA(&Message);
if (Message.message == WM_QUIT) {
Running = false;
}
}
// TODO Should we pull this more frequently?
for (DWORD ControllerIndex = 0; ControllerIndex < XUSER_MAX_COUNT; ControllerIndex++) {
XINPUT_STATE ControllerState;
if (XInputGetState_(ControllerIndex, &ControllerState) == ERROR_SUCCESS) {
// controller is plugged in
// dwPacket number might increment too rapidly, take a look
XINPUT_GAMEPAD *Pad = &ControllerState.Gamepad;
bool32 Up = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_UP);
bool32 Down = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_DOWN);
bool32 Left = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_LEFT);
bool32 Right = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_RIGHT);
bool32 Start = (Pad->wButtons & XINPUT_GAMEPAD_START);
bool32 Back = (Pad->wButtons & XINPUT_GAMEPAD_BACK);
bool32 AButton = (Pad->wButtons & XINPUT_GAMEPAD_A);
bool32 BButton = (Pad->wButtons & XINPUT_GAMEPAD_B);
bool32 XButton = (Pad->wButtons & XINPUT_GAMEPAD_X);
bool32 YButton = (Pad->wButtons & XINPUT_GAMEPAD_Y);
bool32 LeftShoulder = (Pad->wButtons & XINPUT_GAMEPAD_LEFT_SHOULDER);
bool32 RightShoulder = (Pad->wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER);
int16 StickX = Pad->sThumbLX;
int16 StickY = Pad->sThumbLY;
if (AButton) {
YOffset += 2;
XINPUT_VIBRATION Vibration;
Vibration.wLeftMotorSpeed = 60000;
Vibration.wRightMotorSpeed = 60000;
XInputSetState_(ControllerIndex, &Vibration);
}
else {
XINPUT_VIBRATION Vibration;
Vibration.wLeftMotorSpeed = 0;
Vibration.wRightMotorSpeed = 0;
XInputSetState_(ControllerIndex, &Vibration);
}
} else {
// controller not available
}
}
HDC DeviceContext = GetDC(Window);
RenderWeirdGradient(&GlobalBackbuffer, XOffset, YOffset);
DWORD PlayCursor;
DWORD WriteCursor;
if (SUCCEEDED(GlobalSecondaryBuffer->GetCurrentPosition(&PlayCursor, &WriteCursor))) {
DWORD BytesToWrite;
DWORD BytesToLock = (SoundOutput.RunningSampleIndex * SoundOutput.BytesPerSample) % SoundOutput.SecondaryBufferSize;
// TODO: Change to use lower latency offset from play cursor when we actually have sound effects.
if (BytesToLock == PlayCursor) {
BytesToWrite = 0;
}
else if (BytesToLock > PlayCursor) {
BytesToWrite = SoundOutput.SecondaryBufferSize - BytesToLock;
BytesToWrite += PlayCursor;
}
else {
BytesToWrite = PlayCursor - BytesToLock;
}
Win32FillSoundBuffer(&SoundOutput, BytesToLock, BytesToWrite);
}
win32_window_dimensions Dimensions = Win32GetWindowDimensions(Window);
Win32DisplayBufferInWindow(DeviceContext, Dimensions.Width, Dimensions.Height, &GlobalBackbuffer, 0, 0, Dimensions.Width, Dimensions.Height);
ReleaseDC(Window, DeviceContext);
}
}
else
{
// TODO: logging
}
}
else
{
// TODO: logging
}
return 0;
}