Handmade Hero»Forums»Code
Dan Zaidan
45 posts / 1 project
Game programmer. Creator of Eliosi's Hunt. I share the love I have for making games on my Youtube channel: http://youtube.com/danzaidan
[Day 235] Opengl's pixel format takes a long time
Hi folks!

I'm trying to work with Opengl and even though I got it to work (I can set a screen color) successfully, it takes a long time (something like 3 seconds) for opengl to init.

I stepped through the code and found that the bottle neck was in ChoosePixelFormat:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
PIXELFORMATDESCRIPTOR desired_pixel_format = {};
    desired_pixel_format.nSize = sizeof(desired_pixel_format);
    desired_pixel_format.nVersion = 1;
    desired_pixel_format.dwFlags = PFD_SUPPORT_OPENGL|PFD_DRAW_TO_WINDOW|PFD_DOUBLEBUFFER;
    desired_pixel_format.cColorBits = 32;
    desired_pixel_format.cAlphaBits = 8;
    desired_pixel_format.iLayerType = PFD_MAIN_PLANE;
    
    int suggested_pixel_format_index = ChoosePixelFormat(window_dc, &desired_pixel_format);
    PIXELFORMATDESCRIPTOR suggested_pixel_format;
    DescribePixelFormat(window_dc, suggested_pixel_format_index, sizeof(suggested_pixel_format), &suggested_pixel_format);
    SetPixelFormat(window_dc, suggested_pixel_format_index, &suggested_pixel_format);


So I copied the values from the pixel format windows gave me and hardcoded it into a new code that doesn't use ChoosePixelFormat.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
PIXELFORMATDESCRIPTOR pixel_format = {};
    pixel_format.nSize = sizeof(pixel_format);
    pixel_format.nVersion = 1;
    pixel_format.dwFlags = 33317;
    pixel_format.cColorBits = 32;
    pixel_format.cRedBits = 8;
    pixel_format.cRedShift = 16;
    pixel_format.cGreenBits = 8;
    pixel_format.cGreenShift = 8;
    pixel_format.cBlueBits = 8;
    pixel_format.cBlueShift = 0;
    pixel_format.cAlphaBits = 8;
    pixel_format.cAlphaShift = 24;
    pixel_format.cAccumBits = 64;
    pixel_format.cAccumRedBits = 16;
    pixel_format.cAccumGreenBits = 16;
    pixel_format.cAccumBlueBits = 16;
    pixel_format.cAccumAlphaBits = 16;
    pixel_format.cDepthBits = 24;
    pixel_format.cStencilBits = 0;
    pixel_format.cAuxBuffers = 4;
    
    BOOL result = SetPixelFormat(window_dc, 8, &pixel_format);


However this time, the bottleneck happened in SetPixelFormat.

I found it quite weird that it launched 4 threads and specially weird that it changed places (ChoosePixelFormat and SetPixelFormat) based on what code I called, and that the output log looked the same on them both:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
'win32_main.exe' (Win32): Loaded 'C:\Windows\System32\nvoglv64.dll'. Cannot find or open the PDB file.
'win32_main.exe' (Win32): Loaded 'C:\Windows\System32\shell32.dll'. Cannot find or open the PDB file.
'win32_main.exe' (Win32): Loaded 'C:\Windows\System32\windows.storage.dll'. Cannot find or open the PDB file.
'win32_main.exe' (Win32): Loaded 'C:\Windows\System32\shlwapi.dll'. Cannot find or open the PDB file.
'win32_main.exe' (Win32): Loaded 'C:\Windows\System32\powrprof.dll'. Cannot find or open the PDB file.
'win32_main.exe' (Win32): Loaded 'C:\Windows\System32\profapi.dll'. Cannot find or open the PDB file.
'win32_main.exe' (Win32): Loaded 'C:\Windows\System32\setupapi.dll'. Cannot find or open the PDB file.
'win32_main.exe' (Win32): Loaded 'C:\Windows\System32\wtsapi32.dll'. Cannot find or open the PDB file.
'win32_main.exe' (Win32): Loaded 'C:\Windows\System32\version.dll'. Cannot find or open the PDB file.
'win32_main.exe' (Win32): Loaded 'C:\Windows\System32\devobj.dll'. Cannot find or open the PDB file.
'win32_main.exe' (Win32): Loaded 'C:\Windows\System32\wintrust.dll'. Cannot find or open the PDB file.
'win32_main.exe' (Win32): Loaded 'C:\Windows\System32\msasn1.dll'. Cannot find or open the PDB file.
'win32_main.exe' (Win32): Loaded 'C:\Windows\System32\crypt32.dll'. Cannot find or open the PDB file.
The thread 0x2ce8 has exited with code 0 (0x0).
The thread 0x2dd8 has exited with code 0 (0x0).
The thread 0xb20 has exited with code 0 (0x0).
The thread 0x2e64 has exited with code 0 (0x0).
'win32_main.exe' (Win32): Loaded 'C:\Windows\System32\nvspcap64.dll'. Cannot find or open the PDB file.
'win32_main.exe' (Win32): Loaded 'C:\Windows\System32\ole32.dll'. Cannot find or open the PDB file.
'win32_main.exe' (Win32): Loaded 'C:\Windows\System32\psapi.dll'. Cannot find or open the PDB file.
'win32_main.exe' (Win32): Loaded 'C:\Windows\System32\winhttp.dll'. Cannot find or open the PDB file.


Last week, I tried messing around with SDL and found that whenever I changed the window to use Opengl, it took the same 3 seconds to start. I tested that .exe in 4 different PCs. Two of them opened instantaneously, and two (the better two) took a long time.

I have a 64-bit Windows 10, running on an i7-5820K @3.30GHz and two GTX 780.

What could possibly be causing this?

Thanks,
Dan Zaidan
Mārtiņš Možeiko
2559 posts / 2 projects
[Day 235] Opengl's pixel format takes a long time
Edited by Mārtiņš Možeiko on
Bad driver. Bad anti-virus software. Some other running service/utility/software. But most likely just a drivers issue. Not much you can do...
Alice
1 posts
None
[Day 235] Opengl's pixel format takes a long time
I'm getting the same thing. On my PC with a GTX 750Ti it takes 3 seconds, yet on my laptop with just the integrated intel graphics, it only takes about 100 milliseconds.
Lewis
2 posts
[Day 235] Opengl's pixel format takes a long time
I'm running into the same problem, about 1.2 seconds for me. Some web searching digs up a number of posts about this issue, but no actual solutions. It does reek of a driver issue, but the issue seems widespread enough that finding a workaround would be highly desirable.
Dan Zaidan
45 posts / 1 project
Game programmer. Creator of Eliosi's Hunt. I share the love I have for making games on my Youtube channel: http://youtube.com/danzaidan
[Day 235] Opengl's pixel format takes a long time
@mmozeiko I only use Windows Defender in this PC, it turned it off and added it to the exceptions list but there was no difference. I ended all the processes I could and no difference, so yeah, it's probably a driver problem.

It's somewhat reassuring that Nytheris and musicaljelly also have the problem. :P

Just to add some info, I tested on the drivers GeForce 382.05, 384.76 and 384.94.
Mārtiņš Možeiko
2559 posts / 2 projects
[Day 235] Opengl's pixel format takes a long time
Edited by Mārtiņš Možeiko on
I did a little debugging and disassembling of Nvidia OpenGL driver (user-space part of it) to look what it is doing.

First I wrote this test code: https://gist.github.com/mmozeiko/9b661cf8f48b56945984d518a9cd6310

On my desktop PC (i7-6700K, GTX 970, Windows 10 x64, Nvidia 384.94 driver) it gives me 0.668 seconds for Choose + Set pixel format functions.

After profiling, disassembling and debugging the driver, I found that most of the time it is processing huge list application & executable names. Not sure exactly what it is doing but its a lot of code+time. I think it tries to mach profile for custom 3D settings. In your Nvidia Control Panel go to "Manage 3D Settings" -> Program Settings -> uncheck "Show only programs found on this computer" and check how big is the list in combobox. It is huge.

Unfortunately there is no good way to officially delete contents of this list. I started to look where this list is stored and found three locations:
  1. C:\ProgramData\NVIDIA Corporation\Drs\nvdrsdb0.bin
  2. C:\ProgramData\NVIDIA Corporation\Drs\nvdrsdb1.bin
  3. C:\Program Files\NVIDIA Corporation\Drs\nvdrsdb.bin
First two you can safely remove - but just in case DO NOT DELETE these files. Rename to something like nvdrsdb0.bin.old. It looks that these files store customized settings and are recreated from third location if they don't exist.

After removing first two files, the test program from my gist now prints 0.456 seconds. That is 32% improvement. Pretty nice.

Unfortunately we cannot remove or replace with empty file the third location. By doing that the Nvidia opengl driver will simply crash and none of your applications will work. What I did instead - I went to Nvidia site and took this file from old 280.26 driver version from 2011. There this file is only 305KB big compared to 1.4MB - so it stores less information about application settings. You can get this file here: nvdrsdb.zip You'll need to replace this file every time you upgrade Nvidia driver.

After replacing nvdrsdb.bin file my test program prints out 0.306 seconds which is ~54% - two times faster than initially. Even better!

Now it looks that Nvidia opengl code now is spending most of the time in different place, some initialization code with loading library (LoadLibrary function). Processing that big list is not a bottleneck anymore. Ideally I would want to reduce this list to 0 items, but that would require more time on reverse engineering format of nvdrsdb.bin file. I tried some quick'n'dirty experiments - replaced few numbers with value 0 in header, but all I got was crash. So more debugging is needed. But it should be possible.

I think Nvidia is just adding more and more predefined application profiles to this file, it gets bigger and bigger, so the linear scan through list gets slower and slower. Not 100% sure about this, that's just my guess.

I do not know if this breaks anything. Maybe your SLI configuration will stop working. Maybe there will be some glitches with older OpenGL applications/games - this file might contain some workarounds, not only 3D setting customizations. But try it, maybe it gets faster also for you. This is not a real fix, but for dev machine this could be acceptable workaround.

Dan Zaidan
45 posts / 1 project
Game programmer. Creator of Eliosi's Hunt. I share the love I have for making games on my Youtube channel: http://youtube.com/danzaidan
[Day 235] Opengl's pixel format takes a long time
Wow, thanks so much for digging into this!

I ran your code and it printed 1.081.
So I went to the C:\Program Files\NVIDIA Corporation\Drs directory and there was no nvdrsdb0.bin or nvdrsdb0.bin!

Only nvdrsdb.bin and dbInstaller.exe.
After changing the nvdrsdb.bin file to the one you linked, I got a small performance increase to 1.077. :(

Over in the SDL thread, Daniel_Gibson linked to this tweet from Sean Barret: https://twitter.com/nothings/status/891335303130005504
Based on his tweet: "If NVIDIA folks following me want more info" I suppose Nvidia is already aware of the driver issue, and that it is actually pretty widespread (with different results, apparently). :P
Mārtiņš Možeiko
2559 posts / 2 projects
[Day 235] Opengl's pixel format takes a long time
Edited by Mārtiņš Možeiko on
nvdrsdb0.bin and nvdrsdb1.bin files are in "C:\ProgramData\NVIDIA Corporation\Drs" folder. Not "Program Files".
Dan Zaidan
45 posts / 1 project
Game programmer. Creator of Eliosi's Hunt. I share the love I have for making games on my Youtube channel: http://youtube.com/danzaidan
[Day 235] Opengl's pixel format takes a long time
Oh yeah! (I can't believe I overlooked that... :( )

Now it's waay faster! 0.478!

Thanks so much! :)
3 posts
[Day 235] Opengl's pixel format takes a long time
Edited by ginkgobitter on Reason: changed misleading comment
I have a small addition to this not pertaining to the particular nvidia issue at hand, but the seemingly excessive call cost in general.

Since Choose/Set/...PixelFormat are part of OpenGL, despite them usually being called through GDI32, they require the relevant DLLs and their dependencies to be loaded and initialized, which gets triggered on the first function call.
Hence, you can shave off even more time by making a call to one of these functions as early as possible within a new thread.

1
2
3
4
5
6
7
8
9
DWORD WINAPI glSpeedUp(LPVOID param) {
	HDC dc = GetDC(NULL);
	DescribePixelFormat(dc, 0, 0, NULL);
	ReleaseDC(NULL, dc);
	return 0;
}

// this stack size is far from optimal; refer the later post for a more fitting way to create this thread
CreateThread(NULL, 2048, &glSpeedUp, NULL, 0, NULL);


This is a fire and forget solution, because once your actual PixelFormat calls are made, they will just wait for the initialization to finish, if necessary. Depending on how much time the rest of your initialization took, you might end up reducing the execution time of the PixelFormat call to pretty much nothing (these calls are very fast).

On a system with only one core (or in the unlikely scenario that your process affinity was changed accordingly) this most certainly yields no benefit. If you have this information readily available to you and this is the case, you may as well skip this pre-loading step.
Simon Anciaux
1337 posts
[Day 235] Opengl's pixel format takes a long time
I tried on an AMD card with the latest drivers in a small game and it's actually a little slower on my machine. Creating and setting up the window is one of the first things the application do, so there isn't much time for the "preload". And since my goal is to display the window as soon as possible, I will probably never have enough time to preload. But if it works on nvidia card maybe it's worth the small loss on AMD cards ?
 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
Timing from application startup to window display (with OpenGL context).

Without glSpeedUp (performance counter)
439165
450329
419435
431645
417669

With glSpeedUp (performance counter)
484501
480652
424411
522190
514524

Without glSpeedUp (performance counter / performance frequency)
0.168818
0.165523
0.194572
0.190022
0.205242

With glSpeedUp (performance counter / performance frequency)
0.201068
0.212608
0.204966
0.168355
0.215469

3 posts
[Day 235] Opengl's pixel format takes a long time
Edited by ginkgobitter on Reason: typo
It surprises me that the slowdown is so significant (in fact, that there could be one at all). I am actually working without libraries and implicit imports. I import all the function calls explicitly and create the speedup thread as soon as the necessary function pointers are loaded, so it can start processing while finishing to import other functions.
After that there's still detection of monitors and calls for DPI settings, initialization of configuration files... so there's quite a bit of time to at least shave some time off the loading process.

I am very surprised that you actually experience a slowdown which doesn't really makes sense to me. It's what I would imagine could happen on a unicore system where the process cannot be parallelized. But I cannot see another scenario in which this would become slower. That would mean the thread creation took longer than the code leading up to your first PixelFormat call.

If you have some time, I'd really appreciate more details (what exactly are you doing between thread creation and your first PixelFormat call and how long is it taking, and do you have a multicore system?), I am currently running this on a R9 280 (driver version 17.7.1) on an 8-core AMD system and this process makes the call about 30% faster for me.

(I actually have not tried it on NVIDIA cards yet - but it would make sense that it works the same way, since the general way of handling this is coming from Windows, not the GPU driver)
Simon Anciaux
1337 posts
[Day 235] Opengl's pixel format takes a long time
Edited by Simon Anciaux on Reason: Error in the compile command, Updated config, GTX test
Here is the code (I removed everything related to the game). Search for window_create.
   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
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
#define NOLOOP 1

#define WIN32_LEAN_AND_MEAN 1
#include <windows.h>
#include <stdint.h>

typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;

typedef int8_t s8;
typedef int16_t s16;
typedef int32_t s32;
typedef int64_t s64;

typedef uint8_t b8;
typedef uint32_t b32;

typedef uintptr_t umm;
typedef intptr_t smm;

typedef float r32;
typedef double r64;

#define arrayCount( array ) ( ( u64 ) ( sizeof( array ) / sizeof( ( array )[ 0 ] ) ) )
#define s32_max 0x7fffffff
#define s32_min ( -0x7fffffff - 1 )

typedef union PlatformSpecific {
    
    struct {
        HWND windowHandle;
        HDC deviceContext;
        HGLRC renderContext;
    };
} PlatformSpecific;

typedef struct window_State {
    
    b32 running;
    b32 closeRequested;
    u32 hasFocus;
    s32 x;
    s32 y;
    u32 width;
    u32 height;
    b32 resized;
    u32 screenWidth;
    u32 screenHeight;
    u8 keys[ 256 ];
    u8 scancodes[ 256 ];
    u32 characters[ 32 ];
    u32 characterCount;
    s32 mouseX;
    s32 mouseY;
    PlatformSpecific platform;
} window_State;

enum input_Key {
    
    key_none,
    
    key_mouseLeft,
    key_mouseRight,
    key_mouseMidle,
    key_mouse_4,
    key_mouse_5,
    key_cancel,
    key_backspace,
    key_tab,
    key_clear,
    key_return,
    key_shift,
    key_control,
    key_alt,
    key_pause,
    key_capsLock,
    key_kana,
    key_hangul,
    key_junja,
    key_final,
    key_hanja,
    key_kanji,
    key_escape,
    key_convert,
    key_nonConvert,
    key_accept,
    key_modeChange,
    key_space,
    key_pageUp,
    key_pageDown,
    key_end,
    key_home,
    key_left,
    key_up,
    key_right,
    key_down,
    key_select,
    key_print,
    key_execute,
    key_printScreen,
    key_insert,
    key_delete,
    key_help,
    
    key_0,
    key_1,
    key_2,
    key_3,
    key_4,
    key_5,
    key_6,
    key_7,
    key_8,
    key_9,
    
    key_a,
    key_b,
    key_c,
    key_d,
    key_e,
    key_f,
    key_g,
    key_h,
    key_i,
    key_j,
    key_k,
    key_l,
    key_m,
    key_n,
    key_o,
    key_p,
    key_q,
    key_r,
    key_s,
    key_t,
    key_u,
    key_v,
    key_w,
    key_x,
    key_y,
    key_z,
    
    key_leftMeta,
    key_rightMeta,
    key_application,
    key_sleep,
    key_numpad_0,
    key_numpad_1,
    key_numpad_2,
    key_numpad_3,
    key_numpad_4,
    key_numpad_5,
    key_numpad_6,
    key_numpad_7,
    key_numpad_8,
    key_numpad_9,
    
    key_multiply,
    key_divide,
    key_add,
    key_subtract,
    key_separator,
    key_decimal,
    
    key_f1,
    key_f2,
    key_f3,
    key_f4,
    key_f5,
    key_f6,
    key_f7,
    key_f8,
    key_f9,
    key_f10,
    key_f11,
    key_f12,
    key_f13,
    key_f14,
    key_f15,
    key_f16,
    key_f17,
    key_f18,
    key_f19,
    key_f20,
    key_f21,
    key_f22,
    key_f23,
    key_f24,
    
    key_numLock,
    key_scrollLock,
    key_leftShift,
    key_rightShift,
    key_leftControl,
    key_rightControl,
    key_leftAlt,
    key_rightAlt,
    
    key_browserBack,
    key_browserForward,
    key_browserRefresh,
    key_browserStop,
    key_browserSearch,
    key_browserFavorites,
    key_browserHome,
    key_volumeMute,
    key_volumeDown,
    key_volumeUp,
    key_mediaNext,
    key_mediaPrevious,
    key_mediaStop,
    key_mediaPlay,
    key_launchMail,
    key_launchMedia,
    key_launchApplication_1,
    key_launchApplication_2,
    
    key_oemPlus,
    key_oemMinus,
    key_oemComma,
    key_oemPeriod,
    key_oem_1,
    key_oem_2,
    key_oem_3,
    key_oem_4,
    key_oem_5,
    key_oem_6,
    key_oem_7,
    key_oem_8,
    key_oem_102,
    key_oemClear,
    key_processKey,
    key_packet,
    key_attn,
    key_crsel,
    key_exsel,
    key_ereof,
    key_play,
    key_zoom,
    key_noname,
    key_pa1,
    
    key_count
};

u8 vkToKey[ 256 ] = { };
u8 keyToVk[ 256 ] = { };

void input_vkToKey( ) {
    
#define vkKeyMapping( vk, key ) vkToKey[ vk ] = key; keyToVk[ key ] = vk;
    
    vkKeyMapping( VK_LBUTTON, key_mouseLeft );
    vkKeyMapping( VK_RBUTTON, key_mouseRight );
    vkKeyMapping( VK_MBUTTON, key_mouseMidle );
    vkKeyMapping( VK_XBUTTON1, key_mouse_4 );
    vkKeyMapping( VK_XBUTTON2, key_mouse_5 );
    vkKeyMapping( VK_CANCEL, key_cancel );
    vkKeyMapping( VK_BACK, key_backspace );
    vkKeyMapping( VK_TAB, key_tab );
    vkKeyMapping( VK_CLEAR, key_clear );
    vkKeyMapping( VK_RETURN, key_return );
    vkKeyMapping( VK_SHIFT, key_shift );
    vkKeyMapping( VK_CONTROL, key_control );
    vkKeyMapping( VK_MENU, key_alt );
    vkKeyMapping( VK_PAUSE, key_pause );
    vkKeyMapping( VK_CAPITAL, key_capsLock );
    vkKeyMapping( VK_KANA, key_kana );
    vkKeyMapping( VK_HANGUL, key_hangul );
    vkKeyMapping( VK_JUNJA, key_junja );
    vkKeyMapping( VK_FINAL, key_final );
    vkKeyMapping( VK_HANJA, key_hanja );
    vkKeyMapping( VK_KANJI, key_kanji );
    vkKeyMapping( VK_ESCAPE, key_escape );
    vkKeyMapping( VK_CONVERT, key_convert );
    vkKeyMapping( VK_NONCONVERT, key_nonConvert );
    vkKeyMapping( VK_ACCEPT, key_accept );
    vkKeyMapping( VK_MODECHANGE, key_modeChange );
    vkKeyMapping( VK_SPACE, key_space );
    vkKeyMapping( VK_PRIOR, key_pageUp  );
    vkKeyMapping( VK_NEXT, key_pageDown );
    vkKeyMapping( VK_END, key_end );
    vkKeyMapping( VK_HOME, key_home );
    vkKeyMapping( VK_LEFT, key_left );
    vkKeyMapping( VK_UP, key_up );
    vkKeyMapping( VK_RIGHT, key_right );
    vkKeyMapping( VK_DOWN, key_down );
    vkKeyMapping( VK_SELECT, key_select );
    vkKeyMapping( VK_PRINT, key_print );
    vkKeyMapping( VK_EXECUTE, key_execute );
    vkKeyMapping( VK_SNAPSHOT, key_printScreen );
    vkKeyMapping( VK_INSERT, key_insert );
    vkKeyMapping( VK_DELETE, key_delete );
    vkKeyMapping( VK_HELP, key_help );
    vkKeyMapping( '0', key_0 );
    vkKeyMapping( '1', key_1 );
    vkKeyMapping( '2', key_2 );
    vkKeyMapping( '3', key_3 );
    vkKeyMapping( '4', key_4 );
    vkKeyMapping( '5', key_5 );
    vkKeyMapping( '6', key_6 );
    vkKeyMapping( '7', key_7 );
    vkKeyMapping( '8', key_8 );
    vkKeyMapping( '9', key_9 );
    vkKeyMapping( 'A', key_a );
    vkKeyMapping( 'B', key_b );
    vkKeyMapping( 'C', key_c );
    vkKeyMapping( 'D', key_d );
    vkKeyMapping( 'E', key_e );
    vkKeyMapping( 'F', key_f );
    vkKeyMapping( 'G', key_g );
    vkKeyMapping( 'H', key_h );
    vkKeyMapping( 'I', key_i );
    vkKeyMapping( 'J', key_j );
    vkKeyMapping( 'K', key_k );
    vkKeyMapping( 'L', key_l );
    vkKeyMapping( 'M', key_m );
    vkKeyMapping( 'N', key_n );
    vkKeyMapping( 'O', key_o );
    vkKeyMapping( 'P', key_p );
    vkKeyMapping( 'Q', key_q );
    vkKeyMapping( 'R', key_r );
    vkKeyMapping( 'S', key_s );
    vkKeyMapping( 'T', key_t );
    vkKeyMapping( 'U', key_u );
    vkKeyMapping( 'V', key_v );
    vkKeyMapping( 'W', key_w );
    vkKeyMapping( 'X', key_x );
    vkKeyMapping( 'Y', key_y );
    vkKeyMapping( 'Z', key_z );
    vkKeyMapping( VK_LWIN, key_leftMeta );
    vkKeyMapping( VK_RWIN, key_rightMeta );
    vkKeyMapping( VK_APPS, key_application );
    vkKeyMapping( VK_SLEEP, key_sleep );
    vkKeyMapping( VK_NUMPAD0, key_numpad_0 );
    vkKeyMapping( VK_NUMPAD1, key_numpad_1 );
    vkKeyMapping( VK_NUMPAD2, key_numpad_2 );
    vkKeyMapping( VK_NUMPAD3, key_numpad_3 );
    vkKeyMapping( VK_NUMPAD4, key_numpad_4 );
    vkKeyMapping( VK_NUMPAD5, key_numpad_5 );
    vkKeyMapping( VK_NUMPAD6, key_numpad_6 );
    vkKeyMapping( VK_NUMPAD7, key_numpad_7 );
    vkKeyMapping( VK_NUMPAD8, key_numpad_8 );
    vkKeyMapping( VK_NUMPAD9, key_numpad_9 );
    vkKeyMapping( VK_MULTIPLY, key_multiply );
    vkKeyMapping( VK_DIVIDE, key_divide );
    vkKeyMapping( VK_ADD, key_add );
    vkKeyMapping( VK_SUBTRACT, key_subtract );
    vkKeyMapping( VK_SEPARATOR, key_separator );
    vkKeyMapping( VK_DECIMAL, key_decimal );
    vkKeyMapping( VK_F1, key_f1 );
    vkKeyMapping( VK_F2, key_f2 );
    vkKeyMapping( VK_F3, key_f3 );
    vkKeyMapping( VK_F4, key_f4 );
    vkKeyMapping( VK_F5, key_f5 );
    vkKeyMapping( VK_F6, key_f6 );
    vkKeyMapping( VK_F7, key_f7 );
    vkKeyMapping( VK_F8, key_f8 );
    vkKeyMapping( VK_F9, key_f9 );
    vkKeyMapping( VK_F10, key_f10 );
    vkKeyMapping( VK_F11, key_f11 );
    vkKeyMapping( VK_F12, key_f12 );
    vkKeyMapping( VK_F13, key_f13 );
    vkKeyMapping( VK_F14, key_f14 );
    vkKeyMapping( VK_F15, key_f15 );
    vkKeyMapping( VK_F16, key_f16 );
    vkKeyMapping( VK_F17, key_f17 );
    vkKeyMapping( VK_F18, key_f18 );
    vkKeyMapping( VK_F19, key_f19 );
    vkKeyMapping( VK_F20, key_f20 );
    vkKeyMapping( VK_F21, key_f21 );
    vkKeyMapping( VK_F22, key_f22 );
    vkKeyMapping( VK_F23, key_f23 );
    vkKeyMapping( VK_F24, key_f24 );
    vkKeyMapping( VK_NUMLOCK, key_numLock );
    vkKeyMapping( VK_SCROLL, key_scrollLock );
    vkKeyMapping( VK_LSHIFT, key_leftShift );
    vkKeyMapping( VK_RSHIFT, key_rightShift );
    vkKeyMapping( VK_LCONTROL, key_leftControl );
    vkKeyMapping( VK_RCONTROL, key_rightControl );
    vkKeyMapping( VK_LMENU, key_leftAlt );
    vkKeyMapping( VK_RMENU, key_rightAlt );
    
    vkKeyMapping( VK_BROWSER_BACK, key_browserBack );
    vkKeyMapping( VK_BROWSER_FORWARD, key_browserForward );
    vkKeyMapping( VK_BROWSER_REFRESH, key_browserRefresh );
    vkKeyMapping( VK_BROWSER_STOP, key_browserStop );
    vkKeyMapping( VK_BROWSER_SEARCH, key_browserSearch );
    vkKeyMapping( VK_BROWSER_FAVORITES, key_browserFavorites );
    vkKeyMapping( VK_BROWSER_HOME, key_browserHome );
    vkKeyMapping( VK_VOLUME_MUTE, key_volumeMute );
    vkKeyMapping( VK_VOLUME_DOWN, key_volumeDown );
    vkKeyMapping( VK_VOLUME_UP, key_volumeUp );
    vkKeyMapping( VK_MEDIA_NEXT_TRACK, key_mediaNext );
    vkKeyMapping( VK_MEDIA_PREV_TRACK, key_mediaPrevious );
    vkKeyMapping( VK_MEDIA_STOP, key_mediaStop );
    vkKeyMapping( VK_MEDIA_PLAY_PAUSE, key_mediaPlay );
    vkKeyMapping( VK_LAUNCH_MAIL, key_launchMail );
    vkKeyMapping( VK_LAUNCH_MEDIA_SELECT, key_launchMedia );
    vkKeyMapping( VK_LAUNCH_APP1, key_launchApplication_1 );
    vkKeyMapping( VK_LAUNCH_APP2, key_launchApplication_2 );
    vkKeyMapping( VK_OEM_PLUS, key_oemPlus );
    vkKeyMapping( VK_OEM_COMMA, key_oemComma );
    vkKeyMapping( VK_OEM_MINUS, key_oemMinus );
    vkKeyMapping( VK_OEM_PERIOD, key_oemPeriod );
    vkKeyMapping( VK_OEM_1, key_oem_1 );
    vkKeyMapping( VK_OEM_2, key_oem_2 );
    vkKeyMapping( VK_OEM_3, key_oem_3 );
    vkKeyMapping( VK_OEM_4, key_oem_4 );
    vkKeyMapping( VK_OEM_5, key_oem_5 );
    vkKeyMapping( VK_OEM_6, key_oem_6 );
    vkKeyMapping( VK_OEM_7, key_oem_7 );
    vkKeyMapping( VK_OEM_8, key_oem_8 );
    vkKeyMapping( VK_OEM_102, key_oem_102 );
    vkKeyMapping( VK_OEM_CLEAR, key_oemClear );
    vkKeyMapping( VK_PROCESSKEY, key_processKey );
    vkKeyMapping( VK_PACKET, key_packet );
    vkKeyMapping( VK_ATTN, key_attn );
    vkKeyMapping( VK_CRSEL, key_crsel );
    vkKeyMapping( VK_EXSEL, key_exsel );
    vkKeyMapping( VK_EREOF, key_ereof );
    vkKeyMapping( VK_PLAY, key_play );
    vkKeyMapping( VK_ZOOM, key_zoom );
    vkKeyMapping( VK_NONAME, key_noname );
    vkKeyMapping( VK_PA1, key_pa1 );
    
#undef vkKeyMapping
}

enum input_Scancode {
    
    sc_escape = 0x01,
    sc_1 = 0x02,
    sc_2 = 0x03,
    sc_3 = 0x04,
    sc_4 = 0x05,
    sc_5 = 0x06,
    sc_6 = 0x07,
    sc_7 = 0x08,
    sc_8 = 0x09,
    sc_9 = 0x0A,
    sc_0 = 0x0B,
    sc_minus = 0x0C,
    sc_equals = 0x0D,
    sc_backspace = 0x0E,
    sc_tab = 0x0F,
    sc_q = 0x10,
    sc_w = 0x11,
    sc_e = 0x12,
    sc_r = 0x13,
    sc_t = 0x14,
    sc_y = 0x15,
    sc_u = 0x16,
    sc_i = 0x17,
    sc_o = 0x18,
    sc_p = 0x19,
    sc_bracketLeft = 0x1A,
    sc_bracketRight = 0x1B,
    sc_enter = 0x1C,
    sc_controlLeft = 0x1D,
    sc_a = 0x1E,
    sc_s =0x1F,
    sc_d = 0x20,
    sc_f = 0x21,
    sc_g = 0x22,
    sc_h = 0x23,
    sc_j = 0x24,
    sc_k = 0x25,
    sc_l = 0x26,
    sc_semicolon = 0x27,
    sc_apostrophe = 0x28,
    sc_grave = 0x29,
    sc_shiftLeft = 0x2A,
    sc_backslash = 0x2B,
    sc_z = 0x2C,
    sc_x = 0x2D,
    sc_c = 0x2E,
    sc_v = 0x2F,
    sc_b = 0x30,
    sc_n = 0x31,
    sc_m = 0x32,
    sc_comma = 0x33,
    sc_preiod = 0x34,
    sc_slash = 0x35,
    sc_shiftRight = 0x36,
    sc_numpad_multiply = 0x37,
    sc_altLeft = 0x38,
    sc_space = 0x39,
    sc_capsLock = 0x3A,
    sc_f1 = 0x3B,
    sc_f2 = 0x3C,
    sc_f3 = 0x3D,
    sc_f4 = 0x3E,
    sc_f5 = 0x3F,
    sc_f6 = 0x40,
    sc_f7 = 0x41,
    sc_f8 = 0x42,
    sc_f9 = 0x43,
    sc_f10 = 0x44,
    sc_numLock = 0x45,
    sc_scrollLock = 0x46,
    sc_numpad_7 = 0x47,
    sc_numpad_8 = 0x48,
    sc_numpad_9 = 0x49,
    sc_numpad_minus = 0x4A,
    sc_numpad_4 = 0x4B,
    sc_numpad_5 = 0x4C,
    sc_numpad_6 = 0x4D,
    sc_numpad_plus = 0x4E,
    sc_numpad_1 = 0x4F,
    sc_numpad_2 = 0x50,
    sc_numpad_3 = 0x51,
    sc_numpad_0 = 0x52,
    sc_numpad_period = 0x53,
    sc_alt_printScreen = 0x54, /* Alt + print screen. MapVirtualKeyEx( VK_SNAPSHOT, MAPVK_VK_TO_VSC_EX, 0 ) returns scancode 0x54. */
    sc_bracketAngle = 0x56, /* Key between the left shift and Z. */
    sc_f11 = 0x57,
    sc_f12 = 0x58,
    sc_oem_1 = 0x5a, /* VK_OEM_WSCTRL */
    sc_oem_2 = 0x5b, /* VK_OEM_FINISH */
    sc_oem_3 = 0x5c, /* VK_OEM_JUMP */
    sc_eraseEOF = 0x5d,
    sc_oem_4 = 0x5e, /* VK_OEM_BACKTAB */
    sc_oem_5 = 0x5f, /* VK_OEM_AUTO */
    sc_zoom = 0x62,
    sc_help = 0x63,
    sc_f13 = 0x64,
    sc_f14 = 0x65,
    sc_f15 = 0x66,
    sc_f16 = 0x67,
    sc_f17 = 0x68,
    sc_f18 = 0x69,
    sc_f19 = 0x6a,
    sc_f20 = 0x6b,
    sc_f21 = 0x6c,
    sc_f22 = 0x6d,
    sc_f23 = 0x6e,
    sc_oem_6 = 0x6f, /* VK_OEM_PA3 */
    sc_katakana = 0x70,
    sc_oem_7 = 0x71, /* VK_OEM_RESET */
    sc_f24 = 0x76,
    sc_sbcschar = 0x77,
    sc_convert = 0x79,
    sc_nonconvert = 0x7B, /* VK_OEM_PA1 */
    
    sc_media_previous = 0xE010,
    sc_media_next = 0xE019,
    sc_numpad_enter = 0xE01C,
    sc_controlRight = 0xE01D,
    sc_volume_mute = 0xE020,
    sc_launch_app2 = 0xE021,
    sc_media_play = 0xE022,
    sc_media_stop = 0xE024,
    sc_volume_down = 0xE02E,
    sc_volume_up = 0xE030,
    sc_browser_home = 0xE032,
    sc_numpad_divide = 0xE035,
    sc_printScreen = 0xE037,
    /*
    sc_printScreen:
    - make: 0xE02A 0xE037
    - break: 0xE0B7 0xE0AA
    - MapVirtualKeyEx( VK_SNAPSHOT, MAPVK_VK_TO_VSC_EX, 0 ) returns scancode 0x54;
    - There is no VK_KEYDOWN with VK_SNAPSHOT.
    */
    sc_altRight = 0xE038,
    sc_cancel = 0xE046, /* CTRL + Pause */
    sc_home = 0xE047,
    sc_arrowUp = 0xE048,
    sc_pageUp = 0xE049,
    sc_arrowLeft = 0xE04B,
    sc_arrowRight = 0xE04D,
    sc_end = 0xE04F,
    sc_arrowDown = 0xE050,
    sc_pageDown = 0xE051,
    sc_insert = 0xE052,
    sc_delete = 0xE053,
    sc_metaLeft = 0xE05B,
    sc_metaRight = 0xE05C,
    sc_application = 0xE05D,
    sc_power = 0xE05E,
    sc_sleep = 0xE05F,
    sc_wake = 0xE063,
    sc_browser_search = 0xE065,
    sc_browser_favorites = 0xE066,
    sc_browser_refresh = 0xE067,
    sc_browser_stop = 0xE068,
    sc_browser_forward = 0xE069,
    sc_browser_back = 0xE06A,
    sc_launch_app1 = 0xE06B,
    sc_launch_email = 0xE06C,
    sc_launch_media = 0xE06D,
    
    sc_pause = 0xE11D45,
    /*
    sc_pause:
    - make: 0xE11D 45 0xE19D C5
    - make in raw input: 0xE11D 0x45
    - break: none
    - No repeat when you hold the key down
    - There are no break so I don't know how the key down/up is expected to work. Raw input sends "keydown" and "keyup" messages, and it appears that the keyup message is sent directly after the keydown message (you can't hold the key down) so depending on when GetMessage or PeekMessage will return messages, you may get both a keydown and keyup message "at the same time". If you use VK messages most of the time you only get keydown messages, but some times you get keyup messages too.
    - when pressed at the same time as one or both control keys, generates a 0xE046 (sc_cancel) and the string for that scancode is "break".
    */
};

u32 input_scancodeList[ ] = {
    
    sc_escape,
    sc_1,
    sc_2,
    sc_3,
    sc_4,
    sc_5,
    sc_6,
    sc_7,
    sc_8,
    sc_9,
    sc_0,
    sc_minus,
    sc_equals,
    sc_backspace,
    sc_tab,
    sc_q,
    sc_w,
    sc_e,
    sc_r,
    sc_t,
    sc_y,
    sc_u,
    sc_i,
    sc_o,
    sc_p,
    sc_bracketLeft,
    sc_bracketRight,
    sc_enter,
    sc_controlLeft,
    sc_a,
    sc_s,
    sc_d,
    sc_f,
    sc_g,
    sc_h,
    sc_j,
    sc_k,
    sc_l,
    sc_semicolon,
    sc_apostrophe,
    sc_grave,
    sc_shiftLeft,
    sc_backslash,
    sc_z,
    sc_x,
    sc_c,
    sc_v,
    sc_b,
    sc_n,
    sc_m,
    sc_comma,
    sc_preiod,
    sc_slash,
    sc_shiftRight,
    sc_numpad_multiply,
    sc_altLeft,
    sc_space,
    sc_capsLock,
    sc_f1,
    sc_f2,
    sc_f3,
    sc_f4,
    sc_f5,
    sc_f6,
    sc_f7,
    sc_f8,
    sc_f9,
    sc_f10,
    sc_numLock,
    sc_scrollLock,
    sc_numpad_7,
    sc_numpad_8,
    sc_numpad_9,
    sc_numpad_minus,
    sc_numpad_4,
    sc_numpad_5,
    sc_numpad_6,
    sc_numpad_plus,
    sc_numpad_1,
    sc_numpad_2,
    sc_numpad_3,
    sc_numpad_0,
    sc_numpad_period,
    sc_alt_printScreen,
    sc_bracketAngle,
    sc_f11,
    sc_f12,
    sc_oem_1,
    sc_oem_2,
    sc_oem_3,
    sc_eraseEOF,
    sc_oem_4,
    sc_oem_5,
    sc_zoom,
    sc_help,
    sc_f13,
    sc_f14,
    sc_f15,
    sc_f16,
    sc_f17,
    sc_f18,
    sc_f19,
    sc_f20,
    sc_f21,
    sc_f22,
    sc_f23,
    sc_oem_6,
    sc_katakana,
    sc_oem_7,
    sc_f24,
    sc_sbcschar,
    sc_convert,
    sc_nonconvert,
    
    sc_media_previous,
    sc_media_next,
    sc_numpad_enter,
    sc_controlRight,
    sc_volume_mute,
    sc_launch_app2,
    sc_media_play,
    sc_media_stop,
    sc_volume_down,
    sc_volume_up,
    sc_browser_home,
    sc_numpad_divide,
    sc_printScreen,
    sc_altRight,
    sc_cancel,
    sc_home,
    sc_arrowUp,
    sc_pageUp,
    sc_arrowLeft,
    sc_arrowRight,
    sc_end,
    sc_arrowDown,
    sc_pageDown,
    sc_insert,
    sc_delete,
    sc_metaLeft,
    sc_metaRight,
    sc_application,
    sc_power,
    sc_sleep,
    sc_wake,
    sc_browser_search,
    sc_browser_favorites,
    sc_browser_refresh,
    sc_browser_stop,
    sc_browser_forward,
    sc_browser_back,
    sc_launch_app1,
    sc_launch_email,
    sc_launch_media,
    
    sc_pause
};

#include "glcorearb.h"

PFNGLGETSTRINGPROC glGetString;
PFNGLGETINTEGERVPROC glGetIntegerv;
PFNGLGETERRORPROC glGetError;
PFNGLCLEARCOLORPROC glClearColor;
PFNGLGENTEXTURESPROC glGenTextures;
PFNGLBINDTEXTUREPROC glBindTexture;
PFNGLTEXPARAMETERIPROC glTexParameteri;
PFNGLTEXIMAGE2DPROC glTexImage2D;
PFNGLCLEARPROC glClear;
PFNGLDRAWARRAYSPROC glDrawArrays;
PFNGLFLUSHPROC glFlush;
PFNGLPIXELSTOREIPROC glPixelStorei;
PFNGLDELETETEXTURESPROC glDeleteTextures;
PFNGLFINISHPROC glFinish;
PFNGLENABLEPROC glEnable;
PFNGLBLENDFUNCPROC glBlendFunc;
PFNGLDRAWELEMENTSPROC glDrawElements;
PFNGLDISABLEPROC glDisable;
PFNGLVIEWPORTPROC glViewport;

PFNGLGETSHADERIVPROC glGetShaderiv;
PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog;
PFNGLATTACHSHADERPROC glAttachShader;
PFNGLBINDATTRIBLOCATIONPROC glBindAttribLocation;
PFNGLCOMPILESHADERPROC glCompileShader;
PFNGLCREATEPROGRAMPROC glCreateProgram;
PFNGLCREATESHADERPROC glCreateShader;
PFNGLDELETEPROGRAMPROC glDeleteProgram;
PFNGLDELETESHADERPROC glDeleteShader;
PFNGLDETACHSHADERPROC glDetachShader;
PFNGLDISABLEVERTEXATTRIBARRAYPROC glDisableVertexAttribArray;
PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray;
PFNGLGETPROGRAMIVPROC glGetProgramiv;
PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog;
PFNGLLINKPROGRAMPROC glLinkProgram;
PFNGLSHADERSOURCEPROC glShaderSource;
PFNGLUSEPROGRAMPROC glUseProgram;
PFNGLBINDBUFFERPROC glBindBuffer;
PFNGLGENBUFFERSPROC glGenBuffers;
PFNGLBUFFERDATAPROC glBufferData;
PFNGLBUFFERSUBDATAPROC glBufferSubData;
PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer;
PFNGLBINDFRAGDATALOCATIONPROC glBindFragDataLocation;
PFNGLGETATTRIBLOCATIONPROC glGetAttribLocation;
PFNGLDELETEBUFFERSPROC glDeleteBuffers;
PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays;
PFNGLGENVERTEXARRAYSPROC glGenVertexArrays;
PFNGLBINDVERTEXARRAYPROC glBindVertexArray;
PFNGLACTIVETEXTUREPROC glActiveTexture;
PFNGLGENERATEMIPMAPPROC glGenerateMipmap;
PFNGLGETSTRINGIPROC glGetStringi;
PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation;
PFNGLUNIFORMMATRIX2X3FVPROC glUniformMatrix2x3fv;
PFNGLUNIFORMMATRIX3X4FVPROC glUniformMatrix3x4fv;
PFNGLUNIFORMMATRIX4FVPROC glUniformMatrix4fv;
PFNGLUNIFORM4FVPROC glUniform4fv;
PFNGLPRIMITIVERESTARTINDEXPROC glPrimitiveRestartIndex;

typedef BOOL ( * wglChoosePixelFormatARB_t )( HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats );
typedef HGLRC ( * wglCreateContextAttribsARB_t )( HDC hDC, HGLRC hshareContext, const int *attribList );
typedef const char * ( * wglGetExtensionsStringARB_t )( HDC hdc );
typedef void ( * wglSwapIntervalEXT_t )( int intervalCount );

wglGetExtensionsStringARB_t wglGetExtensionsStringARB = 0;
wglChoosePixelFormatARB_t wglChoosePixelFormatARB = 0;
wglCreateContextAttribsARB_t wglCreateContextAttribsARB = 0;
wglSwapIntervalEXT_t wglSwapIntervalEXT = 0;

void getWGLFunctions( void ) {
    
    wglGetExtensionsStringARB = ( wglGetExtensionsStringARB_t ) wglGetProcAddress( "wglGetExtensionsStringARB" );
    wglChoosePixelFormatARB = ( wglChoosePixelFormatARB_t ) wglGetProcAddress( "wglChoosePixelFormatARB" );
    wglCreateContextAttribsARB = ( wglCreateContextAttribsARB_t ) wglGetProcAddress( "wglCreateContextAttribsARB" );
    wglSwapIntervalEXT = ( wglSwapIntervalEXT_t ) wglGetProcAddress( "wglSwapIntervalEXT" );
    
    // _assert( wglGetExtensionsStringARB > ( void* ) 3 );
    // _assert( wglChoosePixelFormatARB > ( void* ) 3 );
    // _assert( wglCreateContextAttribsARB > ( void* ) 3 );
    // _assert( wglSwapIntervalEXT > ( void* ) 3 );
}

void window_getGLFunctions( ) {
    
    HMODULE hOpenGL = LoadLibrary( "opengl32.dll" );
    
    glGetString = ( PFNGLGETSTRINGPROC ) GetProcAddress( hOpenGL, "glGetString" );
    glGetIntegerv = ( PFNGLGETINTEGERVPROC ) GetProcAddress( hOpenGL, "glGetIntegerv" );
    glGetError = ( PFNGLGETERRORPROC ) GetProcAddress( hOpenGL, "glGetError" );
    glClearColor = ( PFNGLCLEARCOLORPROC ) GetProcAddress( hOpenGL, "glClearColor" );
    glGenTextures = ( PFNGLGENTEXTURESPROC ) GetProcAddress( hOpenGL, "glGenTextures" );
    glBindTexture = ( PFNGLBINDTEXTUREPROC ) GetProcAddress( hOpenGL, "glBindTexture" );
    glTexParameteri = ( PFNGLTEXPARAMETERIPROC ) GetProcAddress( hOpenGL, "glTexParameteri" );
    glTexImage2D = ( PFNGLTEXIMAGE2DPROC ) GetProcAddress( hOpenGL, "glTexImage2D" );
    glClear = ( PFNGLCLEARPROC ) GetProcAddress( hOpenGL, "glClear" );
    glDrawArrays = ( PFNGLDRAWARRAYSPROC ) GetProcAddress( hOpenGL, "glDrawArrays" );
    glFlush = ( PFNGLFLUSHPROC ) GetProcAddress( hOpenGL, "glFlush" );
    glPixelStorei = ( PFNGLPIXELSTOREIPROC ) GetProcAddress( hOpenGL, "glPixelStorei" );
    glDeleteTextures = ( PFNGLDELETETEXTURESPROC ) GetProcAddress( hOpenGL, "glDeleteTextures" );
    glFinish = ( PFNGLFINISHPROC ) GetProcAddress( hOpenGL, "glFinish" );
    glEnable = ( PFNGLENABLEPROC ) GetProcAddress( hOpenGL, "glEnable" );
    glBlendFunc = ( PFNGLBLENDFUNCPROC ) GetProcAddress( hOpenGL, "glBlendFunc" );
    glDrawElements = ( PFNGLDRAWELEMENTSPROC ) GetProcAddress( hOpenGL, "glDrawElements" );
    glDisable = ( PFNGLDISABLEPROC ) GetProcAddress( hOpenGL, "glDisable" );
    glViewport = ( PFNGLVIEWPORTPROC ) GetProcAddress( hOpenGL, "glViewport" );
    
    FreeLibrary( hOpenGL );
    
    glGetShaderiv = ( PFNGLGETSHADERIVPROC ) wglGetProcAddress( "glGetShaderiv" );
    glGetShaderInfoLog = ( PFNGLGETSHADERINFOLOGPROC ) wglGetProcAddress( "glGetShaderInfoLog" );
    glAttachShader = ( PFNGLATTACHSHADERPROC ) wglGetProcAddress( "glAttachShader" );
    glBindAttribLocation = ( PFNGLBINDATTRIBLOCATIONPROC ) wglGetProcAddress( "glBindAttribLocation" );
    glCompileShader = ( PFNGLCOMPILESHADERPROC ) wglGetProcAddress( "glCompileShader" );
    glCreateProgram = ( PFNGLCREATEPROGRAMPROC ) wglGetProcAddress( "glCreateProgram" );
    glCreateShader = ( PFNGLCREATESHADERPROC ) wglGetProcAddress( "glCreateShader" );
    glDeleteProgram = ( PFNGLDELETEPROGRAMPROC ) wglGetProcAddress( "glDeleteProgram" );
    glDeleteShader = ( PFNGLDELETESHADERPROC ) wglGetProcAddress( "glDeleteShader" );
    glDetachShader = ( PFNGLDETACHSHADERPROC ) wglGetProcAddress( "glDetachShader" );
    glDisableVertexAttribArray = ( PFNGLDISABLEVERTEXATTRIBARRAYPROC ) wglGetProcAddress( "glDisableVertexAttribArray" );
    glEnableVertexAttribArray = ( PFNGLENABLEVERTEXATTRIBARRAYPROC ) wglGetProcAddress( "glEnableVertexAttribArray" );
    glGetProgramiv = ( PFNGLGETPROGRAMIVPROC ) wglGetProcAddress( "glGetProgramiv" );
    glGetProgramInfoLog = ( PFNGLGETPROGRAMINFOLOGPROC ) wglGetProcAddress( "glGetProgramInfoLog" );
    glLinkProgram = ( PFNGLLINKPROGRAMPROC ) wglGetProcAddress( "glLinkProgram" );
    glShaderSource = ( PFNGLSHADERSOURCEPROC ) wglGetProcAddress( "glShaderSource" );
    glUseProgram = ( PFNGLUSEPROGRAMPROC ) wglGetProcAddress( "glUseProgram" );
    glBindBuffer = ( PFNGLBINDBUFFERPROC ) wglGetProcAddress( "glBindBuffer" );
    glGenBuffers = ( PFNGLGENBUFFERSPROC ) wglGetProcAddress( "glGenBuffers" );
    glBufferData = ( PFNGLBUFFERDATAPROC ) wglGetProcAddress( "glBufferData" );
    glBufferSubData = ( PFNGLBUFFERSUBDATAPROC ) wglGetProcAddress( "glBufferSubData" );
    glVertexAttribPointer = ( PFNGLVERTEXATTRIBPOINTERPROC ) wglGetProcAddress( "glVertexAttribPointer" );
    glBindFragDataLocation = ( PFNGLBINDFRAGDATALOCATIONPROC ) wglGetProcAddress( "glBindFragDataLocation" );
    glGetAttribLocation = ( PFNGLGETATTRIBLOCATIONPROC ) wglGetProcAddress( "glGetAttribLocation" );
    glDeleteBuffers = ( PFNGLDELETEBUFFERSPROC ) wglGetProcAddress( "glDeleteBuffers" );
    glDeleteVertexArrays = ( PFNGLDELETEVERTEXARRAYSPROC ) wglGetProcAddress( "glDeleteVertexArrays" );
    glGenVertexArrays = ( PFNGLGENVERTEXARRAYSPROC ) wglGetProcAddress( "glGenVertexArrays" );
    glBindVertexArray = ( PFNGLBINDVERTEXARRAYPROC ) wglGetProcAddress( "glBindVertexArray" );
    glActiveTexture = ( PFNGLACTIVETEXTUREPROC ) wglGetProcAddress( "glActiveTexture" );
    glGenerateMipmap = ( PFNGLGENERATEMIPMAPPROC ) wglGetProcAddress( "glGenerateMipmap" );
    glGetStringi = ( PFNGLGETSTRINGIPROC ) wglGetProcAddress( "glGetStringi" );
    glGetUniformLocation = ( PFNGLGETUNIFORMLOCATIONPROC ) wglGetProcAddress( "glGetUniformLocation" );
    glUniformMatrix2x3fv = ( PFNGLUNIFORMMATRIX2X3FVPROC ) wglGetProcAddress( "glUniformMatrix2x3fv" );
    glUniformMatrix3x4fv = ( PFNGLUNIFORMMATRIX3X4FVPROC ) wglGetProcAddress( "glUniformMatrix3x4fv" );
    glUniformMatrix4fv = ( PFNGLUNIFORMMATRIX4FVPROC ) wglGetProcAddress( "glUniformMatrix4fv" );
    glUniform4fv = ( PFNGLUNIFORM4FVPROC ) wglGetProcAddress( "glUniform4fv" );
    glPrimitiveRestartIndex = ( PFNGLPRIMITIVERESTARTINDEXPROC ) wglGetProcAddress( "glPrimitiveRestartIndex" );
}

#define WGL_NUMBER_PIXEL_FORMATS_ARB            0x2000
#define WGL_DRAW_TO_WINDOW_ARB                  0x2001
#define WGL_DRAW_TO_BITMAP_ARB                  0x2002
#define WGL_ACCELERATION_ARB                    0x2003
#define WGL_NEED_PALETTE_ARB                    0x2004
#define WGL_NEED_SYSTEM_PALETTE_ARB             0x2005
#define WGL_SWAP_LAYER_BUFFERS_ARB              0x2006
#define WGL_SWAP_METHOD_ARB                     0x2007
#define WGL_NUMBER_OVERLAYS_ARB                 0x2008
#define WGL_NUMBER_UNDERLAYS_ARB                0x2009
#define WGL_TRANSPARENT_ARB                     0x200A
#define WGL_TRANSPARENT_RED_VALUE_ARB           0x2037
#define WGL_TRANSPARENT_GREEN_VALUE_ARB         0x2038
#define WGL_TRANSPARENT_BLUE_VALUE_ARB          0x2039
#define WGL_TRANSPARENT_ALPHA_VALUE_ARB         0x203A
#define WGL_TRANSPARENT_INDEX_VALUE_ARB         0x203B
#define WGL_SHARE_DEPTH_ARB                     0x200C
#define WGL_SHARE_STENCIL_ARB                   0x200D
#define WGL_SHARE_ACCUM_ARB                     0x200E
#define WGL_SUPPORT_GDI_ARB                     0x200F
#define WGL_SUPPORT_OPENGL_ARB                  0x2010
#define WGL_DOUBLE_BUFFER_ARB                   0x2011
#define WGL_STEREO_ARB                          0x2012
#define WGL_PIXEL_TYPE_ARB                      0x2013
#define WGL_COLOR_BITS_ARB                      0x2014
#define WGL_RED_BITS_ARB                        0x2015
#define WGL_RED_SHIFT_ARB                       0x2016
#define WGL_GREEN_BITS_ARB                      0x2017
#define WGL_GREEN_SHIFT_ARB                     0x2018
#define WGL_BLUE_BITS_ARB                       0x2019
#define WGL_BLUE_SHIFT_ARB                      0x201A
#define WGL_ALPHA_BITS_ARB                      0x201B
#define WGL_ALPHA_SHIFT_ARB                     0x201C
#define WGL_ACCUM_BITS_ARB                      0x201D
#define WGL_ACCUM_RED_BITS_ARB                  0x201E
#define WGL_ACCUM_GREEN_BITS_ARB                0x201F
#define WGL_ACCUM_BLUE_BITS_ARB                 0x2020
#define WGL_ACCUM_ALPHA_BITS_ARB                0x2021
#define WGL_DEPTH_BITS_ARB                      0x2022
#define WGL_STENCIL_BITS_ARB                    0x2023
#define WGL_AUX_BUFFERS_ARB                     0x2024

#define WGL_NO_ACCELERATION_ARB                 0x2025
#define WGL_GENERIC_ACCELERATION_ARB            0x2026
#define WGL_FULL_ACCELERATION_ARB               0x2027

#define WGL_SWAP_EXCHANGE_ARB                   0x2028
#define WGL_SWAP_COPY_ARB                       0x2029
#define WGL_SWAP_UNDEFINED_ARB                  0x202A

#define WGL_TYPE_RGBA_ARB                       0x202B
#define WGL_TYPE_COLORINDEX_ARB                 0x202C

#define WGL_CONTEXT_MAJOR_VERSION_ARB           0x2091
#define WGL_CONTEXT_MINOR_VERSION_ARB           0x2092
#define WGL_CONTEXT_LAYER_PLANE_ARB             0x2093
#define WGL_CONTEXT_FLAGS_ARB                   0x2094
#define WGL_CONTEXT_PROFILE_MASK_ARB            0x9126

#define WGL_CONTEXT_DEBUG_BIT_ARB               0x0001
#define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB  0x0002

#define WGL_CONTEXT_CORE_PROFILE_BIT_ARB        0x00000001
#define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002

#define ERROR_INVALID_VERSION_ARB               0x2095
#define ERROR_INVALID_PROFILE_ARB               0x2096

umm input_getScancodeOffset( u32 scancode ) {
    
    umm result = scancode;
    umm group_0_end = sc_nonconvert;
    umm group_1_start = sc_media_previous;
    umm group_1_end = sc_launch_media;
    umm group_2_start = sc_pause;
    
    if ( scancode >= group_2_start ) {
        result = group_0_end + 1 + ( group_1_end - group_1_start ) + 1 + ( scancode - group_2_start );
    } else if ( scancode >= group_1_start ) {
        result = group_0_end + 1 + ( scancode - group_1_start );
    }
    
    // _assert( result <= 0xff );
    
    return result;
}

enum input_KeyStateFlag {
    
    input_KeyStateFlag_pressed = 1 << 0,
    input_KeyStateFlag_transitionCountMask = 0xfe
};

void input_syncKeys( window_State* state ) {
    
    umm index;
    state->keys[ key_none ] = 0;
    
    for ( index = key_mouseLeft; index < key_pa1; index++ ) {
        
        u16 keyState = GetAsyncKeyState( keyToVk[ index ] );
        state->keys[ index ] = ( ( keyState & ( 0x1 << 15 ) ) > 0 ) ? input_KeyStateFlag_pressed : 0;
    }
    
    for ( index = 0; index < arrayCount( input_scancodeList ); index++ ) {
        
        u32 scancode = input_scancodeList[ index ];
        umm offset;
        u32 vk;
        u16 keyState;
        
        if ( scancode == 0x45 ) {
            scancode = 0xE045;
        } else if ( scancode == 0xE11D45 ) {
            scancode = 0x45;
        }
        
        offset = input_getScancodeOffset( scancode );
        vk = MapVirtualKeyEx( scancode, MAPVK_VSC_TO_VK_EX, 0 );
        keyState = GetAsyncKeyState( vk );
        
        state->scancodes[ offset ] = ( ( keyState & ( 0x1 << 15 ) ) > 0 ) ? input_KeyStateFlag_pressed : 0;
    }
    
    state->characterCount = 0;
}

void input_clearKeys( window_State* state ) {
    
    umm key, scancode;
    
    for ( key = 0; key < key_count; key++ ) {
        state->keys[ key ] = ( state->keys[ key ] & input_KeyStateFlag_pressed ) << 1;
    }
    
    for ( scancode = 0; scancode < arrayCount( state->scancodes ); scancode++ ) {
        state->scancodes[ scancode ] = ( state->scancodes[ scancode ] & input_KeyStateFlag_pressed ) << 1;
    }
    
    state->characterCount = 0;
}

LRESULT CALLBACK windowProc( HWND window, UINT message, WPARAM wParam, LPARAM lParam ) {
    
    LRESULT result = 0;
    window_State* state = ( window_State* ) GetWindowLongPtr( window, 0 );
    
    switch ( message ) {
        
        // NOTE simon: Not caught by PeekMessage.
        
        case WM_DESTROY :
        case WM_CLOSE : {
            state->closeRequested = true;
        } break;
        
        // NOTE simon: WM_SIZE and WM_MOVE will not be called if we don't call DefWIndowProc with WM_WINDOWPOSCHANGED. WM_SIZE and  WM_MOVE will be called a startup only.
        case WM_WINDOWPOSCHANGED :
        case WM_MOVE :
        case WM_SIZE : {
            
            RECT clientRect = { };
            GetClientRect( window, &clientRect );
            state->width = clientRect.right;
            state->height = clientRect.bottom;
            state->resized = true;
            
            POINT p;
            p.x = 0;
            p.y = state->height;
            ClientToScreen( window, &p );
            
            state->x = p.x;
            state->y = state->screenHeight - p.y;
            
        } break;
        
        case WM_SYSCOMMAND: {
            
            // NOTE simon: Remove beeping sound when ALT + some key is pressed.
            if ( wParam == SC_KEYMENU ) {
                result = 0;
            } else {
                result = DefWindowProc( window, message, wParam, lParam );
            }
        } break;
        
        case WM_SETFOCUS: {
            input_syncKeys( state );
            state->hasFocus = true;
            result = 0;
        } break;
        
        case WM_KILLFOCUS: {
            input_clearKeys( state );
            state->hasFocus = false;
            result = 0;
        } break;
        
        // NOTE simon: End of not caught by PeekMessage.
        
        default : {
            result = DefWindowProc( window, message, wParam, lParam );
        } break;
    }
    
    return result;
}

void cleanUpWindow( HGLRC* renderContext, HWND* windowHandle, HDC* deviceContext ) {
    
    if ( renderContext != 0 && *renderContext != 0 ) {
        wglMakeCurrent( 0, 0 );
        wglDeleteContext( *renderContext );
        *renderContext = 0;
    }
    
    if ( windowHandle != 0 && *windowHandle != 0 ) {
        
        if ( deviceContext != 0 && *deviceContext != 0 ){
            ReleaseDC( *windowHandle, *deviceContext );
            *deviceContext = 0;
        }
        
        DestroyWindow( *windowHandle );
        *windowHandle = 0;
    }
}

#define mouseButtonDown( key ) \
u8 value = ( u8 ) ( state->keys[ key ] & input_KeyStateFlag_transitionCountMask ); \
value += 2; \
value |= 1; \
state->keys[ key ] = value;

#define mouseButtonUp( key ) \
u8 value = ( u8 ) ( state->keys[ key ] & input_KeyStateFlag_transitionCountMask ); \
value += 2; \
state->keys[ key ] = value;

#define mouseButton_4_5( key ) \
if ( HIWORD( message.wParam ) == XBUTTON1 ) { \
    key = key_mouse_4; \
} else if ( HIWORD( message.wParam ) == XBUTTON2 ) { \
    key = key_mouse_5; \
}

#define handleMouseButton( messagePrefix, key ) \
case WM_##messagePrefix##BUTTONDOWN: { \
    mouseButtonDown( key ); \
} break; \
case WM_##messagePrefix##BUTTONUP: { \
    mouseButtonUp( key ); \
} break;

void window_handleMessages( window_State* state ) {
    
    state->characterCount = 0;
    
    // NOTE simon: We need to set the wasPressed flag manually because if you hold a key
    // you only receive keydown messages at intervals (eg: text repeating).
    // We also need to clear the wasPressed flag (key released 2 frames ago).
    for ( umm key = 0; key < key_count; key++ ) {
        state->keys[ key ] &= input_KeyStateFlag_pressed;
    }
    
    for ( umm scancode = 0; scancode < arrayCount( state->scancodes ); scancode++ ) {
        state->scancodes[ scancode ] &= input_KeyStateFlag_pressed;
    }
    
    POINT p;
    GetCursorPos( &p );
    state->mouseX = p.x - state->x;
    state->mouseY = state->screenHeight - 1 - p.y - state->y;
    
    b32 pauseScancodeRead = false;
    
    MSG message;
    
    while ( PeekMessage( &message, 0, 0, 0, PM_REMOVE ) ) {
        
        switch ( message.message ) {
            
            /* NOTE simon: WM_QUIT only happens if PostQuitMessage is called. */
            case WM_QUIT : {
                state->closeRequested = true;
            } break;
            
            handleMouseButton( L, key_mouseLeft );
            handleMouseButton( R, key_mouseRight );
            handleMouseButton( M, key_mouseMidle );
            
            case WM_XBUTTONDOWN: {
                
                u32 key = 0;
                mouseButton_4_5( key );
                mouseButtonDown( key );
                
            } break;
            
            case WM_XBUTTONUP: {
                
                u32 key = 0;
                mouseButton_4_5( key );
                mouseButtonUp( key );
                
            } break;
            
            case WM_SYSKEYDOWN :
            case WM_KEYDOWN :
            case WM_SYSKEYUP :
            case WM_KEYUP: {
                
                u32 key = vkToKey[ message.wParam ];
                
                u8 pressed = ( u8 ) ( ( ~message.lParam ) >> 31 ) & 0x1;
                u8 transition = ( state->keys[ key ] & input_KeyStateFlag_pressed ) != pressed;
                u8 value = state->keys[ key ] & input_KeyStateFlag_transitionCountMask;
                
                b32 extended = ( message.lParam >> 24 ) & 0x1;
                u32 scancode = ( message.lParam >> 16 ) & 0xff;
                
                if ( extended ) {
                    
                    /* Num lock is extended in the lparam but not in the scancode list. */
                    if ( scancode != 0x45 ) {
                        scancode |= 0xE000;
                    }
                    
                } else {
                    
                    /* And Pause in not extended when it should be 0xE11D45. */
                    if ( scancode == 0x45 ) {
                        scancode = 0xE11D45;
                    } else if ( scancode == 0x54 ) { /* ALT + print screen */
                        scancode = 0xE037;
                    }
                }
                
                /* We need to force the transition because print screen doesn't sends keydown messages. */
                if ( scancode == 0xE037 ) {
                    transition = 1;
                }
                
                value += ( transition << 1 );
                value |= pressed;
                state->keys[ key ] = value;
                
                /* state->scancodes[ window_getScancodeOffset( scancode ) ] = value; */
                
                if ( message.wParam == VK_SHIFT ) {
                    
                    key = vkToKey[ ( scancode == sc_shiftLeft ) ? VK_LSHIFT : VK_RSHIFT ];
                    state->keys[ key ] = value;
                    
                } else if ( message.wParam == VK_CONTROL) {
                    
                    key = vkToKey[ ( extended ) ? VK_RCONTROL : VK_LCONTROL ];
                    state->keys[ key ] = value;
                    
                } else if ( message.wParam == VK_MENU ) {
                    
                    key = vkToKey[ ( extended ) ? VK_RMENU : VK_LMENU ];
                    state->keys[ key ] = value;
                }
                
                if ( message.message == WM_SYSKEYUP && message.wParam == VK_F4 ) {
                    state->closeRequested = true;
                }
                
                TranslateMessage( &message );
                
            } break;
            
            case WM_INPUT: {
                
                RAWINPUT rawInput;
                u32 rawInputSize = sizeof( rawInput );
                GetRawInputData( ( HRAWINPUT ) message.lParam, RID_INPUT, &rawInput, &rawInputSize, sizeof( RAWINPUTHEADER ) );
                
                if ( rawInput.header.dwType == RIM_TYPEKEYBOARD ) {
                    
                    u32 scancode = rawInput.data.keyboard.MakeCode;
                    u16 flags = rawInput.data.keyboard.Flags;
                    // _assert( scancode <= 0xff );
                    
                    u8 pressed = 0;
                    
                    if ( ( flags & RI_KEY_BREAK ) == 0 ) {
                        pressed = 1;
                    }
                    
                    if ( ( flags & RI_KEY_E0 ) != 0 ) {
                        scancode |= 0xE000;
                    } else if ( ( flags & RI_KEY_E1 ) != 0 ) {
                        scancode |= 0xE100;
                    }
                    
                    b32 ignore = false;
                    
                    if ( pauseScancodeRead ) {
                        
                        if ( scancode == 0x45 ) {
                            scancode = 0xE11D45;
                        }
                        
                        pauseScancodeRead = false;
                        
                    } else if ( scancode == 0xE11D ) {
                        
                        pauseScancodeRead = true;
                        
                    } else if ( scancode == 0x54 ) {
                        /* 0x54 is generated when print screen and one or both alt are pressed. */
                        scancode = 0xE037;
                    }
                    
                    if ( scancode == 0xE11D || scancode == 0xE02A || scancode == 0xE0AA || scancode == 0xE0B6 || scancode == 0xE036 ) {
                        ignore = true;
                    }
                    
                    if ( !ignore ) {
                        
                        umm offset = input_getScancodeOffset( scancode );
                        u8 value = state->scancodes[ offset ] & input_KeyStateFlag_transitionCountMask;
                        u8 transition = ( state->scancodes[ offset ] & input_KeyStateFlag_pressed ) != pressed;
                        value += ( transition << 1 );
                        value |= pressed;
                        state->scancodes[ offset ] = value;
                    }
                }
                
            } break;
            
            case WM_CHAR: {
                
                if ( state->characterCount < arrayCount( state->characters ) ) {
                    state->characters[ state->characterCount++ ] = ( u32 ) message.wParam;
                }
                
            } break;
            
            default : {
                TranslateMessage( &message );
                DispatchMessage( &message );
            } break;
        }
    }
}

void window_swapBuffers( PlatformSpecific* platform ) {
    SwapBuffers( platform->deviceContext );
}

void window_create( window_State* state, char* windowName, u32 width, u32 height, s32 x, s32 y ) {
    
    input_vkToKey( );
    
    WNDCLASS windowClass = { };
    windowClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
    windowClass.lpfnWndProc = windowProc;
    windowClass.hInstance = GetModuleHandle( 0 );
    windowClass.lpszClassName = "simple_window";
    windowClass.hCursor = LoadCursor( 0, IDC_ARROW );
    windowClass.cbWndExtra = sizeof( window_State* );
    
    if ( RegisterClass( &windowClass ) != 0 ) {
        
        HWND dummyHandle = 0;
        u32 windowStyle = WS_OVERLAPPEDWINDOW;
        
        dummyHandle = CreateWindowEx( 0, windowClass.lpszClassName, windowName, windowStyle, state->x, state->y, state->width, state->height, 0, 0, windowClass.hInstance, 0
                                     );
        
        SetWindowLongPtr( dummyHandle, 0, ( LONG_PTR ) state );
        
        PIXELFORMATDESCRIPTOR pfd = {
            sizeof( PIXELFORMATDESCRIPTOR ),
            1,
            PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
            PFD_TYPE_RGBA,
            32,
            0, 0, 0, 0, 0, 0,
            0,
            0,
            0,
            0, 0, 0, 0,
            24,
            8,
            0,
            PFD_MAIN_PLANE,
            0,
            0, 0, 0
        };
        
        HDC dummyDeviceContext = GetDC( dummyHandle );
        
        state->screenWidth = GetDeviceCaps( dummyDeviceContext, HORZRES );
        state->screenHeight =  GetDeviceCaps( dummyDeviceContext, VERTRES );
        
        RECT windowRect = { };
        
        if ( x == s32_max ) {
            windowRect.left = ( state->screenWidth - width ) / 2;
            x = windowRect.left;
        } else {
            windowRect.left = x;
        }
        
        if ( y == s32_max ) {
            windowRect.top = ( state->screenHeight - height ) / 2;
            y = windowRect.top;
        } else {
            windowRect.top = state->screenHeight - height - y;
        }
        
        windowRect.right = windowRect.left + width;
        windowRect.bottom = windowRect.top + height;
        
        AdjustWindowRect( &windowRect, WS_OVERLAPPEDWINDOW, 0 );
        
        /* NOTE simon: window_State contains the client rect information.
        Do not use windowRect here since it contains window rect information. */
        state->x = x;
        state->y = y;
        state->width = width;
        state->height = height;
        
        int defaultPixelFormat = ChoosePixelFormat( dummyDeviceContext, &pfd );
        DescribePixelFormat( dummyDeviceContext, defaultPixelFormat, sizeof( pfd ), &pfd );
        SetPixelFormat( dummyDeviceContext, defaultPixelFormat, &pfd );
        
        HGLRC dummyContext = wglCreateContext( dummyDeviceContext );
        
        if ( dummyContext ==  0 ) {
            
            // log_string( "Failed to create a default OpenGL context\n" );
            cleanUpWindow( &dummyContext, &dummyHandle, &dummyDeviceContext );
            
        } else {
            
            wglMakeCurrent( dummyDeviceContext, dummyContext );
            getWGLFunctions( );
            window_getGLFunctions( );
            // window_logPlatformExtensions( dummyDeviceContext );
            // log_string( "Dummy context\n" );
            // window_logGLInfos(  );
            
            /* NOTE simon: add WS_EX_TOPMOST as the first argument to have always on top window. */
            u32 exStyle = 0;
            // u32 exStyle = WS_EX_TOPMOST;
            
            HWND windowHandle = CreateWindowEx( exStyle, windowClass.lpszClassName, windowName, windowStyle, windowRect.left, windowRect.top, windowRect.right - windowRect.left, windowRect.bottom - windowRect.top, 0, 0, windowClass.hInstance, 0 );
            
            SetWindowLongPtr( windowHandle, 0, ( LONG_PTR ) state );
            
            HDC deviceContext = GetDC( windowHandle );
            
            const int attribList[] = {
                WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
                WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
                WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
                WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
                WGL_COLOR_BITS_ARB, 32,
                WGL_DEPTH_BITS_ARB, 24,
                WGL_STENCIL_BITS_ARB, 8,
                0,
            };
            
            int pixelFormat;
            UINT numFormats;
            
            if ( wglChoosePixelFormatARB( deviceContext, attribList, 0, 1, &pixelFormat, &numFormats ) ) {
                DescribePixelFormat( deviceContext, pixelFormat, sizeof( pfd ), &pfd );
                SetPixelFormat( deviceContext, pixelFormat, &pfd );
            } else {
                SetPixelFormat( deviceContext, defaultPixelFormat, &pfd );
            }
            
            const int contextAttribList[ ] = {
                
                WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
                WGL_CONTEXT_MINOR_VERSION_ARB, 3,
                //WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
                WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
                0
            };
            
            HGLRC renderContext = wglCreateContextAttribsARB( deviceContext, 0, contextAttribList );
            
            if ( renderContext != 0 ) {
                
                cleanUpWindow( &dummyContext, &dummyHandle, &dummyDeviceContext );
                
                wglMakeCurrent( deviceContext, renderContext );
                wglSwapIntervalEXT( 1 );
                
                // log_string( "\nActual context\n" );
                window_getGLFunctions( );
                // window_logGLInfos( );
                ShowWindow( windowHandle, SW_SHOW );
                
                state->platform.windowHandle = windowHandle;
                state->platform.deviceContext = deviceContext;
                state->platform.renderContext = renderContext;
                state->closeRequested = false;
                state->running = true;
                
            } else {
                
                // log_string( "Failed to create an advanced render context.\n" );
                cleanUpWindow( &dummyContext, &dummyHandle, &dummyDeviceContext );
            }
        }
        
        RAWINPUTDEVICE rawInputDevice;
        rawInputDevice.usUsagePage = 0x01;
        rawInputDevice.usUsage = 0x06;
        rawInputDevice.dwFlags = 0; /* RIDEV_NOLEGACY;   // adds HID keyboard and also ignores legacy keyboard messages */
        rawInputDevice.hwndTarget = 0;
        
        b32 registered = RegisterRawInputDevices( &rawInputDevice, 1, sizeof( rawInputDevice ) );
    }
}

#if GLSPEEDUP
DWORD WINAPI glSpeedUp(LPVOID param) {
    HDC dc = GetDC(NULL);
    DescribePixelFormat(dc, 0, 0, NULL);
    ReleaseDC(NULL, dc);
    return 0;
}
#endif

#include <stdio.h>

int main( int argc, char* argv[ ] ) {
    
    u64 hz, start, end;
    QueryPerformanceFrequency( ( LARGE_INTEGER* ) &hz );
    QueryPerformanceCounter( ( LARGE_INTEGER* ) &start );
    
#if GLSPEEDUP
    CreateThread( NULL, 2048, &glSpeedUp, NULL, 0, NULL );
#endif
    
    window_State _window = { 0 };
    window_State* window = &_window;
    window_create( window, "Speedup", 1280, 720, s32_max, s32_max );
    QueryPerformanceCounter( ( LARGE_INTEGER* ) &end );
    
    FILE* f = fopen( "timings.txt", "a" );
#if GLSPEEDUP
    fprintf( f, "fast: %8d - %.6f\n", end - start, ( ( r64 ) end - ( r64 ) start ) / ( r64 ) hz );
#else
    fprintf( f, "slow: %8d - %.6f\n", end - start, ( ( r64 ) end - ( r64 ) start ) / ( r64 ) hz );
#endif
    fclose( f );
    
#ifndef NOLOOP
    while ( window->running ) {
        
        window_handleMessages( window );
        
        if ( window->closeRequested ) {
            window->running = false;
        }
        
        window_swapBuffers( &window->platform );
    }
#endif
    
    return 0;
}

And a test that launches the program 20 times (can be overwritten with the first command line argument) and output the average. Note that this will result in flashing windows on the screen.
  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
#include <windows.h>
#include <stdint.h>
    
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
    
typedef int8_t s8;
typedef int16_t s16;
typedef int32_t s32;
typedef int64_t s64;
    
typedef uint8_t b8;
typedef uint32_t b32;
    
typedef uintptr_t umm;
typedef intptr_t smm;
    
typedef float r32;
typedef double r64;
    
b32 terminal_execute( char* command, char* workingDirectory, b32 shouldWait, u32* returnValue ) {
        
    b32 result = 0;
        
    PROCESS_INFORMATION processInformation = { 0 };
    STARTUPINFO startupInformation = { 0 };
    startupInformation.cb = sizeof( startupInformation );
        
    if ( CreateProcess( 0, command, 0, 0, 0, 0, 0, workingDirectory, &startupInformation, &processInformation ) ) {
            
       result = 1;
            
       if ( shouldWait && processInformation.hProcess != 0 ) {
                
            DWORD waitStatus = WaitForSingleObject( processInformation.hProcess, INFINITE );
                
            if ( waitStatus != WAIT_OBJECT_0 ) {
                result = 0;
            }
       }
            
       if ( processInformation.hProcess ) {
                
            if ( returnValue ) {
                    
                b32 success = GetExitCodeProcess( processInformation.hProcess, ( LPDWORD ) returnValue );
                    
                if ( !success || *returnValue == STILL_ACTIVE ) {
                    result = 0;
                }
            }
                
            CloseHandle( processInformation.hProcess );
        }
            
        if ( processInformation.hThread ) {
            CloseHandle( processInformation.hThread );
        }
    }
        
    return result;
}
    
#include <stdio.h>
    
int main( int argc, char** argv ) {
        
    u64 hz;
    QueryPerformanceFrequency( ( LARGE_INTEGER* ) &hz );
    DeleteFile( "timings.txt" );
    u32 loopCount = 20;
        
    if ( argc == 2 ) {
        loopCount = atoi( argv[ 1 ] );
    }
        
    for ( umm i = 0; i < loopCount; i++ ) {
        terminal_execute( "speedup_slow.exe", "./", true, 0 );
    }
        
    for ( umm i = 0; i < loopCount; i++ ) {
        terminal_execute( "speedup_fast.exe", "./", true, 0 );
    }
        
    FILE* f = fopen( "timings.txt", "r" );
    fseek( f, 0, SEEK_END );
    umm length = ftell( f );
    fseek( f, 0, SEEK_SET );
        
    char* buffer = ( char* )malloc( length );
    char* bufferStart = buffer;
        
    fread( buffer, length, 1, f );
    fclose( f );
    {
        u64 sum = 0;
            
        for ( umm i = 0; i < loopCount; i++ ) {
                
            buffer[ 14 ] = 0;
            sum += atoi( buffer + 5 );
            buffer += 26;
        }
            
        r64 average = ( r64 ) sum / ( r64 ) loopCount;
        r64 time = ( r64 ) average / ( r64 ) hz;
            
        printf( "slow: %10.2f - %.6f\n", average, time );
    }
        
    {
        u64 sum = 0;
            
        for ( umm i = 0; i < loopCount; i++ ) {
                
            buffer[ 14 ] = 0;
            sum += atoi( buffer + 5 );
            buffer += 26;
        }
            
        r64 average = ( r64 ) sum / ( r64 ) loopCount;
        r64 time = ( r64 ) average / ( r64 ) hz;
            
        printf( "fast: %10.2f - %.6f\n", average, time );
    }
        
    free( bufferStart );
        
    getchar( );
      
    return 0;
}

And the compile commands (I didn't cleanup the compile flags so some of them are irrelevant here):
1
2
3
cl main.cpp  -Fespeedup_slow.exe -MTd -Gm- -nologo -GR- -EHa- -Oi -fp:fast -WX -W4 -wd4201 -wd4505 -wd4996 -wd4100 -wd4189 -Zi -Fm -FC  -P -O2 -DCOMPILER_CL  -DWINDOWS  -DLOG -link -INCREMENTAL:NO -opt:ref  -subsystem:windows -entry:mainCRTStartup user32.lib OpenGL32.lib GDI32.lib
cl main.cpp  -Fespeedup_fast.exe -MTd -Gm- -nologo -GR- -EHa- -Oi -fp:fast -WX -W4 -wd4201 -wd4505 -wd4996 -wd4100 -wd4189 -Zi -Fm -FC  -P -O2 -DGLSPEEDUP -DCOMPILER_CL  -DWINDOWS  -DLOG -link -INCREMENTAL:NO -opt:ref  -subsystem:windows -entry:mainCRTStartup user32.lib OpenGL32.lib GDI32.lib
cl test.cpp -nologo -O2

Here is an archive with everything in it (including compiled exes).

I use this test on the game (with a return 0; after the window display) with 100 launch, the averages are pretty close.
1
2
Without the speedup 513725.44 - 0.188007
With the speedup    515176.71 - 0.188538


My config: Intel Core i7 860 (4 cores), Radeon r9 280 (driver 17.7.2), Windows 7 ultimate 64bit.

Edit: A friend tested the version from the code above with 20 runs on his Geforce Gtx 970 (without the mmozeiko fix) on Windows 10:
1
2
Without the speedup 3724980.00 - 1.088578
With the speedup    3679021.80 - 1.07514
3 posts
[Day 235] Opengl's pixel format takes a long time
Edited by ginkgobitter on Reason: corrected value
Thanks for the elaborate answer. I reviewed your code and all that happens between thread creation and window creation are < 200 simple assignments and registering the window class.. I'd be surprised if that even took a millisecond total.

So in your case creating a thread to initiate the loading probably does slightly more harm than good because there's really nothing to parallelize it with. And on your computer it seems that thread creation and executing these "unnecessary" calls is even slower than what you do until that first PixelBuffer call.

What you can do, however, is take any code that loads resources later-on and move it before your opengl context initialization as long as it takes less than say - 300ms (actually, I heard Intel cards finish in about 100ms - so maybe that's a better target?). This is what the first PixelBuffer call will waste anyway - whether you are doing something in the meantime or not. Since you create your window without the context (in my case context creation is handled inside WM_CREATE), it would't even affect how fast your window is displayed.

I have tested this on an NVIDIA GTX 760 with i7-4771 setup using the latest drivers and it worked just as well. Granted, savings are less substantial giving the ~2-3 seconds time it takes to check the profiles (big thanks to mmozeiko for insight into what the driver is doing).

Regarding the stack use for this loading thread - the following method is probably better:
1
CreateThread(NULL, 3*64*1024, &glSpeedUp, NULL, STACK_SIZE_PARAM_IS_A_RESERVATION, NULL);

The call as it was before could have potentially caused paging to be involved in the stack access (depending on the linker settings). It also turned out that the loading process actually required a bit more than one memory page (usually 64kb), so I made it a flat two pages.