-
Notifications
You must be signed in to change notification settings - Fork 293
Expand file tree
/
Copy pathgfxwrapper_opengl.c
More file actions
2866 lines (2441 loc) · 106 KB
/
gfxwrapper_opengl.c
File metadata and controls
2866 lines (2441 loc) · 106 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
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
/*
Copyright (c) 2017-2025 The Khronos Group Inc.
Copyright (c) 2016 Oculus VR, LLC.
Portions of macOS, iOS, functionality copyright (c) 2016 The Brenwill Workshop Ltd.
SPDX-License-Identifier: Apache-2.0
*/
#include "gfxwrapper_opengl.h"
#include "EGL/eglplatform.h"
#include "glad/egl.h"
/*
================================================================================================================================
System level functionality
================================================================================================================================
*/
static void Error(const char *format, ...) {
#if defined(OS_WINDOWS)
char buffer[4096];
va_list args;
va_start(args, format);
vsnprintf_s(buffer, 4096, _TRUNCATE, format, args);
va_end(args);
OutputDebugStringA(buffer);
// MessageBoxA(NULL, buffer, "ERROR", MB_OK | MB_ICONINFORMATION);
#elif defined(OS_LINUX)
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
printf("\n");
fflush(stdout);
#elif defined(OS_APPLE_MACOS)
char buffer[4096];
va_list args;
va_start(args, format);
int length = vsnprintf(buffer, 4096, format, args);
va_end(args);
NSLog(@"%s\n", buffer);
if ([NSThread isMainThread]) {
NSString *string = [[NSString alloc] initWithBytes:buffer length:length encoding:NSASCIIStringEncoding];
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
NSAlert *alert = [[NSAlert alloc] init];
[alert addButtonWithTitle:@"OK"];
[alert setMessageText:@"Error"];
[alert setInformativeText:string];
[alert setAlertStyle:NSWarningAlertStyle];
[alert runModal];
#pragma GCC diagnostic pop
}
#elif defined(OS_APPLE_IOS)
char buffer[4096];
va_list args;
va_start(args, format);
int length = vsnprintf(buffer, 4096, format, args);
va_end(args);
NSLog(@"%s\n", buffer);
if ([NSThread isMainThread]) {
NSString *string = [[NSString alloc] initWithBytes:buffer length:length encoding:NSASCIIStringEncoding];
UIAlertController *alert =
[UIAlertController alertControllerWithTitle:@"Error" message:string preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action){
}]];
[UIApplication.sharedApplication.keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
}
#elif defined(OS_ANDROID)
char buffer[4096];
va_list args;
va_start(args, format);
vsnprintf(buffer, 4096, format, args);
va_end(args);
__android_log_print(ANDROID_LOG_ERROR, "atw", "%s", buffer);
#endif
// Without exiting, the application will likely crash.
if (format != NULL) {
exit(1);
}
}
/*
================================================================================================================================
EGL error checking.
================================================================================================================================
*/
#if defined(OS_ANDROID) || defined(OS_LINUX_WAYLAND)
#define EGL(func) \
do { \
if (func == EGL_FALSE) { \
Error(#func " failed: %s", EglErrorString(eglGetError())); \
} \
} while (0)
static const char *EglErrorString(const EGLint error) {
switch (error) {
case EGL_SUCCESS:
return "EGL_SUCCESS";
case EGL_NOT_INITIALIZED:
return "EGL_NOT_INITIALIZED";
case EGL_BAD_ACCESS:
return "EGL_BAD_ACCESS";
case EGL_BAD_ALLOC:
return "EGL_BAD_ALLOC";
case EGL_BAD_ATTRIBUTE:
return "EGL_BAD_ATTRIBUTE";
case EGL_BAD_CONTEXT:
return "EGL_BAD_CONTEXT";
case EGL_BAD_CONFIG:
return "EGL_BAD_CONFIG";
case EGL_BAD_CURRENT_SURFACE:
return "EGL_BAD_CURRENT_SURFACE";
case EGL_BAD_DISPLAY:
return "EGL_BAD_DISPLAY";
case EGL_BAD_SURFACE:
return "EGL_BAD_SURFACE";
case EGL_BAD_MATCH:
return "EGL_BAD_MATCH";
case EGL_BAD_PARAMETER:
return "EGL_BAD_PARAMETER";
case EGL_BAD_NATIVE_PIXMAP:
return "EGL_BAD_NATIVE_PIXMAP";
case EGL_BAD_NATIVE_WINDOW:
return "EGL_BAD_NATIVE_WINDOW";
case EGL_CONTEXT_LOST:
return "EGL_CONTEXT_LOST";
default:
return "unknown";
}
}
#endif
/*
================================================================================================================================
OpenGL extensions.
================================================================================================================================
*/
#if defined(OS_ANDROID)
// GL_EXT_disjoint_timer_query without _EXT
#if !defined(GL_TIMESTAMP)
#define GL_QUERY_COUNTER_BITS GL_QUERY_COUNTER_BITS_EXT
#define GL_TIME_ELAPSED GL_TIME_ELAPSED_EXT
#define GL_TIMESTAMP GL_TIMESTAMP_EXT
#define GL_GPU_DISJOINT GL_GPU_DISJOINT_EXT
#endif
// GL_EXT_buffer_storage without _EXT
#if !defined(GL_BUFFER_STORAGE_FLAGS)
#define GL_MAP_READ_BIT 0x0001 // GL_MAP_READ_BIT_EXT
#define GL_MAP_WRITE_BIT 0x0002 // GL_MAP_WRITE_BIT_EXT
#define GL_MAP_PERSISTENT_BIT 0x0040 // GL_MAP_PERSISTENT_BIT_EXT
#define GL_MAP_COHERENT_BIT 0x0080 // GL_MAP_COHERENT_BIT_EXT
#define GL_DYNAMIC_STORAGE_BIT 0x0100 // GL_DYNAMIC_STORAGE_BIT_EXT
#define GL_CLIENT_STORAGE_BIT 0x0200 // GL_CLIENT_STORAGE_BIT_EXT
#define GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT 0x00004000 // GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT_EXT
#define GL_BUFFER_IMMUTABLE_STORAGE 0x821F // GL_BUFFER_IMMUTABLE_STORAGE_EXT
#define GL_BUFFER_STORAGE_FLAGS 0x8220 // GL_BUFFER_STORAGE_FLAGS_EXT
#endif
#if !defined(EGL_OPENGL_ES3_BIT)
#define EGL_OPENGL_ES3_BIT 0x0040
#endif
// GL_EXT_texture_cube_map_array
#if !defined(GL_TEXTURE_CUBE_MAP_ARRAY)
#define GL_TEXTURE_CUBE_MAP_ARRAY 0x9009
#endif
// GL_EXT_texture_filter_anisotropic
#if !defined(GL_TEXTURE_MAX_ANISOTROPY_EXT)
#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE
#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
#endif
// GL_EXT_texture_border_clamp or GL_OES_texture_border_clamp
#if !defined(GL_CLAMP_TO_BORDER)
#define GL_CLAMP_TO_BORDER 0x812D
#endif
// No 1D textures in OpenGL ES.
#if !defined(GL_TEXTURE_1D)
#define GL_TEXTURE_1D 0x0DE0
#endif
// No 1D texture arrays in OpenGL ES.
#if !defined(GL_TEXTURE_1D_ARRAY)
#define GL_TEXTURE_1D_ARRAY 0x8C18
#endif
// No multi-sampled texture arrays in OpenGL ES.
#if !defined(GL_TEXTURE_2D_MULTISAMPLE_ARRAY)
#define GL_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9102
#endif
#endif
/*
================================================================================================================================
Driver Instance.
================================================================================================================================
*/
bool ksDriverInstance_Create(ksDriverInstance *instance) {
memset(instance, 0, sizeof(ksDriverInstance));
return true;
}
void ksDriverInstance_Destroy(ksDriverInstance *instance) { memset(instance, 0, sizeof(ksDriverInstance)); }
/*
================================================================================================================================
GPU Device.
================================================================================================================================
*/
bool ksGpuDevice_Create(ksGpuDevice *device, ksDriverInstance *instance, const ksGpuQueueInfo *queueInfo) {
/*
Use an extensions to select the appropriate device:
https://www.opengl.org/registry/specs/NV/gpu_affinity.txt
https://www.opengl.org/registry/specs/AMD/wgl_gpu_association.txt
https://www.opengl.org/registry/specs/AMD/glx_gpu_association.txt
On Linux configure each GPU to use a separate X screen and then select
the X screen to render to.
*/
memset(device, 0, sizeof(ksGpuDevice));
device->instance = instance;
device->queueInfo = *queueInfo;
return true;
}
void ksGpuDevice_Destroy(ksGpuDevice *device) { memset(device, 0, sizeof(ksGpuDevice)); }
/*
================================================================================================================================
GPU Context.
================================================================================================================================
*/
ksGpuSurfaceBits ksGpuContext_BitsForSurfaceFormat(const ksGpuSurfaceColorFormat colorFormat,
const ksGpuSurfaceDepthFormat depthFormat) {
ksGpuSurfaceBits bits;
bits.redBits = ((colorFormat == KS_GPU_SURFACE_COLOR_FORMAT_R8G8B8A8)
? 8
: ((colorFormat == KS_GPU_SURFACE_COLOR_FORMAT_B8G8R8A8)
? 8
: ((colorFormat == KS_GPU_SURFACE_COLOR_FORMAT_R5G6B5)
? 5
: ((colorFormat == KS_GPU_SURFACE_COLOR_FORMAT_B5G6R5) ? 5 : 8))));
bits.greenBits = ((colorFormat == KS_GPU_SURFACE_COLOR_FORMAT_R8G8B8A8)
? 8
: ((colorFormat == KS_GPU_SURFACE_COLOR_FORMAT_B8G8R8A8)
? 8
: ((colorFormat == KS_GPU_SURFACE_COLOR_FORMAT_R5G6B5)
? 6
: ((colorFormat == KS_GPU_SURFACE_COLOR_FORMAT_B5G6R5) ? 6 : 8))));
bits.blueBits = ((colorFormat == KS_GPU_SURFACE_COLOR_FORMAT_R8G8B8A8)
? 8
: ((colorFormat == KS_GPU_SURFACE_COLOR_FORMAT_B8G8R8A8)
? 8
: ((colorFormat == KS_GPU_SURFACE_COLOR_FORMAT_R5G6B5)
? 5
: ((colorFormat == KS_GPU_SURFACE_COLOR_FORMAT_B5G6R5) ? 5 : 8))));
bits.alphaBits = ((colorFormat == KS_GPU_SURFACE_COLOR_FORMAT_R8G8B8A8)
? 8
: ((colorFormat == KS_GPU_SURFACE_COLOR_FORMAT_B8G8R8A8)
? 8
: ((colorFormat == KS_GPU_SURFACE_COLOR_FORMAT_R5G6B5)
? 0
: ((colorFormat == KS_GPU_SURFACE_COLOR_FORMAT_B5G6R5) ? 0 : 8))));
bits.colorBits = bits.redBits + bits.greenBits + bits.blueBits + bits.alphaBits;
bits.depthBits =
((depthFormat == KS_GPU_SURFACE_DEPTH_FORMAT_D16) ? 16 : ((depthFormat == KS_GPU_SURFACE_DEPTH_FORMAT_D24) ? 24 : 0));
return bits;
}
GLenum ksGpuContext_InternalSurfaceColorFormat(const ksGpuSurfaceColorFormat colorFormat) {
return ((colorFormat == KS_GPU_SURFACE_COLOR_FORMAT_R8G8B8A8)
? GL_RGBA8
: ((colorFormat == KS_GPU_SURFACE_COLOR_FORMAT_B8G8R8A8)
? GL_RGBA8
: ((colorFormat == KS_GPU_SURFACE_COLOR_FORMAT_R5G6B5)
? GL_RGB565
: ((colorFormat == KS_GPU_SURFACE_COLOR_FORMAT_B5G6R5) ? GL_RGB565 : GL_RGBA8))));
}
GLenum ksGpuContext_InternalSurfaceDepthFormat(const ksGpuSurfaceDepthFormat depthFormat) {
return ((depthFormat == KS_GPU_SURFACE_DEPTH_FORMAT_D16)
? GL_DEPTH_COMPONENT16
: ((depthFormat == KS_GPU_SURFACE_DEPTH_FORMAT_D24) ? GL_DEPTH_COMPONENT24 : GL_DEPTH_COMPONENT24));
}
#if defined(OS_WINDOWS)
static bool ksGpuContext_CreateForSurface(ksGpuContext *context, const ksGpuDevice *device, const int queueIndex,
const ksGpuSurfaceColorFormat colorFormat, const ksGpuSurfaceDepthFormat depthFormat,
const ksGpuSampleCount sampleCount, HINSTANCE hInstance, HDC hDC) {
UNUSED_PARM(queueIndex);
context->device = device;
const ksGpuSurfaceBits bits = ksGpuContext_BitsForSurfaceFormat(colorFormat, depthFormat);
PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR),
1, // version
PFD_DRAW_TO_WINDOW | // must support windowed
PFD_SUPPORT_OPENGL | // must support OpenGL
PFD_DOUBLEBUFFER, // must support double buffering
PFD_TYPE_RGBA, // iPixelType
bits.colorBits, // cColorBits
0,
0, // cRedBits, cRedShift
0,
0, // cGreenBits, cGreenShift
0,
0, // cBlueBits, cBlueShift
0,
0, // cAlphaBits, cAlphaShift
0, // cAccumBits
0, // cAccumRedBits
0, // cAccumGreenBits
0, // cAccumBlueBits
0, // cAccumAlphaBits
bits.depthBits, // cDepthBits
0, // cStencilBits
0, // cAuxBuffers
PFD_MAIN_PLANE, // iLayerType
0, // bReserved
0, // dwLayerMask
0, // dwVisibleMask
0 // dwDamageMask
};
HWND localWnd = NULL;
HDC localDC = hDC;
if (sampleCount > KS_GPU_SAMPLE_COUNT_1) {
// A valid OpenGL context is needed to get OpenGL extensions including wglChoosePixelFormatARB
// and wglCreateContextAttribsARB. A device context with a valid pixel format is needed to create
// an OpenGL context. However, once a pixel format is set on a device context it is final.
// Therefore a pixel format is set on the device context of a temporary window to create a context
// to get the extensions for multi-sampling.
localWnd = CreateWindowA(APPLICATION_NAME, "temp", 0, 0, 0, 0, 0, NULL, NULL, hInstance, NULL);
localDC = GetDC(localWnd);
}
int pixelFormat = ChoosePixelFormat(localDC, &pfd);
if (pixelFormat == 0) {
Error("Failed to find a suitable pixel format.");
return false;
}
if (!SetPixelFormat(localDC, pixelFormat, &pfd)) {
Error("Failed to set the pixel format.");
return false;
}
// Now that the pixel format is set, create a temporary context to get the extensions.
{
gladLoaderLoadWGL(localDC);
HGLRC hGLRC = wglCreateContext(localDC);
wglMakeCurrent(localDC, hGLRC);
gladLoaderLoadWGL(localDC);
wglMakeCurrent(NULL, NULL);
wglDeleteContext(hGLRC);
}
if (sampleCount > KS_GPU_SAMPLE_COUNT_1) {
// Release the device context and destroy the window that were created to get extensions.
ReleaseDC(localWnd, localDC);
DestroyWindow(localWnd);
int pixelFormatAttribs[] = {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,
bits.colorBits,
WGL_DEPTH_BITS_ARB,
bits.depthBits,
WGL_SAMPLE_BUFFERS_ARB,
1,
WGL_SAMPLES_ARB,
sampleCount,
0};
unsigned int numPixelFormats = 0;
if (!wglChoosePixelFormatARB(hDC, pixelFormatAttribs, NULL, 1, &pixelFormat, &numPixelFormats) || numPixelFormats == 0) {
Error("Failed to find MSAA pixel format.");
return false;
}
memset(&pfd, 0, sizeof(pfd));
if (!DescribePixelFormat(hDC, pixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd)) {
Error("Failed to describe the pixel format.");
return false;
}
if (!SetPixelFormat(hDC, pixelFormat, &pfd)) {
Error("Failed to set the pixel format.");
return false;
}
}
int contextAttribs[] = {WGL_CONTEXT_MAJOR_VERSION_ARB,
OPENGL_VERSION_MAJOR,
WGL_CONTEXT_MINOR_VERSION_ARB,
OPENGL_VERSION_MINOR,
WGL_CONTEXT_PROFILE_MASK_ARB,
WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
WGL_CONTEXT_FLAGS_ARB,
WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB | WGL_CONTEXT_DEBUG_BIT_ARB,
0};
context->hDC = hDC;
context->hGLRC = wglCreateContextAttribsARB(hDC, NULL, contextAttribs);
if (!context->hGLRC) {
Error("Failed to create GL context.");
return false;
}
wglMakeCurrent(hDC, context->hGLRC);
return true;
}
#elif defined(OS_LINUX_XLIB) || defined(OS_LINUX_XCB_GLX)
static int glxGetFBConfigAttrib2(Display *dpy, GLXFBConfig config, int attribute) {
int value;
glXGetFBConfigAttrib(dpy, config, attribute, &value);
return value;
}
static bool ksGpuContext_CreateForSurface(ksGpuContext *context, const ksGpuDevice *device, const int queueIndex,
const ksGpuSurfaceColorFormat colorFormat, const ksGpuSurfaceDepthFormat depthFormat,
const ksGpuSampleCount sampleCount, Display *xDisplay, int xScreen) {
UNUSED_PARM(queueIndex);
gladLoaderLoadGLX(xDisplay, xScreen);
context->device = device;
int glxErrorBase;
int glxEventBase;
if (!glXQueryExtension(xDisplay, &glxErrorBase, &glxEventBase)) {
Error("X display does not support the GLX extension.");
return false;
}
int glxVersionMajor;
int glxVersionMinor;
if (!glXQueryVersion(xDisplay, &glxVersionMajor, &glxVersionMinor)) {
Error("Unable to retrieve GLX version.");
return false;
}
int fbConfigCount = 0;
GLXFBConfig *fbConfigs = glXGetFBConfigs(xDisplay, xScreen, &fbConfigCount);
if (fbConfigCount == 0) {
Error("No valid framebuffer configurations found.");
return false;
}
const ksGpuSurfaceBits bits = ksGpuContext_BitsForSurfaceFormat(colorFormat, depthFormat);
bool foundFbConfig = false;
for (int i = 0; i < fbConfigCount; i++) {
if (glxGetFBConfigAttrib2(xDisplay, fbConfigs[i], GLX_FBCONFIG_ID) == 0) {
continue;
}
if (glxGetFBConfigAttrib2(xDisplay, fbConfigs[i], GLX_VISUAL_ID) == 0) {
continue;
}
if (glxGetFBConfigAttrib2(xDisplay, fbConfigs[i], GLX_DOUBLEBUFFER) == 0) {
continue;
}
if ((glxGetFBConfigAttrib2(xDisplay, fbConfigs[i], GLX_RENDER_TYPE) & GLX_RGBA_BIT) == 0) {
continue;
}
if ((glxGetFBConfigAttrib2(xDisplay, fbConfigs[i], GLX_DRAWABLE_TYPE) & GLX_WINDOW_BIT) == 0) {
continue;
}
if (glxGetFBConfigAttrib2(xDisplay, fbConfigs[i], GLX_RED_SIZE) != bits.redBits) {
continue;
}
if (glxGetFBConfigAttrib2(xDisplay, fbConfigs[i], GLX_GREEN_SIZE) != bits.greenBits) {
continue;
}
if (glxGetFBConfigAttrib2(xDisplay, fbConfigs[i], GLX_BLUE_SIZE) != bits.blueBits) {
continue;
}
if (glxGetFBConfigAttrib2(xDisplay, fbConfigs[i], GLX_ALPHA_SIZE) != bits.alphaBits) {
continue;
}
if (glxGetFBConfigAttrib2(xDisplay, fbConfigs[i], GLX_DEPTH_SIZE) != bits.depthBits) {
continue;
}
if (sampleCount > KS_GPU_SAMPLE_COUNT_1) {
if (glxGetFBConfigAttrib2(xDisplay, fbConfigs[i], GLX_SAMPLE_BUFFERS) != 1) {
continue;
}
if (glxGetFBConfigAttrib2(xDisplay, fbConfigs[i], GLX_SAMPLES) != (int)sampleCount) {
continue;
}
}
context->visualid = glxGetFBConfigAttrib2(xDisplay, fbConfigs[i], GLX_VISUAL_ID);
context->glxFBConfig = fbConfigs[i];
foundFbConfig = true;
break;
}
XFree(fbConfigs);
if (!foundFbConfig) {
Error("Failed to to find desired framebuffer configuration.");
return false;
}
context->xDisplay = xDisplay;
int attribs[] = {GLX_CONTEXT_MAJOR_VERSION_ARB,
OPENGL_VERSION_MAJOR,
GLX_CONTEXT_MINOR_VERSION_ARB,
OPENGL_VERSION_MINOR,
GL_CONTEXT_PROFILE_MASK,
GL_CONTEXT_CORE_PROFILE_BIT,
GLX_CONTEXT_FLAGS_ARB,
GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
0};
context->glxContext = glXCreateContextAttribsARB(xDisplay, // Display * dpy
context->glxFBConfig, // GLXFBConfig config
NULL, // GLXContext share_context
True, // Bool direct
attribs); // const int * attrib_list
if (context->glxContext == NULL) {
Error("Unable to create GLX context.");
return false;
}
if (!glXIsDirect(xDisplay, context->glxContext)) {
Error("Unable to create direct rendering context.");
return false;
}
return true;
}
#elif defined(OS_LINUX_XCB)
static uint32_t xcb_glx_get_property(const uint32_t *properties, const uint32_t numProperties, uint32_t propertyName) {
for (uint32_t i = 0; i < numProperties; i++) {
if (properties[i * 2 + 0] == propertyName) {
return properties[i * 2 + 1];
}
}
return 0;
}
static bool ksGpuContext_CreateForSurface(ksGpuContext *context, const ksGpuDevice *device, const int queueIndex,
const ksGpuSurfaceColorFormat colorFormat, const ksGpuSurfaceDepthFormat depthFormat,
const ksGpuSampleCount sampleCount, xcb_connection_t *connection, int screen_number) {
UNUSED_PARM(queueIndex);
context->device = device;
xcb_glx_query_version_cookie_t glx_query_version_cookie =
xcb_glx_query_version(connection, OPENGL_VERSION_MAJOR, OPENGL_VERSION_MINOR);
xcb_glx_query_version_reply_t *glx_query_version_reply =
xcb_glx_query_version_reply(connection, glx_query_version_cookie, NULL);
if (glx_query_version_reply == NULL) {
Error("Unable to retrieve GLX version.");
return false;
}
free(glx_query_version_reply);
xcb_glx_get_fb_configs_cookie_t get_fb_configs_cookie = xcb_glx_get_fb_configs(connection, screen_number);
xcb_glx_get_fb_configs_reply_t *get_fb_configs_reply = xcb_glx_get_fb_configs_reply(connection, get_fb_configs_cookie, NULL);
if (get_fb_configs_reply == NULL || get_fb_configs_reply->num_FB_configs == 0) {
Error("No valid framebuffer configurations found.");
return false;
}
const ksGpuSurfaceBits bits = ksGpuContext_BitsForSurfaceFormat(colorFormat, depthFormat);
const uint32_t *fb_configs_properties = xcb_glx_get_fb_configs_property_list(get_fb_configs_reply);
const uint32_t fb_configs_num_properties = get_fb_configs_reply->num_properties;
bool foundFbConfig = false;
for (uint32_t i = 0; i < get_fb_configs_reply->num_FB_configs; i++) {
const uint32_t *fb_config = fb_configs_properties + i * fb_configs_num_properties * 2;
if (xcb_glx_get_property(fb_config, fb_configs_num_properties, GLX_FBCONFIG_ID) == 0) {
continue;
}
if (xcb_glx_get_property(fb_config, fb_configs_num_properties, GLX_VISUAL_ID) == 0) {
continue;
}
if (xcb_glx_get_property(fb_config, fb_configs_num_properties, GLX_DOUBLEBUFFER) == 0) {
continue;
}
if ((xcb_glx_get_property(fb_config, fb_configs_num_properties, GLX_RENDER_TYPE) & GLX_RGBA_BIT) == 0) {
continue;
}
if ((xcb_glx_get_property(fb_config, fb_configs_num_properties, GLX_DRAWABLE_TYPE) & GLX_WINDOW_BIT) == 0) {
continue;
}
if (xcb_glx_get_property(fb_config, fb_configs_num_properties, GLX_RED_SIZE) != bits.redBits) {
continue;
}
if (xcb_glx_get_property(fb_config, fb_configs_num_properties, GLX_GREEN_SIZE) != bits.greenBits) {
continue;
}
if (xcb_glx_get_property(fb_config, fb_configs_num_properties, GLX_BLUE_SIZE) != bits.blueBits) {
continue;
}
if (xcb_glx_get_property(fb_config, fb_configs_num_properties, GLX_ALPHA_SIZE) != bits.alphaBits) {
continue;
}
if (xcb_glx_get_property(fb_config, fb_configs_num_properties, GLX_DEPTH_SIZE) != bits.depthBits) {
continue;
}
if (sampleCount > KS_GPU_SAMPLE_COUNT_1) {
if (xcb_glx_get_property(fb_config, fb_configs_num_properties, GLX_SAMPLE_BUFFERS) != 1) {
continue;
}
if (xcb_glx_get_property(fb_config, fb_configs_num_properties, GLX_SAMPLES) != sampleCount) {
continue;
}
}
context->fbconfigid = xcb_glx_get_property(fb_config, fb_configs_num_properties, GLX_FBCONFIG_ID);
context->visualid = xcb_glx_get_property(fb_config, fb_configs_num_properties, GLX_VISUAL_ID);
foundFbConfig = true;
break;
}
free(get_fb_configs_reply);
if (!foundFbConfig) {
Error("Failed to to find desired framebuffer configuration.");
return false;
}
context->connection = connection;
context->screen_number = screen_number;
// Create the context.
uint32_t attribs[] = {GLX_CONTEXT_MAJOR_VERSION_ARB,
OPENGL_VERSION_MAJOR,
GLX_CONTEXT_MINOR_VERSION_ARB,
OPENGL_VERSION_MINOR,
GLX_CONTEXT_PROFILE_MASK_ARB,
GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
GLX_CONTEXT_FLAGS_ARB,
GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
0};
context->glxContext = xcb_generate_id(connection);
xcb_glx_create_context_attribs_arb(connection, // xcb_connection_t * connection
context->glxContext, // xcb_glx_context_t context
context->fbconfigid, // xcb_glx_fbconfig_t fbconfig
screen_number, // uint32_t screen
0, // xcb_glx_context_t share_list
1, // uint8_t is_direct
4, // uint32_t num_attribs
attribs); // const uint32_t * attribs
// Make sure the context is direct.
xcb_generic_error_t *error;
xcb_glx_is_direct_cookie_t glx_is_direct_cookie = xcb_glx_is_direct_unchecked(connection, context->glxContext);
xcb_glx_is_direct_reply_t *glx_is_direct_reply = xcb_glx_is_direct_reply(connection, glx_is_direct_cookie, &error);
const bool is_direct = (glx_is_direct_reply != NULL && glx_is_direct_reply->is_direct);
free(glx_is_direct_reply);
if (!is_direct) {
Error("Unable to create direct rendering context.");
return false;
}
return true;
}
#elif defined(OS_LINUX_WAYLAND)
static bool ksGpuContext_CreateForSurface(ksGpuContext *context, const ksGpuDevice *device, struct wl_display *native_display) {
context->device = device;
if (gladLoaderLoadEGL(NULL) == 0) {
return false;
}
EGLint numConfigs;
EGLint majorVersion;
EGLint minorVersion;
// clang-format off
EGLint fbAttribs[] = {
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_RENDERABLE_TYPE, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT,
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_NONE,
};
EGLint contextAttribs[] = {
EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT,
EGL_CONTEXT_CLIENT_VERSION, OPENGL_VERSION_MAJOR,
EGL_CONTEXT_MINOR_VERSION, OPENGL_VERSION_MINOR,
EGL_NONE,
};
// clang-format on
context->display = eglGetDisplay(native_display);
if (context->display == EGL_NO_DISPLAY) {
Error("Could not create EGL Display.");
return false;
}
if (!eglInitialize(context->display, &majorVersion, &minorVersion)) {
Error("eglInitialize failed.");
return false;
}
printf("Initialized EGL context version %d.%d\n", majorVersion, minorVersion);
if (gladLoaderLoadEGL(context->display) == 0) {
return false;
}
EGLBoolean ret = eglGetConfigs(context->display, NULL, 0, &numConfigs);
if (ret != EGL_TRUE || numConfigs == 0) {
Error("eglGetConfigs failed.");
return false;
}
ret = eglChooseConfig(context->display, fbAttribs, &context->config, 1, &numConfigs);
if (ret != EGL_TRUE || numConfigs != 1) {
Error("eglChooseConfig failed.");
return false;
}
context->mainSurface = eglCreateWindowSurface(context->display, context->config, context->native_window, NULL);
if (context->mainSurface == EGL_NO_SURFACE) {
Error("eglCreateWindowSurface failed");
return false;
}
eglBindAPI(EGL_OPENGL_API);
context->context = eglCreateContext(context->display, context->config, EGL_NO_CONTEXT, contextAttribs);
if (context->context == EGL_NO_CONTEXT) {
Error("Could not create OpenGL context.");
return false;
}
if (!eglMakeCurrent(context->display, context->mainSurface, context->mainSurface, context->context)) {
Error("Could not make the current context current.");
return false;
}
return true;
}
#elif defined(OS_APPLE_MACOS)
static bool ksGpuContext_CreateForSurface(ksGpuContext *context, const ksGpuDevice *device, const int queueIndex,
const ksGpuSurfaceColorFormat colorFormat, const ksGpuSurfaceDepthFormat depthFormat,
const ksGpuSampleCount sampleCount, CGDirectDisplayID display) {
UNUSED_PARM(queueIndex);
context->device = device;
const ksGpuSurfaceBits bits = ksGpuContext_BitsForSurfaceFormat(colorFormat, depthFormat);
NSOpenGLPixelFormatAttribute pixelFormatAttributes[] = {NSOpenGLPFAMinimumPolicy,
1,
NSOpenGLPFAScreenMask,
CGDisplayIDToOpenGLDisplayMask(display),
NSOpenGLPFAAccelerated,
NSOpenGLPFAOpenGLProfile,
NSOpenGLProfileVersion3_2Core,
NSOpenGLPFADoubleBuffer,
NSOpenGLPFAColorSize,
bits.colorBits,
NSOpenGLPFADepthSize,
bits.depthBits,
NSOpenGLPFASampleBuffers,
(sampleCount > KS_GPU_SAMPLE_COUNT_1),
NSOpenGLPFASamples,
sampleCount,
0};
NSOpenGLPixelFormat *pixelFormat = [[[NSOpenGLPixelFormat alloc] initWithAttributes:pixelFormatAttributes] autorelease];
if (pixelFormat == nil) {
Error("Failed : NSOpenGLPixelFormat.");
return false;
}
context->nsContext = [[NSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:nil];
if (context->nsContext == nil) {
Error("Failed : NSOpenGLContext.");
return false;
}
context->cglContext = [context->nsContext CGLContextObj];
return true;
}
#elif defined(OS_ANDROID)
static bool ksGpuContext_CreateForSurface(ksGpuContext *context, const ksGpuDevice *device, const int queueIndex,
const ksGpuSurfaceColorFormat colorFormat, const ksGpuSurfaceDepthFormat depthFormat,
const ksGpuSampleCount sampleCount, EGLDisplay display) {
context->device = device;
context->display = display;
// Do NOT use eglChooseConfig, because the Android EGL code pushes in multisample
// flags in eglChooseConfig when the user has selected the "force 4x MSAA" option in
// settings, and that is completely wasted on the time warped frontbuffer.
enum { MAX_CONFIGS = 1024 };
EGLConfig configs[MAX_CONFIGS];
EGLint numConfigs = 0;
EGL(eglGetConfigs(display, configs, MAX_CONFIGS, &numConfigs));
const ksGpuSurfaceBits bits = ksGpuContext_BitsForSurfaceFormat(colorFormat, depthFormat);
// clang-format off
const EGLint configAttribs[] = {
EGL_RED_SIZE, bits.redBits,
EGL_GREEN_SIZE, bits.greenBits,
EGL_BLUE_SIZE, bits.blueBits,
EGL_ALPHA_SIZE, bits.alphaBits,
EGL_DEPTH_SIZE, bits.depthBits,
// EGL_STENCIL_SIZE, 0,
EGL_SAMPLE_BUFFERS, (sampleCount > KS_GPU_SAMPLE_COUNT_1),
EGL_SAMPLES, (sampleCount > KS_GPU_SAMPLE_COUNT_1) ? sampleCount : 0,
EGL_NONE,
};
// clang-format on
context->config = 0;
for (int i = 0; i < numConfigs; i++) {
EGLint value = 0;
eglGetConfigAttrib(display, configs[i], EGL_RENDERABLE_TYPE, &value);
if ((value & EGL_OPENGL_ES3_BIT) != EGL_OPENGL_ES3_BIT) {
continue;
}
// Without EGL_KHR_surfaceless_context, the config needs to support both pbuffers and window surfaces.
eglGetConfigAttrib(display, configs[i], EGL_SURFACE_TYPE, &value);
if ((value & (EGL_WINDOW_BIT | EGL_PBUFFER_BIT)) != (EGL_WINDOW_BIT | EGL_PBUFFER_BIT)) {
continue;
}
int j = 0;
for (; configAttribs[j] != EGL_NONE; j += 2) {
eglGetConfigAttrib(display, configs[i], configAttribs[j], &value);
if (value != configAttribs[j + 1]) {
break;
}
}
if (configAttribs[j] == EGL_NONE) {
context->config = configs[i];
break;
}
}
if (context->config == 0) {
Error("Failed to find EGLConfig");
return false;
}
EGLint contextAttribs[] = {EGL_CONTEXT_CLIENT_VERSION, OPENGL_VERSION_MAJOR, EGL_NONE, EGL_NONE, EGL_NONE};
// Use the default priority if KS_GPU_QUEUE_PRIORITY_MEDIUM is selected.
const ksGpuQueuePriority priority = device->queueInfo.queuePriorities[queueIndex];
if (priority != KS_GPU_QUEUE_PRIORITY_MEDIUM) {
contextAttribs[2] = EGL_CONTEXT_PRIORITY_LEVEL_IMG;
contextAttribs[3] = (priority == KS_GPU_QUEUE_PRIORITY_LOW) ? EGL_CONTEXT_PRIORITY_LOW_IMG : EGL_CONTEXT_PRIORITY_HIGH_IMG;
}
context->context = eglCreateContext(display, context->config, EGL_NO_CONTEXT, contextAttribs);
if (context->context == EGL_NO_CONTEXT) {
Error("eglCreateContext() failed: %s", EglErrorString(eglGetError()));
return false;
}
const EGLint surfaceAttribs[] = {EGL_WIDTH, 16, EGL_HEIGHT, 16, EGL_NONE};
context->tinySurface = eglCreatePbufferSurface(display, context->config, surfaceAttribs);
if (context->tinySurface == EGL_NO_SURFACE) {
Error("eglCreatePbufferSurface() failed: %s", EglErrorString(eglGetError()));
eglDestroyContext(display, context->context);
context->context = EGL_NO_CONTEXT;
return false;
}
context->mainSurface = context->tinySurface;
return true;
}
#endif
bool ksGpuContext_CreateShared(ksGpuContext *context, const ksGpuContext *other, int queueIndex) {
UNUSED_PARM(queueIndex);
memset(context, 0, sizeof(ksGpuContext));
context->device = other->device;
#if defined(OS_WINDOWS)
context->hDC = other->hDC;
context->hGLRC = wglCreateContext(other->hDC);
if (!wglShareLists(other->hGLRC, context->hGLRC)) {
return false;
}
#elif defined(OS_LINUX_XLIB) || defined(OS_LINUX_XCB_GLX)
context->xDisplay = other->xDisplay;
context->visualid = other->visualid;
context->glxFBConfig = other->glxFBConfig;
context->glxDrawable = other->glxDrawable;
context->glxContext = glXCreateNewContext(other->xDisplay, other->glxFBConfig, GLX_RGBA_TYPE, other->glxContext, True);
if (context->glxContext == NULL) {
return false;
}
#elif defined(OS_LINUX_XCB)
context->connection = other->connection;
context->screen_number = other->screen_number;
context->fbconfigid = other->fbconfigid;
context->visualid = other->visualid;
context->glxDrawable = other->glxDrawable;
context->glxContext = xcb_generate_id(other->connection);
xcb_glx_create_context(other->connection, context->glxContext, other->visualid, other->screen_number, other->glxContext, 1);
context->glxContextTag = 0;
#elif defined(OS_APPLE_MACOS)
context->nsContext = NULL;
CGLPixelFormatObj pf = CGLGetPixelFormat(other->cglContext);
if (CGLCreateContext(pf, other->cglContext, &context->cglContext) != kCGLNoError) {
Error("Failed : CGLCreateContext.");
return false;
}
CGSConnectionID cid;
CGSWindowID wid;
CGSSurfaceID sid;
if (CGLGetSurface(other->cglContext, &cid, &wid, &sid) != kCGLNoError) {
Error("Failed : CGLGetSurface.");
return false;
}
if (CGLSetSurface(context->cglContext, cid, wid, sid) != kCGLNoError) {
Error("Failed : CGLSetSurface.");
return false;
}
#elif defined(OS_ANDROID) || defined(OS_LINUX_WAYLAND)
context->display = other->display;
EGLint configID;
if (!eglQueryContext(context->display, other->context, EGL_CONFIG_ID, &configID)) {
Error("eglQueryContext EGL_CONFIG_ID failed: %s", EglErrorString(eglGetError()));
return false;