-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.zig
1684 lines (1447 loc) · 62.3 KB
/
main.zig
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
const std = @import("std");
const builtin = @import("builtin");
const Atomic = std.atomic.Atomic;
const android = @import("android");
pub const panic = android.panic;
pub const log = android.log;
const EGLContext = android.egl.EGLContext;
const JNI = android.JNI;
const c = android.egl.c;
const ovr = android.ovr;
const Allocator = std.mem.Allocator;
const c_allocator = std.heap.c_allocator;
const app_log = std.log.scoped(.app);
const check_gl_errors = std.debug.runtime_safety and true;
const num_multisamples = 4;
const initial_cpu_level = 2;
const initial_gpu_level = 3;
const colors = struct {
pub const black = [4]u8{ 0, 0, 0, 255 };
pub const red = [4]u8{ 255, 0, 0, 255 };
pub const green = [4]u8{ 0, 255, 0, 255 };
pub const blue = [4]u8{ 0, 0, 255, 255 };
pub const magenta = [4]u8{ 255, 0, 255, 255 };
pub const cyan = [4]u8{ 0, 255, 255, 255 };
pub const yellow = [4]u8{ 255, 255, 0, 255 };
pub const white = [4]u8{ 255, 255, 255, 255 };
pub const purple = [4]u8{ 128, 0, 255, 255 };
pub const seafoam = [4]u8{ 0, 255, 128, 255 };
pub const orange = [4]u8{ 255, 128, 0, 255 };
pub const chartreuse = [4]u8{ 128, 255, 0, 255 };
pub const pink = [4]u8{ 255, 0, 128, 255 };
pub const blue_cyan = [4]u8{ 0, 128, 255, 255 };
pub const dignified_gray = [4]u8{ 51, 51, 51, 255 };
};
pub const Program = struct {
const max_uniforms = 8;
const max_textures = 8;
program: c.GLuint = 0,
vertex_shader: c.GLuint = 0,
fragment_shader: c.GLuint = 0,
uniform_locations: [max_uniforms]c.GLint = undefined,
uniform_bindings: [max_uniforms]c.GLint = undefined,
textures: [max_textures]c.GLint = undefined,
const version_header = "#version 300 es\n";
const enable_multiview = "#define DISABLE_MULTIVIEW 0\n";
const disable_multiview = "#define DISABLE_MULTIVIEW 1\n";
pub fn create(
self: *Program,
vertex_source: [:0]const u8,
fragment_source: [:0]const u8,
vertex_attributes: []const VertexAttribute,
use_multiview: bool,
) !void {
var status: c.GLint = 0;
const vs = GL(c.glCreateShader(c.GL_VERTEX_SHADER), @src());
errdefer GL(c.glDeleteShader(vs), @src());
const vertex_sources = [_][*c]const u8{
version_header,
if (use_multiview) enable_multiview else disable_multiview,
vertex_source.ptr,
};
GL(c.glShaderSource(vs, 3, &vertex_sources, 0), @src());
GL(c.glCompileShader(vs), @src());
GL(c.glGetShaderiv(vs, c.GL_COMPILE_STATUS, &status), @src());
if (status == c.GL_FALSE) {
var msg: [4096]c.GLchar = undefined;
GL(c.glGetShaderInfoLog(vs, msg.len, 0, &msg), @src());
const err_log = std.mem.sliceTo(&msg, 0);
app_log.err("Failed to compile vertex shader!\nSource:\n{s}\n{s}\n", .{ vertex_source, err_log });
return error.ShaderCreationFailed;
}
const fs = GL(c.glCreateShader(c.GL_FRAGMENT_SHADER), @src());
errdefer GL(c.glDeleteShader(fs), @src());
const fragment_sources = [_][*c]const u8{
version_header,
fragment_source.ptr,
};
GL(c.glShaderSource(fs, 2, &fragment_sources, 0), @src());
GL(c.glCompileShader(fs), @src());
GL(c.glGetShaderiv(fs, c.GL_COMPILE_STATUS, &status), @src());
if (status == c.GL_FALSE) {
var msg: [4096]c.GLchar = undefined;
GL(c.glGetShaderInfoLog(fs, msg.len, 0, &msg), @src());
const err_log = std.mem.sliceTo(&msg, 0);
app_log.err("Failed to compile fragment shader!\nSource:\n{s}\n{s}\n", .{ vertex_source, err_log });
return error.ShaderCreationFailed;
}
const program = GL(c.glCreateProgram(), @src());
errdefer GL(c.glDeleteProgram(program), @src());
GL(c.glAttachShader(program, vs), @src());
GL(c.glAttachShader(program, fs), @src());
for (vertex_attributes) |attr| {
GL(c.glBindAttribLocation(program, attr.location, attr.name.ptr), @src());
}
GL(c.glLinkProgram(program), @src());
GL(c.glGetProgramiv(program, c.GL_LINK_STATUS, &status), @src());
if (status == c.GL_FALSE) {
var msg: [4096]c.GLchar = undefined;
GL(c.glGetProgramInfoLog(fs, msg.len, 0, &msg), @src());
const err_log = std.mem.sliceTo(&msg, 0);
app_log.err("Failed to link program!\n{s}\n", .{err_log});
return error.ShaderCreationFailed;
}
var num_buffer_bindings: c_int = 0;
// fetch uniform locations
std.mem.set(c.GLint, &self.uniform_locations, -1);
for (program_uniforms) |uniform| {
if (uniform.kind == .buffer) {
const location = GL(c.glGetUniformBlockIndex(program, uniform.name.ptr), @src());
const binding = num_buffer_bindings;
num_buffer_bindings += 1;
GL(c.glUniformBlockBinding(program, location, @intCast(c_uint, binding)), @src());
self.uniform_locations[uniform.index] = @intCast(c_int, location);
self.uniform_bindings[uniform.index] = binding;
} else {
const location = GL(c.glGetUniformLocation(program, uniform.name.ptr), @src());
self.uniform_locations[uniform.index] = location;
self.uniform_bindings[uniform.index] = location;
}
}
GL(c.glUseProgram(program), @src());
// fetch texture locations
for (self.textures) |*tex, i| {
var buf: [32]u8 = undefined;
const tex_name = std.fmt.bufPrintZ(&buf, "Texture{}", .{i}) catch unreachable;
tex.* = GL(c.glGetUniformLocation(program, tex_name.ptr), @src());
if (tex.* != -1) {
GL(c.glUniform1i(tex.*, @intCast(c_int, i)), @src());
}
}
GL(c.glUseProgram(0), @src());
self.vertex_shader = vs;
self.fragment_shader = fs;
self.program = program;
}
pub fn destroy(self: *Program) void {
if (self.program != 0) {
GL(c.glDeleteProgram(self.program), @src());
self.program = 0;
}
if (self.fragment_shader != 0) {
GL(c.glDeleteShader(self.fragment_shader), @src());
self.fragment_shader = 0;
}
if (self.vertex_shader != 0) {
GL(c.glDeleteShader(self.vertex_shader), @src());
self.vertex_shader = 0;
}
}
};
const vertex_shader_src =
\\ #ifndef DISABLE_MULTIVIEW
\\ #define DISABLE_MULTIVIEW 0
\\ #endif
\\ #define NUM_VIEWS 2
\\ #if defined( GL_OVR_multiview2 ) && ! DISABLE_MULTIVIEW
\\ #extension GL_OVR_multiview2 : enable
\\ layout(num_views=NUM_VIEWS) in;
\\ #define VIEW_ID gl_ViewID_OVR
\\ #else
\\ uniform lowp int ViewID;
\\ #define VIEW_ID ViewID
\\ #endif
\\ in vec3 vertexPosition;
\\ in vec4 vertexColor;
\\ in mat4 vertexTransform;
\\ uniform SceneMatrices
\\ {
\\ uniform mat4 ViewMatrix[NUM_VIEWS];
\\ uniform mat4 ProjectionMatrix[NUM_VIEWS];
\\ } sm;
\\ out vec4 fragmentColor;
\\ void main()
\\ {
\\ gl_Position = sm.ProjectionMatrix[VIEW_ID] * ( sm.ViewMatrix[VIEW_ID] * ( vertexTransform * vec4( vertexPosition * 0.1, 1.0 ) ) );
\\ fragmentColor = vertexColor;
\\ }
;
const fragment_shader_src =
\\ in lowp vec4 fragmentColor;
\\ out lowp vec4 outColor;
\\ void main()
\\ {
\\ outColor = fragmentColor;
\\ }
;
pub const Uniform = struct {
pub const view_id = 0;
pub const scene_matrices = 1;
index: u8,
kind: enum {
vector4,
matrix4x4,
int,
buffer,
},
name: [:0]const u8,
};
pub const program_uniforms = [_]Uniform{
.{ .index = Uniform.view_id, .kind = .int, .name = "ViewID" },
.{ .index = Uniform.scene_matrices, .kind = .buffer, .name = "SceneMatrices" },
};
pub const VertexAttribute = struct {
location: u32,
name: [:0]const u8,
};
pub const VertexAttribPointer = struct {
index: c.GLuint,
size: c.GLint,
kind: c.GLenum,
normalized: c.GLboolean,
stride: c.GLsizei,
pointer: ?*const anyopaque,
};
pub const Geometry = struct {
const max_vertex_attrib_pointers = 3;
// Vertex attribute bindings
pub const va_position = 0;
pub const va_color = 1;
pub const va_uv = 2;
pub const va_transform = 3;
pub const program_vertex_attributes = [_]VertexAttribute{
.{ .location = va_position, .name = "vertexPosition" },
.{ .location = va_color, .name = "vertexColor" },
.{ .location = va_uv, .name = "vertexUv" },
.{ .location = va_transform, .name = "vertexTransform" },
};
vertex_buffer: c.GLuint = 0,
index_buffer: c.GLuint = 0,
vertex_array_object: c.GLuint = 0,
vertex_count: u32 = 0,
index_count: u32 = 0,
vertex_attribs: []const VertexAttribPointer = &.{},
pub fn createCube(self: *Geometry) void {
const CubeVertices = extern struct {
positions: [8][4]i8,
colors: [8][4]u8,
};
// zig fmt: off
const cube_vertices = CubeVertices{
.positions = .{
.{-127, 127, -127, 127},
.{ 127, 127, -127, 127},
.{ 127, 127, 127, 127},
.{-127, 127, 127, 127}, // top
.{-127, -127, -127, 127},
.{-127, -127, 127, 127},
.{ 127, -127, 127, 127},
.{ 127, -127, -127, 127}, // bottom
},
.colors = .{
.{ 0, 255, 0, 255},
.{255, 255, 0, 255},
.{255, 255, 255, 255},
.{ 0, 255, 255, 255},
.{ 0, 0, 0, 255},
.{ 0, 0, 255, 255},
.{255, 0, 255, 255},
.{255, 0, 0, 255},
},
};
const cube_indices = [36]u16{
0, 2, 1, 2, 0, 3, // top
4, 6, 5, 6, 4, 7, // bottom
2, 6, 7, 7, 1, 2, // right
0, 4, 5, 5, 3, 0, // left
3, 5, 6, 6, 2, 3, // front
0, 1, 7, 7, 4, 0, // back
};
// zig fmt: on
self.vertex_count = 8;
self.index_count = 36;
const cube_vertex_attrs = comptime [_]VertexAttribPointer{ .{
.index = va_position,
.size = 4,
.kind = c.GL_BYTE,
.normalized = 1,
.stride = @sizeOf([4]i8),
.pointer = @intToPtr(?*const anyopaque, @offsetOf(CubeVertices, "positions")),
}, .{
.index = va_color,
.size = 4,
.kind = c.GL_UNSIGNED_BYTE,
.normalized = 1,
.stride = @sizeOf([4]u8),
.pointer = @intToPtr(?*const anyopaque, @offsetOf(CubeVertices, "colors")),
} };
self.vertex_attribs = &cube_vertex_attrs;
var vb: c.GLuint = undefined;
GL(c.glGenBuffers(1, &vb), @src());
self.vertex_buffer = vb;
GL(c.glBindBuffer(c.GL_ARRAY_BUFFER, vb), @src());
GL(c.glBufferData(c.GL_ARRAY_BUFFER, @sizeOf(CubeVertices), &cube_vertices, c.GL_STATIC_DRAW), @src());
GL(c.glBindBuffer(c.GL_ARRAY_BUFFER, 0), @src());
var ib: c.GLuint = undefined;
GL(c.glGenBuffers(1, &ib), @src());
self.index_buffer = ib;
GL(c.glBindBuffer(c.GL_ELEMENT_ARRAY_BUFFER, ib), @src());
GL(c.glBufferData(c.GL_ELEMENT_ARRAY_BUFFER, @sizeOf(@TypeOf(cube_indices)), &cube_indices, c.GL_STATIC_DRAW), @src());
GL(c.glBindBuffer(c.GL_ELEMENT_ARRAY_BUFFER, 0), @src());
}
pub fn destroy(self: *Geometry) void {
GL(c.glDeleteBuffers(1, &self.index_buffer), @src());
GL(c.glDeleteBuffers(1, &self.vertex_buffer), @src());
self.* = .{};
}
pub fn createVAO(self: *Geometry) void {
var vao: c.GLuint = undefined;
GL(c.glGenVertexArrays(1, &vao), @src());
self.vertex_array_object = vao;
GL(c.glBindVertexArray(vao), @src());
GL(c.glBindBuffer(c.GL_ELEMENT_ARRAY_BUFFER, self.index_buffer), @src());
setUpBuffer(vao, self.vertex_buffer, self.vertex_attribs, false);
}
pub fn destroyVAO(self: *Geometry) void {
GL(c.glDeleteVertexArrays(1, &self.vertex_array_object), @src());
}
};
pub const Framebuffer = struct {
width: c_int,
height: c_int,
multisamples: u32,
texture_swapchain_length: u32,
texture_swapchain_index: u32,
use_multiview: bool,
color_texture_swapchain: *ovr.TextureSwapChain,
depth_buffers: []c.GLuint,
frame_buffers: []c.GLuint,
pub fn init(
try_use_multiview: bool,
color_format: c.GLenum,
width: c_int,
height: c_int,
multisamples: c_int,
allocator: Allocator,
) !Framebuffer {
const glRenderbufferStorageMultisampleEXT =
glext.getProc(glext.glRenderbufferStorageMultisampleEXT);
const glFramebufferTexture2DMultisampleEXT =
glext.getProc(glext.glFramebufferTexture2DMultisampleEXT);
const glFramebufferTextureMultiviewOVR =
glext.getProc(glext.glFramebufferTextureMultiviewOVR);
const glFramebufferTextureMultisampleMultiviewOVR =
glext.getProc(glext.glFramebufferTextureMultisampleMultiviewOVR);
const use_multiview = try_use_multiview and glFramebufferTextureMultiviewOVR != null;
const swapchain = ovr.TextureSwapChain.create3(
if (use_multiview) .@"2d_array" else .@"2d",
color_format,
width,
height,
1, // levels
3, // buffer count
) orelse {
app_log.err("CreateTextureSwapChain3 failed!\n", .{});
return error.FramebufferCreateFailed;
};
errdefer swapchain.destroy();
const length = swapchain.getLength();
const depth_buffers = try allocator.alloc(c.GLuint, @intCast(usize, length));
errdefer allocator.free(depth_buffers);
const frame_buffers = try allocator.alloc(c.GLuint, @intCast(usize, length));
errdefer allocator.free(frame_buffers);
if (use_multiview) {
GL(c.glGenTextures(length, depth_buffers.ptr), @src());
} else {
GL(c.glGenRenderbuffers(length, depth_buffers.ptr), @src());
}
errdefer if (use_multiview) {
GL(c.glDeleteTextures(length, depth_buffers.ptr), @src());
} else {
GL(c.glDeleteRenderbuffers(length, depth_buffers.ptr), @src());
};
GL(c.glGenFramebuffers(length, frame_buffers.ptr), @src());
errdefer GL(c.glDeleteFramebuffers(length, frame_buffers.ptr), @src());
var i: u32 = 0;
while (i < @intCast(u32, length)) : (i += 1) {
const color_tex = swapchain.getHandle(@intCast(c_int, i));
// set up render target params
{
const target = if (use_multiview) c.GL_TEXTURE_2D_ARRAY else c.GL_TEXTURE_2D;
const utarget = @intCast(c.GLuint, target);
GL(c.glBindTexture(utarget, color_tex), @src());
GL(c.glTexParameteri(utarget, c.GL_TEXTURE_WRAP_S, glext.GL_CLAMP_TO_BORDER), @src());
GL(c.glTexParameteri(utarget, c.GL_TEXTURE_WRAP_T, glext.GL_CLAMP_TO_BORDER), @src());
const borderColor = std.mem.zeroes([4]c.GLfloat);
GL(c.glTexParameterfv(utarget, glext.GL_TEXTURE_BORDER_COLOR, &borderColor), @src());
GL(c.glTexParameteri(utarget, c.GL_TEXTURE_MIN_FILTER, c.GL_LINEAR), @src());
GL(c.glTexParameteri(utarget, c.GL_TEXTURE_MAG_FILTER, c.GL_LINEAR), @src());
GL(c.glBindTexture(utarget, 0), @src());
}
if (use_multiview) {
// create depth buffer
GL(c.glBindTexture(c.GL_TEXTURE_2D_ARRAY, depth_buffers[i]), @src());
GL(c.glTexStorage3D(c.GL_TEXTURE_2D_ARRAY, 1, c.GL_DEPTH_COMPONENT24, width, height, 2), @src());
GL(c.glBindTexture(c.GL_TEXTURE_2D_ARRAY, 0), @src());
// create frame buffer
GL(c.glBindFramebuffer(c.GL_DRAW_FRAMEBUFFER, frame_buffers[i]), @src());
if (multisamples > 1 and glFramebufferTextureMultisampleMultiviewOVR != null) {
GL(glFramebufferTextureMultisampleMultiviewOVR.?(
c.GL_DRAW_FRAMEBUFFER,
c.GL_DEPTH_ATTACHMENT,
depth_buffers[i],
0, // level
multisamples,
0, // base view index
2, // num views
), @src());
GL(glFramebufferTextureMultisampleMultiviewOVR.?(
c.GL_DRAW_FRAMEBUFFER,
c.GL_COLOR_ATTACHMENT0,
color_tex,
0, // level
multisamples,
0, // base view index
2, // num views
), @src());
} else {
GL(glFramebufferTextureMultiviewOVR.?(
c.GL_DRAW_FRAMEBUFFER,
c.GL_DEPTH_ATTACHMENT,
depth_buffers[i],
0, // level
0, // base view index
2, // num views
), @src());
GL(glFramebufferTextureMultiviewOVR.?(
c.GL_DRAW_FRAMEBUFFER,
c.GL_COLOR_ATTACHMENT0,
color_tex,
0, // level
0, // base view index
2, // num views
), @src());
}
const render_framebuffer_status =
GL(c.glCheckFramebufferStatus(c.GL_DRAW_FRAMEBUFFER), @src());
GL(c.glBindFramebuffer(c.GL_DRAW_FRAMEBUFFER, 0), @src());
if (render_framebuffer_status != c.GL_FRAMEBUFFER_COMPLETE) {
app_log.err(
"Incomplete frame buffer object: {s}\n",
.{glFramebufferStatusString(render_framebuffer_status)},
);
return error.FramebufferCreateFailed;
}
} else {
if (multisamples > 1 and glRenderbufferStorageMultisampleEXT != null and glFramebufferTexture2DMultisampleEXT != null) {
// create multisampled depth buffer.
GL(c.glBindRenderbuffer(c.GL_RENDERBUFFER, depth_buffers[i]), @src());
GL(glRenderbufferStorageMultisampleEXT.?(c.GL_RENDERBUFFER, multisamples, c.GL_DEPTH_COMPONENT24, width, height), @src());
GL(c.glBindRenderbuffer(c.GL_RENDERBUFFER, 0), @src());
// create the frame buffer.
// NOTE: glFramebufferTexture2DMultisampleEXT only works with c.GL_FRAMEBUFFER.
GL(c.glBindFramebuffer(c.GL_FRAMEBUFFER, frame_buffers[i]), @src());
GL(glFramebufferTexture2DMultisampleEXT.?(
c.GL_FRAMEBUFFER,
c.GL_COLOR_ATTACHMENT0,
c.GL_TEXTURE_2D,
color_tex,
0, // level
multisamples,
), @src());
GL(c.glFramebufferRenderbuffer(
c.GL_FRAMEBUFFER,
c.GL_DEPTH_ATTACHMENT,
c.GL_RENDERBUFFER,
depth_buffers[i],
), @src());
const render_framebuffer_status =
GL(c.glCheckFramebufferStatus(c.GL_FRAMEBUFFER), @src());
GL(c.glBindFramebuffer(c.GL_FRAMEBUFFER, 0), @src());
if (render_framebuffer_status != c.GL_FRAMEBUFFER_COMPLETE) {
app_log.err(
"Incomplete frame buffer object: {s}\n",
.{glFramebufferStatusString(render_framebuffer_status)},
);
return error.FramebufferCreateFailed;
}
} else {
GL(c.glBindRenderbuffer(c.GL_RENDERBUFFER, depth_buffers[i]), @src());
GL(c.glRenderbufferStorage(c.GL_RENDERBUFFER, c.GL_DEPTH_COMPONENT24, width, height), @src());
GL(c.glBindRenderbuffer(c.GL_RENDERBUFFER, 0), @src());
GL(c.glBindFramebuffer(c.GL_DRAW_FRAMEBUFFER, frame_buffers[i]), @src());
GL(c.glFramebufferRenderbuffer(
c.GL_DRAW_FRAMEBUFFER,
c.GL_DEPTH_ATTACHMENT,
c.GL_RENDERBUFFER,
depth_buffers[i],
), @src());
GL(c.glFramebufferTexture2D(
c.GL_DRAW_FRAMEBUFFER,
c.GL_COLOR_ATTACHMENT0,
c.GL_TEXTURE_2D,
color_tex,
0,
), @src());
const render_framebuffer_status = GL(c.glCheckFramebufferStatus(c.GL_DRAW_FRAMEBUFFER), @src());
GL(c.glBindFramebuffer(c.GL_DRAW_FRAMEBUFFER, 0), @src());
if (render_framebuffer_status != c.GL_FRAMEBUFFER_COMPLETE) {
app_log.err(
"Incomplete frame buffer object: {s}\n",
.{glFramebufferStatusString(render_framebuffer_status)},
);
return error.FramebufferCreateFailed;
}
}
}
}
return Framebuffer{
.width = width,
.height = height,
.multisamples = @intCast(u32, multisamples),
.texture_swapchain_length = @intCast(u32, length),
.texture_swapchain_index = 0,
.use_multiview = use_multiview,
.color_texture_swapchain = swapchain,
.depth_buffers = depth_buffers,
.frame_buffers = frame_buffers,
};
}
pub fn deinit(self: *@This(), allocator: Allocator) void {
GL(c.glDeleteFramebuffers(@intCast(c_int, self.texture_swapchain_length), self.frame_buffers.ptr), @src());
if (self.use_multiview) {
GL(c.glDeleteTextures(@intCast(c_int, self.texture_swapchain_length), self.depth_buffers.ptr), @src());
} else {
GL(c.glDeleteRenderbuffers(@intCast(c_int, self.texture_swapchain_length), self.depth_buffers.ptr), @src());
}
self.color_texture_swapchain.destroy();
allocator.free(self.depth_buffers);
allocator.free(self.frame_buffers);
self.* = undefined;
}
pub fn setCurrent(self: *@This()) void {
GL(c.glBindFramebuffer(c.GL_DRAW_FRAMEBUFFER, self.frame_buffers[self.texture_swapchain_index]), @src());
}
pub fn setNone() void {
GL(c.glBindFramebuffer(c.GL_DRAW_FRAMEBUFFER, 0), @src());
}
pub fn resolve(self: *@This()) void {
_ = self;
// discard the depth buffer, so the tiler won't need to write it back out to memory.
const depth_attachment = [_]c.GLenum{c.GL_DEPTH_ATTACHMENT};
GL(c.glInvalidateFramebuffer(c.GL_DRAW_FRAMEBUFFER, 1, &depth_attachment), @src());
// we now let the resolve happen implicitly.
}
pub fn advance(self: *@This()) void {
const next = self.texture_swapchain_index + 1;
self.texture_swapchain_index = if (next >= self.texture_swapchain_length) 0 else next;
}
};
fn setUpBuffer(vao: c.GLuint, buffer: c.GLuint, attributes: []const VertexAttribPointer, instanced: bool) void {
GL(c.glBindVertexArray(vao), @src());
GL(c.glBindBuffer(c.GL_ARRAY_BUFFER, buffer), @src());
for (attributes) |*attr| {
GL(c.glEnableVertexAttribArray(attr.index), @src());
GL(c.glVertexAttribPointer(
attr.index,
attr.size,
attr.kind,
attr.normalized,
attr.stride,
attr.pointer,
), @src());
if (instanced) {
GL(c.glVertexAttribDivisor(attr.index, 1), @src());
}
}
GL(c.glBindVertexArray(0), @src());
}
const Scene = struct {
const num_instances = 1500;
const num_rotations = 16;
created: bool = false,
created_vaos: bool = false,
random: u32 = 2,
program: Program = .{},
cube: Geometry = .{},
scene_matrices: c.GLuint = 0,
instance_transform_buffer: c.GLuint = 0,
rotations: [num_rotations]ovr.Vector3f = undefined,
cube_positions: [num_instances]ovr.Vector3f = undefined,
cube_rotations: [num_instances]u32 = undefined,
debug_line_program: Program = .{},
debug_line_instance_buffer: c.GLuint = 0,
debug_lines: std.ArrayListUnmanaged(DebugLine) = .{},
debug_line_vao: c.GLuint = 0,
pub fn isCreated(self: *const Scene) bool {
return self.created;
}
pub fn create(self: *Scene, use_multiview: bool) !void {
@setCold(true);
try self.program.create(
vertex_shader_src,
fragment_shader_src,
&Geometry.program_vertex_attributes,
use_multiview,
);
errdefer self.program.destroy();
self.cube.createCube();
errdefer self.cube.destroy();
// create the transform buffer, empty
GL(c.glGenBuffers(1, &self.instance_transform_buffer), @src());
GL(c.glBindBuffer(c.GL_ARRAY_BUFFER, self.instance_transform_buffer), @src());
GL(c.glBufferData(c.GL_ARRAY_BUFFER, num_instances * 4 * 4 * @sizeOf(f32), null, c.GL_DYNAMIC_DRAW), @src());
GL(c.glBindBuffer(c.GL_ARRAY_BUFFER, 0), @src());
// create the scene matrices uniform buffer
GL(c.glGenBuffers(1, &self.scene_matrices), @src());
GL(c.glBindBuffer(c.GL_UNIFORM_BUFFER, self.scene_matrices), @src());
GL(c.glBufferData(c.GL_UNIFORM_BUFFER, 4 * @sizeOf(ovr.Matrix4f), null, c.GL_STATIC_DRAW), @src());
GL(c.glBindBuffer(c.GL_UNIFORM_BUFFER, 0), @src());
// randomize rotations
for (self.rotations) |*angles| {
angles.* = .{
.x = self.randomFloat(),
.y = self.randomFloat(),
.z = self.randomFloat(),
};
}
// find lots of cubes
const spawn_size = 5.0 + 0.1 * @sqrt(@intToFloat(f32, num_instances));
const close = 0.4;
var distances_sqr: [num_instances]f32 = undefined;
for (self.cube_positions) |_, i| {
const pos = while (true) {
// pick a random position
const rx = (self.randomFloat() - 0.5) * spawn_size;
const ry = (self.randomFloat() - 0.5) * spawn_size;
const rz = (self.randomFloat() - 0.5) * spawn_size;
const abs = std.math.absFloat;
if (abs(rx) >= close and abs(ry) >= close and abs(rz) >= close) {
// check for overlaps with other cubes
for (self.cube_positions[0..i]) |other| {
if (abs(rx - other.x) < close and abs(ry - other.y) < close and abs(rz - other.z) < close) {
break;
}
} else break ovr.Vector3f.init(rx, ry, rz);
}
} else unreachable;
// keep the list of cubes sorted by distance from the origin
const dist_sqr = pos.x * pos.x + pos.y * pos.y + pos.z * pos.z;
var j = i;
while (j > 0) : (j -= 1) {
if (dist_sqr > distances_sqr[j - 1]) break;
distances_sqr[j] = distances_sqr[j - 1];
self.cube_positions[j] = self.cube_positions[j - 1];
self.cube_rotations[j] = self.cube_rotations[j - 1];
}
distances_sqr[j] = dist_sqr;
self.cube_positions[j] = pos;
self.cube_rotations[j] = @floatToInt(u32, self.randomFloat() * (num_rotations - 0.1));
}
try self.debug_line_program.create(
DebugLine.vert_shader,
DebugLine.frag_shader,
&DebugLine.vertex_attrs,
use_multiview,
);
errdefer self.debug_line_program.destroy();
{
var line_instance_buf: c.GLuint = 0;
GL(c.glGenBuffers(1, &line_instance_buf), @src());
self.debug_line_instance_buffer = line_instance_buf;
}
self.created = true;
self.createVAOs();
}
pub fn destroy(self: *Scene) void {
self.destroyVAOs();
self.program.destroy();
self.cube.destroy();
GL(c.glDeleteBuffers(1, &self.instance_transform_buffer), @src());
GL(c.glDeleteBuffers(1, &self.scene_matrices), @src());
self.debug_line_program.destroy();
GL(c.glDeleteBuffers(1, &self.debug_line_instance_buffer), @src());
self.debug_lines.deinit(c_allocator);
self.created = false;
}
pub fn createVAOs(self: *Scene) void {
if (self.created_vaos) return;
// Init cube VAO
{
self.cube.createVAO();
var geometry_instance_layout = [_]VertexAttribPointer{.{
.index = undefined,
.size = 4,
.kind = c.GL_FLOAT,
.normalized = c.GL_FALSE,
.stride = @sizeOf(ovr.Matrix4f),
.pointer = undefined,
}} ** 4;
for (geometry_instance_layout) |*layout, i| {
layout.index = Geometry.va_transform + @intCast(c.GLuint, i);
layout.pointer = @intToPtr(?*anyopaque, i * @sizeOf(ovr.Vector4f));
}
setUpBuffer(
self.cube.vertex_array_object,
self.instance_transform_buffer,
&geometry_instance_layout,
true, // instanced
);
}
// Init debug line VAO
{
var vao: c.GLuint = undefined;
GL(c.glGenVertexArrays(1, &vao), @src());
self.debug_line_vao = vao;
setUpBuffer(
vao,
self.debug_line_instance_buffer,
&DebugLine.va_ptrs,
true, // instanced
);
}
self.created_vaos = true;
}
pub fn destroyVAOs(self: *Scene) void {
if (!self.created_vaos) return;
self.cube.destroyVAO();
GL(c.glDeleteVertexArrays(1, &self.debug_line_vao), @src());
self.created_vaos = false;
}
pub fn randomFloat(self: *Scene) f32 {
self.random = 1664525 *% self.random +% 1013904223;
const bits = 0x3f800000 | (self.random & 0x007FFFFF);
return @bitCast(f32, bits) - 1.0;
}
pub fn drawDebugLine(self: *Scene, start: ovr.Vector3f, end: ovr.Vector3f, color: [4]u8) void {
self.debug_lines.append(c_allocator, .{
.start = start,
.end = end,
.color = color,
}) catch |err| {
std.debug.assert(err == error.OutOfMemory);
app_log.warn("Failed to allocate memory for debug lines, size={}", .{self.debug_lines.capacity});
};
}
};
const Sound = struct {
};
const glext = struct {
const GLCC: std.builtin.CallingConvention =
if (builtin.os.tag == .windows) std.os.windows.WINAPI else .C;
const ExtFunc = struct {
name: [:0]const u8,
Signature: type,
};
pub fn getProc(comptime func: ExtFunc) ?func.Signature {
const proc = @ptrCast(?func.Signature, c.eglGetProcAddress(func.name.ptr));
if (proc == null) {
app_log.warn("Failed to load egl function {s}\n", .{func.name});
}
return proc;
}
pub const glRenderbufferStorageMultisampleEXT = ExtFunc{
.name = "glRenderbufferStorageMultisampleEXT",
.Signature = fn (
target: c.GLenum,
samples: c.GLsizei,
internalformat: c.GLenum,
width: c.GLsizei,
height: c.GLsizei,
) callconv(GLCC) void,
};
pub const glFramebufferTexture2DMultisampleEXT = ExtFunc{
.name = "glFramebufferTexture2DMultisampleEXT",
.Signature = fn (
target: c.GLenum,
attachment: c.GLenum,
textarget: c.GLenum,
texture: c.GLuint,
level: c.GLint,
samples: c.GLsizei,
) callconv(GLCC) void,
};
pub const GL_CLAMP_TO_BORDER = 0x812D;
pub const GL_TEXTURE_BORDER_COLOR = 0x1004;
pub const GL_FRAMEBUFFER_SRGB_EXT: c.GLenum = 0x8DB9;
pub const GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR: c.GLenum = 0x9630;
pub const GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_BASE_VIEW_INDEX_OVR: c.GLenum = 0x9632;
pub const GL_MAX_VIEWS_OVR: c.GLenum = 0x9631;
pub const glFramebufferTextureMultiviewOVR = ExtFunc{
.name = "glFramebufferTextureMultiviewOVR",
.Signature = fn (
target: c.GLenum,
attachment: c.GLenum,
texture: c.GLuint,
level: c.GLint,
base_view_index: c.GLint,
num_views: c.GLsizei,
) callconv(GLCC) void,
};
pub const glFramebufferTextureMultisampleMultiviewOVR = ExtFunc{
.name = "glFramebufferTextureMultisampleMultiviewOVR",
.Signature = fn (
target: c.GLenum,
attachment: c.GLenum,
texture: c.GLuint,
level: c.GLint,
samples: c.GLsizei,
base_view_index: c.GLint,
num_views: c.GLsizei,
) callconv(GLCC) void,
};
};
const events = struct {
pub const resumed_bit = 1 << 0;
pub const window_bit = 1 << 1;
pub const configuration_bit = 1 << 2;
};
const DebugLine = extern struct {
start: ovr.Vector3f,
end: ovr.Vector3f,
color: [4]u8,
const va_start = 0;
const va_end = 1;
const va_color = 2;
const vertex_attrs = [_]VertexAttribute{
.{ .location = va_start, .name = "startPosition" },
.{ .location = va_end, .name = "endPosition" },
.{ .location = va_color, .name = "vertexColor" },
};
const va_ptrs = [_]VertexAttribPointer{
.{
.index = va_start,
.size = 3,
.kind = c.GL_FLOAT,
.normalized = c.GL_FALSE,
.stride = @sizeOf(DebugLine),
.pointer = @intToPtr(?*anyopaque, @offsetOf(DebugLine, "start")),
},
.{
.index = va_end,
.size = 3,
.kind = c.GL_FLOAT,
.normalized = c.GL_FALSE,
.stride = @sizeOf(DebugLine),
.pointer = @intToPtr(?*anyopaque, @offsetOf(DebugLine, "end")),
},
.{
.index = va_color,
.size = 4,
.kind = c.GL_UNSIGNED_BYTE,
.normalized = c.GL_TRUE,
.stride = @sizeOf(DebugLine),
.pointer = @intToPtr(?*anyopaque, @offsetOf(DebugLine, "color")),
},
};
const vert_shader =
\\ #ifndef DISABLE_MULTIVIEW
\\ #define DISABLE_MULTIVIEW 0
\\ #endif
\\ #define NUM_VIEWS 2
\\ #if defined( GL_OVR_multiview2 ) && ! DISABLE_MULTIVIEW
\\ #extension GL_OVR_multiview2 : enable
\\ layout(num_views=NUM_VIEWS) in;
\\ #define VIEW_ID gl_ViewID_OVR
\\ #else
\\ uniform lowp int ViewID;
\\ #define VIEW_ID ViewID
\\ #endif
\\ in vec3 startPosition;
\\ in vec3 endPosition;
\\ in vec4 vertexColor;
\\ uniform SceneMatrices
\\ {
\\ uniform mat4 ViewMatrix[NUM_VIEWS];
\\ uniform mat4 ProjectionMatrix[NUM_VIEWS];
\\ } sm;
\\ out vec4 fragmentColor;
\\ void main()
\\ {