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
|
#include <stdio.h>
#include <SDL2/SDL.h>
#include <glad/glad.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
/* @lookup:
* - The normal matrix calculation in the fragment shader for the object affected by light has been mainly copied.
* I have tried to understand the formula, and whilst it made some sense, it is not fully clear to me, and I cannot picture it yet.
* Revisit the derivation for the normal matrix some time in the future.
* - Lookup the derivation of the formula for reflecting a vector about a normal. I am doing that for specular lighting, but the learnopengl tutorial
* just uses a glsl reflect formula, and at the time of writing it is also very late so I am not in the mood or position to look into it at present.
* - One of the things I have observed with specular lights is that the circle/specular highlight follows the camera (me) when I move. I would like to figure
* out a way by which this does not happen and it remains fixed on the object, at the angle at which it hits it. All of this will be made complicated by the fact
* that ofcourse everything is actually happening from the cameras' perspective. I would still love to figure this out.
*/
/* @todo:
*/
// =========== Shader Loading =============
unsigned int create_vertex_shader(const char* vertex_shader_source)
{
unsigned int vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, &vertex_shader_source, NULL);
glCompileShader(vertex_shader);
int success;
char info_log[512];
glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertex_shader, 512, NULL, info_log);
printf("================================\n");
printf("vertex shader compilation failed:\n%s\n", info_log);
}
return vertex_shader;
}
unsigned int create_fragment_shader(const char* fragment_shader_source)
{
unsigned int fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, &fragment_shader_source, NULL);
glCompileShader(fragment_shader);
int success;
char info_log[512];
glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(fragment_shader, 512, NULL, info_log);
printf("================================\n");
printf("fragment shader compilation failed:\n%s\n", info_log);
}
return fragment_shader;
}
unsigned int create_shader_program(unsigned int vertex_shader, unsigned int fragment_shader)
{
unsigned int shader_program = glCreateProgram();
glAttachShader(shader_program, vertex_shader);
glAttachShader(shader_program, fragment_shader);
glLinkProgram(shader_program);
int success;
char info_log[512];
glGetProgramiv(shader_program, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(shader_program, 512, NULL, info_log);
printf("================================\n");
printf("shader program linking failed:\n%s\n", info_log);
}
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
return shader_program;
}
// =========================================================== MATH ==================================================
#define PI 3.14159265358979323846264338327950288f
#define Square(x) ((x)*(x))
#define To_Radian(x) ((x) * PI / 180.0f)
#define To_Degree(x) ((x) * 180.0f / PI)
float clampf(float x, float bottom, float top)
{
if (x < bottom)
{
x = bottom;
}
else if (x > top)
{
x = top;
}
return x;
}
// ==== Vector Math ====
union Vec3 {
struct {
float x;
float y;
float z;
};
float data[3];
};
union Vec4 {
struct {
float x;
float y;
float z;
float w;
};
float data[4];
};
union Mat4 {
Vec4 xyzw[4];
float data[4][4];
float buffer[16];
};
// ========================================================== Vec3 ==========================================================
Vec3 init3v(float x, float y, float z)
{
Vec3 res;
res.x = x;
res.y = y;
res.z = z;
return res;
}
Vec3 scaler_add3v(Vec3 vec, float scaler)
{
Vec3 res;
res.x = vec.x + scaler;
res.y = vec.y + scaler;
res.z = vec.z + scaler;
return res;
}
Vec3 scaler_multiply3v(Vec3 vec, float scaler)
{
Vec3 res;
res.x = vec.x * scaler;
res.y = vec.y * scaler;
res.z = vec.z * scaler;
return res;
}
Vec3 scaler_divide3v(Vec3 vec, float scaler)
{
Vec3 res;
res.x = vec.x / scaler;
res.y = vec.y / scaler;
res.z = vec.z / scaler;
return res;
}
Vec3 add3v(Vec3 a, Vec3 b)
{
Vec3 res;
res.x = a.x + b.x;
res.y = a.y + b.y;
res.z = a.z + b.z;
return res;
}
Vec3 subtract3v(Vec3 a, Vec3 b)
{
Vec3 res;
res.x = a.x - b.x;
res.y = a.y - b.y;
res.z = a.z - b.z;
return res;
}
float dot_multiply3v(Vec3 a, Vec3 b)
{
float x = a.x * b.x;
float y = a.y * b.y;
float z = a.z * b.z;
float res = x + y + z;
return res;
}
float magnitude3v(Vec3 vec)
{
float res = sqrtf(Square(vec.x) + Square(vec.y) + Square(vec.z));
return res;
}
Vec3 normalize3v(Vec3 vec)
{
float magnitude = magnitude3v(vec);
Vec3 res = scaler_divide3v(vec, magnitude);
return res;
}
#ifndef FUN_CALCS
float angle3v(Vec3 a, Vec3 b)
{
Vec3 a_norm = normalize3v(a);
Vec3 b_norm = normalize3v(b);
float dot_product = dot_multiply3v(a_norm, b_norm);
float res = acosf(dot_product);
return res;
}
#endif
Vec3 cross_multiply3v(Vec3 a, Vec3 b)
{
Vec3 res;
res.x = (a.y * b.z) - (a.z * b.y);
res.y = (a.z * b.x) - (a.x * b.z);
res.z = (a.x * b.y) - (a.y * b.x);
return res;
}
// ============================================== Vec4, Mat4 ==============================================
Vec4 init4v(float x, float y, float z, float w)
{
Vec4 res;
res.x = x;
res.y = y;
res.z = z;
res.w = w;
return res;
}
Mat4 init_value4m(float value)
{
Mat4 res = {0};
res.data[0][0] = value;
res.data[1][1] = value;
res.data[2][2] = value;
res.data[3][3] = value;
return res;
}
// @note: These operations are just defined and not expressed. They are kept here for completeness sake BUT
// since I have not had to do anything related to these, I have not created them.
Vec4 scaler_add4v(Vec4 vec, float scaler);
Vec4 scaler_subtract4v(Vec4 vec, float scaler);
Vec4 scaler_multiply4v(Vec4 vec, float scaler);
Vec4 scaler_divide4v(Vec4 vec, float scaler);
Vec4 add4v(Vec4 a, Vec4 b);
Vec4 subtract4v(Vec4 a, Vec4 b);
Vec4 dot_multiply4v(Vec4 a, Vec4 b);
Mat4 add4m(Mat4 a, Mat4 b)
{
Mat4 res;
// row 0
res.data[0][0] = a.data[0][0] + b.data[0][0];
res.data[0][1] = a.data[0][1] + b.data[0][1];
res.data[0][2] = a.data[0][2] + b.data[0][2];
res.data[0][3] = a.data[0][3] + b.data[0][3];
// row 1
res.data[1][0] = a.data[1][0] + b.data[1][0];
res.data[1][1] = a.data[1][1] + b.data[1][1];
res.data[1][2] = a.data[1][2] + b.data[1][2];
res.data[1][3] = a.data[1][3] + b.data[1][3];
// row 2
res.data[2][0] = a.data[2][0] + b.data[2][0];
res.data[2][1] = a.data[2][1] + b.data[2][1];
res.data[2][2] = a.data[2][2] + b.data[2][2];
res.data[2][3] = a.data[2][3] + b.data[2][3];
// row 3
res.data[3][0] = a.data[3][0] + b.data[3][0];
res.data[3][1] = a.data[3][1] + b.data[3][1];
res.data[3][2] = a.data[3][2] + b.data[3][2];
res.data[3][3] = a.data[3][3] + b.data[3][3];
return res;
}
Mat4 subtract4m(Mat4 a, Mat4 b)
{
Mat4 res;
// row 0
res.data[0][0] = a.data[0][0] - b.data[0][0];
res.data[0][1] = a.data[0][1] - b.data[0][1];
res.data[0][2] = a.data[0][2] - b.data[0][2];
res.data[0][3] = a.data[0][3] - b.data[0][3];
// row 1
res.data[1][0] = a.data[1][0] - b.data[1][0];
res.data[1][1] = a.data[1][1] - b.data[1][1];
res.data[1][2] = a.data[1][2] - b.data[1][2];
res.data[1][3] = a.data[1][3] - b.data[1][3];
// row 2
res.data[2][0] = a.data[2][0] - b.data[2][0];
res.data[2][1] = a.data[2][1] - b.data[2][1];
res.data[2][2] = a.data[2][2] - b.data[2][2];
res.data[2][3] = a.data[2][3] - b.data[2][3];
// row 3
res.data[3][0] = a.data[3][0] - b.data[3][0];
res.data[3][1] = a.data[3][1] - b.data[3][1];
res.data[3][2] = a.data[3][2] - b.data[3][2];
res.data[3][3] = a.data[3][3] - b.data[3][3];
return res;
}
Vec4 multiply4vm(Vec4 vec, Mat4 mat)
{
/*
* @note: Incase I get confused about this in the future.
*
* Everything is row-order, which means that things in memory are laid out row first. So with a sample matrix
* we have this order in memory: r1c1 r1c2 r1c3 r1c4 r2c1 ... (r = row, c = column). The same holds true for
* vectors. (maybe move this explanation to the top)
*
* Now, multiply4vm will multiply a vector with a matrix. Conventionally that does not make any sense as
* a vector is usually 4x1 and a matrix ix 4x4.
* What this function considers a vector, while it is a vector, it is infact a row from a matrix, which
* means that the vector is 1x4 and the matrix is 4x4.
*
* The function is meant to supplement the matrix multiplication process to alleviate the multiple lines of code
* we have to write when multiplying the row of a left matrix to each column of the right matrix
*/
Vec4 res = { 0 };
res.x = (mat.data[0][0] * vec.x) + (mat.data[0][1] * vec.y) + (mat.data[0][2] * vec.z) + (mat.data[0][3] * vec.w);
res.y = (mat.data[1][0] * vec.x) + (mat.data[1][1] * vec.y) + (mat.data[1][2] * vec.z) + (mat.data[1][3] * vec.w);
res.z = (mat.data[2][0] * vec.x) + (mat.data[2][1] * vec.y) + (mat.data[2][2] * vec.z) + (mat.data[2][3] * vec.w);
res.w = (mat.data[3][0] * vec.x) + (mat.data[3][1] * vec.y) + (mat.data[3][2] * vec.z) + (mat.data[3][3] * vec.w);
return res;
}
Mat4 multiply4m(Mat4 a, Mat4 b)
{
Mat4 res = { 0 };
res.xyzw[0] = multiply4vm(a.xyzw[0], b);
res.xyzw[1] = multiply4vm(a.xyzw[1], b);
res.xyzw[2] = multiply4vm(a.xyzw[2], b);
res.xyzw[3] = multiply4vm(a.xyzw[3], b);
return res;
}
// ==== Matrix Transformation ====
Mat4 scaling_matrix4m(float x, float y, float z) // generates a 4x4 scaling matrix for scaling each of the x,y,z axis
{
Mat4 res = init_value4m(1.0f);
res.data[0][0] = x;
res.data[1][1] = y;
res.data[2][2] = z;
return res;
}
Mat4 translation_matrix4m(float x, float y, float z) // generates a 4x4 translation matrix for translation along each of the x,y,z axis
{
Mat4 res = init_value4m(1.0f);
res.data[0][3] = x;
res.data[1][3] = y;
res.data[2][3] = z;
return res;
}
Mat4 rotation_matrix4m(float angle_radians, Vec3 axis) // generates a 4x4 rotation matrix for rotation along each of the x,y,z axis
{
Mat4 res = init_value4m(1.0f);
axis = normalize3v(axis);
float cos_theta = cosf(angle_radians);
float sin_theta = sinf(angle_radians);
float cos_value = 1.0f - cos_theta;
res.data[0][0] = (axis.x * axis.x * cos_value) + cos_theta;
res.data[0][1] = (axis.x * axis.y * cos_value) + (axis.z * sin_theta);
res.data[0][2] = (axis.x * axis.z * cos_value) - (axis.y * sin_theta);
res.data[1][0] = (axis.x * axis.y * cos_value) - (axis.z * sin_theta);
res.data[1][1] = (axis.y * axis.y * cos_value) + cos_theta;
res.data[1][2] = (axis.y * axis.z * cos_value) + (axis.x * sin_theta);
res.data[2][0] = (axis.x * axis.z * cos_value) + (axis.y * sin_theta);
res.data[2][1] = (axis.z * axis.y * cos_value) - (axis.x * sin_theta);
res.data[2][2] = (axis.z * axis.z * cos_value) + cos_theta;
return res;
}
Mat4 perspective_projection_matrix4m(float left, float right, float bottom, float top, float near, float far)
{
Mat4 res = { 0 };
res.data[0][0] = (2.0 * near)/(right - left);
res.data[0][2] = (right + left)/(right - left);
res.data[1][1] = (2.0 * near)/(top - bottom);
res.data[1][2] = (top + bottom)/(top - bottom);
res.data[2][2] = -(far + near)/(far - near);
res.data[2][3] = -2.0*far*near/(far - near);
res.data[3][2] = -1.0;
return res;
}
Mat4 perspective4m(float fov, float aspect_ratio, float near, float far)
{
float cotangent = 1.0f / tanf(fov / 2.0f);
Mat4 res = { 0 };
res.data[0][0] = cotangent / aspect_ratio;
res.data[1][1] = cotangent;
res.data[2][2] = -(far + near) / (far - near);
res.data[2][3] = -2.0 * far * near / (far - near);
res.data[3][2] = -1.0;
return res;
}
Mat4 lookat4m(Vec3 up, Vec3 forward, Vec3 right, Vec3 position)
{
/*
* @note: The construction of the lookat matrix is not obvious. For that reason here is the supplemental matrial I have used to understand
* things while I maintain my elementary understanding of linear algebra.
* 1. This youtube video (https://www.youtube.com/watch?v=3ZmqJb7J5wE) helped me understand why we invert matrices.
* It is because, we are moving from the position matrix which is a global to the view matrix which
* is a local. It won't be very clear from this illustration alone, so you would be best served watching the video and recollecting and understanding from there.
* 2. This article (https://twodee.org/blog/17560) derives (or rather shows), in a very shallow way how we get to the look at matrix.
*/
Mat4 res = init_value4m(1.0);
res.xyzw[0] = Vec4{ right.x, right.y, right.z, -dot_multiply3v(right, position) };
res.xyzw[1] = Vec4{ up.x, up.y, up.z, -dot_multiply3v(up, position) };
res.xyzw[2] = Vec4{ forward.x, forward.y, forward.z, -dot_multiply3v(forward, position) };
res.xyzw[3] = Vec4{ 0.0f, 0.0f, 0.0f, 1.0f };
return res;
}
Mat4 camera_create4m(Vec3 camera_pos, Vec3 camera_look, Vec3 camera_up)
{
// @note: We do this because this allows the camera to have the axis it looks at
// inwards be the +z axis.
// If we did not do this, then the inward axis the camera looks at would be negative.
// I am still learning from learnopengl.com but I imagine that this was done for conveniences' sake.
Vec3 camera_forward_dir = normalize3v(subtract3v(camera_pos, camera_look));
Vec3 camera_right_dir = normalize3v(cross_multiply3v(camera_up, camera_forward_dir));
Vec3 camera_up_dir = normalize3v(cross_multiply3v(camera_forward_dir, camera_right_dir));
Mat4 res = lookat4m(camera_up_dir, camera_forward_dir, camera_right_dir, camera_pos);
return res;
}
Vec3 camera_look_around(float angle_pitch, float angle_yaw)
{
Vec3 camera_look = {0.0};
camera_look.x = cosf(angle_yaw) * cosf(angle_pitch);
camera_look.y = sinf(angle_pitch);
camera_look.z = sinf(angle_yaw) * cosf(angle_pitch);
camera_look = normalize3v(camera_look);
return camera_look;
}
int main(int argc, char* argv[])
{
int width = 1024;
int height = 768;
if (SDL_Init(SDL_INIT_VIDEO) != 0)
{
printf("Error initialising SDL2: %s\n", SDL_GetError());
return 0;
};
// set opengl version and profile
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
// initialise window with opengl flag
SDL_Window* window = SDL_CreateWindow("SDL Test",
50,
50,
width,
height,
SDL_WINDOW_OPENGL);
SDL_SetRelativeMouseMode(SDL_TRUE);
// create an opengl context
SDL_GLContext context = SDL_GL_CreateContext(window);
if (!context)
{
printf("OpenGL context creation failed: %s\n", SDL_GetError());
return -1;
}
// load glad
if (!gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress)) {
printf("Failed to initialize Glad\n");
return 1;
}
const char* vertex_source =
"#version 330 core\n"
"layout(location = 0) in vec3 position;\n"
"layout(location = 1) in vec3 normal;\n"
"uniform mat4 Model;\n"
"uniform mat4 View;\n"
"uniform mat4 Projection;\n"
"out vec3 fragNormal;\n"
"out vec3 worldPosition;\n"
"void main() {\n"
" gl_Position = Projection * View * Model * vec4(position, 1.0);\n"
" worldPosition = vec3(Model * vec4(position, 1.0));\n"
" fragNormal = mat3(transpose(inverse(Model))) * normal;\n"
" fragNormal = normalize(normal);\n"
"}";
const char* fragment_source =
"#version 330 core\n"
"in vec3 fragNormal;\n"
"in vec3 worldPosition;\n"
"out vec4 FragColor;\n"
"uniform sampler2D smilingTexture;\n"
"uniform sampler2D containerTexture;\n"
"uniform vec3 lightPosition;\n"
"uniform vec3 cameraPosition;\n"
"uniform vec4 lightColor;\n"
"uniform vec4 objectColor;\n"
"void main() {\n"
" float ambientLightStrength = 0.1;\n"
" vec4 ambientLight = ambientLightStrength * lightColor;\n"
"\n"
"// @note: Diffuse calculations\n"
" vec3 lightDir = normalize(lightPosition - worldPosition);\n"
" float diffuseStrength = max(dot(lightDir, fragNormal), 0.0);\n"
" vec4 diffuseLight = diffuseStrength * lightColor;\n"
"\n"
"// @note: Specular calculations\n"
" float specularStrength = 0.5;\n"
" vec3 viewDir = normalize(cameraPosition - worldPosition);\n"
" vec3 reflectDir = reflect(-lightDir, fragNormal);\n"
" float specularity = max(dot(viewDir, reflectDir), 0.0);\n"
" float shininess = pow(specularity, 128.0);\n"
" vec4 specularLight = specularStrength * shininess * lightColor;\n"
" "
"\n"
" vec4 color = (ambientLight + diffuseLight + specularLight) * objectColor;\n"
" FragColor = color;\n"
"}\n";
const char* light_vertex_source =
"#version 330 core\n"
"layout(location = 0) in vec3 position;\n"
"uniform mat4 Model;\n"
"uniform mat4 View;\n"
"uniform mat4 Projection;\n"
"void main() {\n"
" gl_Position = Projection * View * Model * vec4(position.x, position.y, position.z, 1.0);\n"
"}\n";
const char* light_fragment_source =
"#version 330 core\n"
"out vec4 FragColor;\n"
"void main() {\n"
" FragColor = vec4(1.0);\n"
"}\n";
GLuint vertex_shader = create_vertex_shader(vertex_source);
GLuint fragment_shader = create_fragment_shader(fragment_source);
GLuint shader_program = create_shader_program(vertex_shader, fragment_shader);
printf("Successfully compiled normal shaders.\n");
GLuint light_vs = create_vertex_shader(light_vertex_source);
GLuint light_fs = create_fragment_shader(light_fragment_source);
GLuint light_sp = create_shader_program(light_vs, light_fs);
GLfloat rect_vertices[] = {
// Position // Color // Texture
-0.5f, -0.5f, 0.0f, 0.6f, 0.3f, 0.3f, 0.0f, 0.0f, // bottom left
0.5f, -0.5f, 0.0f, 0.6f, 0.5f, 0.5f, 1.0f, 0.0f, // bottom right
-0.5f, 0.5f, 0.0f, 0.4f, 0.3f, 0.2f, 0.0f, 1.0f, // top left
0.5f, 0.5f, 0.0f, 0.4f, 0.5f, 0.6f, 1.0f, 1.0f // top right
};
unsigned int rect_indices[] = {
0, 1, 2,
2, 1, 3
};
float cube_normal_vertices[] = {
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, // this is the front side as seen from the camera star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, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f
};
GLuint light_VBO, light_VAO;
{
glGenVertexArrays(1, &light_VAO);
glGenBuffers(1, &light_VBO);
glBindVertexArray(light_VAO);
glBindBuffer(GL_ARRAY_BUFFER, light_VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(cube_vertices), cube_vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
GLuint VBO, VAO, EBO, container_texture, smiling_texture;
{
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
//glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(cube_normal_vertices), cube_normal_vertices, GL_STATIC_DRAW);
//glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
//glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(rect_indices), rect_indices, GL_STATIC_DRAW);
// Position Attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
// Color Attribute
//glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
//glEnableVertexAttribArray(1);
// Texture Attributes
//glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
//glEnableVertexAttribArray(1);
// normal attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);
int img_width, img_height, img_nrChannels;
// ==== Texture 1 ====
glGenTextures(1, &smiling_texture);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, smiling_texture);
const char* smiling_path = "assets/smiling.png";
stbi_set_flip_vertically_on_load(1);
unsigned char* smiling_data = stbi_load(smiling_path, &img_width, &img_height, &img_nrChannels, 0);
// Texture Properties
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
// Texture Data
if (smiling_data)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img_width, img_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, smiling_data);
glGenerateMipmap(GL_TEXTURE_2D);
}
else
{
printf("Error! Failed to load image from `%s`\n", smiling_path);
}
stbi_image_free(smiling_data);
// ==== Texture 2 ====
glGenTextures(1, &container_texture);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, container_texture);
const char* container_path = "assets/container.jpg";
unsigned char* container_data = stbi_load(container_path, &img_width, &img_height, &img_nrChannels, 0);
// Texture Properties
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
// Texture Data
if (container_data)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, container_data);
glGenerateMipmap(GL_TEXTURE_2D);
}
else
{
printf("Error! Failed to load image from `%s`\n", container_path);
}
stbi_image_free(container_data);
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
//glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindTexture(GL_TEXTURE_2D, 0);
}
Vec3 light_location = Vec3{ 0.0, 0.0, 3.0 };
glUseProgram(shader_program);
// texture uniforms
int smiling_loc = glGetUniformLocation(shader_program, "smilingTexture");
glUniform1i(smiling_loc, 0);
int container_loc = glGetUniformLocation(shader_program, "containerTexture");
glUniform1i(container_loc, 1);
Vec4 light_color = Vec4{1.0, 1.0, 1.0, 1.0};
int light_uniform_loc = glGetUniformLocation(shader_program, "lightColor");
glUniform4fv(light_uniform_loc, 1, light_color.data);
Vec4 object_color = Vec4{ 1.0, 1.0, 0.0, 1.0 };
int object_uniform_loc = glGetUniformLocation(shader_program, "objectColor");
glUniform4fv(object_uniform_loc, 1, object_color.data);
int light_pos_loc = glGetUniformLocation(shader_program, "lightPosition");
glUniform3fv(light_pos_loc, 1, light_location.data);
int camera_pos_loc = glGetUniformLocation(shader_program, "cameraPosition");
// objects
Vec3 model_translations[] = {
Vec3{ 0.0, 0.0, 0.0},
Vec3{ -5.0, -1.0, -4.0},
Vec3{ 5.0, 2.0, -4.0},
Vec3{ -3.0, 5.0, -6.0},
Vec3{ 3.0, -7.0, -6.0},
};
float FOV = 90.0;
float time_curr;
float time_prev = SDL_GetTicks64() / 100.0;
uint32_t model_loc = glGetUniformLocation(shader_program, "Model");
// camera stuff
Vec3 camera_pos = Vec3{ 0.0, 5.0, 10.0f};
Vec3 preset_up_dir = Vec3{ 0.0, 1.0, 0.0 };
float angle_yaw, angle_pitch, angle_roll;
angle_pitch = (float)To_Radian(0.0f);
angle_yaw = (float)-To_Radian(90.0f);
Vec3 camera_look = camera_look_around(angle_pitch, angle_yaw);
// @todo: remove this, I dont like this and think that this is unnecessary
Vec3 camera_look_increment;
float camera_speed = 1.0f;
Mat4 view = camera_create4m(camera_pos, camera_look, preset_up_dir);
uint32_t view_loc = glGetUniformLocation(shader_program, "View");
glUniformMatrix4fv(view_loc, 1, GL_TRUE, view.buffer);
Mat4 proj = perspective4m((float)To_Radian(90.0), (float)width / (float)height, 0.1f, 100.0f);
uint32_t proj_loc = glGetUniformLocation(shader_program, "Projection");
glUniformMatrix4fv(proj_loc, 1, GL_TRUE, proj.buffer);
glUseProgram(light_sp);
Mat4 light_model = translation_matrix4m(light_location.x, light_location.y, light_location.z);
//Mat4 light_model = init_value4m(1.0);
//light_model = multiply4m(light_translation, light_model);
uint32_t light_model_loc = glGetUniformLocation(light_sp, "Model");
glUniformMatrix4fv(light_model_loc, 1, GL_TRUE, light_model.buffer);
uint32_t light_view_loc = glGetUniformLocation(light_sp, "View");
glUniformMatrix4fv(light_view_loc, 1, GL_TRUE, view.buffer);
uint32_t light_proj_loc = glGetUniformLocation(light_sp, "Projection");
glUniformMatrix4fv(light_proj_loc, 1, GL_TRUE, proj.buffer);
glEnable(GL_DEPTH_TEST);
bool game_running = true;
bool move_w = false;
bool move_a = false;
bool move_s = false;
bool move_d = false;
while(game_running)
{
// frame delta
time_curr = SDL_GetTicks64() / 100.0;
float time_delta = time_curr - time_prev;
float camera_speed_adjusted = time_delta * camera_speed;
camera_look_increment = scaler_multiply3v(camera_look, camera_speed_adjusted);
SDL_Event ev;
while(SDL_PollEvent(&ev))
{
// INPUT
switch (ev.type)
{
case (SDL_QUIT):
{
game_running = false;
} break;
case (SDL_KEYDOWN):
{
if (ev.key.keysym.sym == SDLK_SPACE)
{}
if (ev.key.keysym.sym == SDLK_UP)
{
#if TESTING_FOV
FOV += 5.0;
Mat4 proj = perspective4m(To_Radian(FOV), (float)width / (float)height, 0.1, 100.0);
#endif
}
if (ev.key.keysym.sym == SDLK_DOWN)
{
#if TESTING_FOV
FOV -= 5.0;
Mat4 proj = perspective4m(To_Radian(FOV), (float)width / (float)height, 0.1, 100.0);
#endif
}
if (ev.key.keysym.sym == SDLK_w)
{
move_w = true;
}
if (ev.key.keysym.sym == SDLK_s)
{
move_s = true;
}
if (ev.key.keysym.sym == SDLK_a)
{
move_a = true;
}
if (ev.key.keysym.sym == SDLK_d)
{
move_d = true;
}
} break;
case (SDL_KEYUP):
{
if (ev.key.keysym.sym == SDLK_w)
{
move_w = false;
}
if (ev.key.keysym.sym == SDLK_s)
{
move_s = false;
}
if (ev.key.keysym.sym == SDLK_a)
{
move_a = false;
}
if (ev.key.keysym.sym == SDLK_d)
{
move_d = false;
}
} break;
case (SDL_MOUSEMOTION):
{
SDL_MouseMotionEvent mouse_event = ev.motion;
float x_motion = (float)mouse_event.xrel;
float y_motion = (float)mouse_event.yrel;
if (x_motion != 0.0 || y_motion != 0.0)
{
angle_yaw = angle_yaw + To_Radian(x_motion * 0.1f);
angle_pitch = clampf(angle_pitch + To_Radian(-y_motion * 0.1f), To_Radian(-89.0f), To_Radian(89.0f));
camera_look = camera_look_around(angle_pitch, angle_yaw);
}
} break;
default:
{
break;
}
}
}
// PROCESS
if (move_w)
{
camera_pos = add3v(camera_pos, camera_look_increment);
}
if (move_s)
{
camera_pos = subtract3v(camera_pos, camera_look_increment);
}
if (move_a)
{
Vec3 camera_right = normalize3v(cross_multiply3v(preset_up_dir, camera_look));
Vec3 camera_right_scaled = scaler_multiply3v(camera_right, camera_speed_adjusted);
camera_pos = add3v(camera_pos, camera_right_scaled);
}
if (move_d)
{
Vec3 camera_right = normalize3v(cross_multiply3v(preset_up_dir, camera_look));
Vec3 camera_right_scaled = scaler_multiply3v(camera_right, camera_speed_adjusted);
camera_pos = subtract3v(camera_pos, camera_right_scaled);
}
// light_location.z = 10.00 * sinf(time_curr/10.0);
view = camera_create4m(camera_pos, add3v(camera_pos, camera_look), preset_up_dir);
// object shader program stuff
glUseProgram(shader_program);
glUniformMatrix4fv(view_loc, 1, GL_TRUE, view.buffer);
glUniform3fv(light_pos_loc, 1, light_location.data);
glUniform3fv(camera_pos_loc, 1, camera_pos.data);
// light/lamp shader program stuff
glUseProgram(light_sp);
light_model = translation_matrix4m(light_location.x, light_location.y, light_location.z);
glUniformMatrix4fv(light_model_loc, 1, GL_TRUE, light_model.buffer);
glUniformMatrix4fv(light_view_loc, 1, GL_TRUE, view.buffer);
time_prev = time_curr;
// OUTPUT
glClearColor(1.0f, 0.6f, .6f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, smiling_texture);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, container_texture);
glUseProgram(light_sp);
glBindVertexArray(light_VAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
glUseProgram(0);
glUseProgram(shader_program);
glBindVertexArray(VAO);
for (int i = 0; i < 5; i++)
{
Vec3 translation_iter = model_translations[i];
Mat4 model = init_value4m(1.0);
Mat4 model_translation = translation_matrix4m(translation_iter.x, translation_iter.y, translation_iter.z);
model = multiply4m(model_translation, model);
glUniformMatrix4fv(model_loc, 1, GL_TRUE, model.buffer);
glDrawArrays(GL_TRIANGLES, 0, 36);
}
glBindVertexArray(0);
SDL_GL_SwapWindow(window);
}
// opengl free calls
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteProgram(shader_program);
// sdl free calls
SDL_GL_DeleteContext(context);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
|