-
Notifications
You must be signed in to change notification settings - Fork 1
/
variance_shadow_mapping_MSM4.c
1438 lines (1249 loc) · 57.2 KB
/
variance_shadow_mapping_MSM4.c
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
// https://github.com/Flix01/Tiny-OpenGL-Shadow-Mapping-Examples
//
// Pdf: Moment Shadow Mapping - Christoph Peters, Reinhard Klein (http://cg.cs.uni-bonn.de/aigaion2root/attachments/MomentShadowMapping.pdf)
// This demo is greatly based on the Direct3D implementation available at: https://github.com/TheRealMJP/Shadows (MIT Licensed)
// Blur filters are based on https://github.com/Jam3/glsl-fast-gaussian-blur/ (MIT licensed)
//
/** License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// DEPENDENCIES:
/*
-> glut or freeglut (the latter is recommended)
-> glew (Windows only)
*/
// HOW TO COMPILE:
/*
// LINUX:
gcc -O2 -std=gnu89 -no-pie variance_shadow_mapping_MSM4.c -o variance_shadow_mapping_MSM4 -I"../" -lglut -lGL -lX11 -lm
// WINDOWS (here we use the static version of glew, and glut32.lib, that can be replaced by freeglut.lib):
cl /O2 /MT /Tc variance_shadow_mapping_MSM4.c /D"GLEW_STATIC" /I"../" /link /out:variance_shadow_mapping_MSM4.exe glut32.lib glew32s.lib opengl32.lib gdi32.lib Shell32.lib comdlg32.lib user32.lib kernel32.lib
// IN ADDITION:
By default the source file assumes that every OpenGL-related header is in "GL/".
But you can define in the command-line the correct paths you use in your system
for glut.h, glew.h, etc. with something like:
-DGLUT_PATH=\"Glut/glut.h\"
-DGLEW_PATH=\"Glew/glew.h\"
(this syntax works on Linux, don't know about Windows)
*/
//#define USE_GLEW // By default it's only defined for Windows builds (but can be defined in Linux/Mac builds too)
#define PROGRAM_NAME "variance_shadow_mapping_MSM4"
#define VISUALIZE_DEPTH_TEXTURE
#define SHADOW_MAP_RESOLUTION 1024 //1024
#define SHADOW_MAP_CLAMP_MODE GL_CLAMP_TO_EDGE // GL_CLAMP or GL_CLAMP_TO_EDGE or GL_CLAMP_TO_BORDER
// GL_CLAMP; // sampling outside of the shadow map gives always shadowed pixels
// GL_CLAMP_TO_EDGE; // sampling outside of the shadow map can give shadowed or unshadowed pixels (it depends on the edge of the shadow map)
// GL_CLAMP_TO_BORDER; // sampling outside of the shadow map gives always non-shadowed pixels (if we set the border color correctly)
#define SHADOW_MAP_FILTER GL_LINEAR // GL_LINEAR_MIPMAP_LINEAR or GL_LINEAR
//#define SHADOW_MAP_BLUR_USING_BOX_FILTER // Optional [Not sure code is correct]
#define SHADOW_MAP_BLUR_KERNEL_SIZE 5 // 0 or 1 (=no blur); 3, 5, 9, 13 valid values (when SHADOW_MAP_BLUR_USING_BOX_FILTER is NOT defined)
//#define SHADOW_MAP_USE_MSM_HAUSDORFF // If not defined MSM_HAMBURGER (the default MSM) is used
//#define __EMSCRIPTEN__ // This is just a hack to use a MSM4-16bit texture format to save half of GPU memory (of course all these demos use the fixed function pipeline and can't work on emscripten as they are)
// Also we need (and use) a higher bias in dp->uniform_location_shadowDepthAndMomentBiases, and some lightBleedingReduction too (but shadows look less blurry this way...).
//#define SHADOW_MAP_USE_OPTIMIZED_MOMENT_QUANTIZATION // Strictly mandatory for MSM4-16bit (we will force this when __EMSCRIPTEN__ is defined), but can be used with MSM4-32bit too (not sure something changes in the latter case)
// Not sure if the following are better or not... I would not use them, so that shaders are more portable
//# define USE_GLSL_FMA
//# define USE_GLSL_TEXTUREGRAD
// These path definitions can be passed to the compiler command-line
#ifndef GLUT_PATH
# define GLUT_PATH "GL/glut.h" // Mandatory
#endif //GLEW_PATH
#ifndef FREEGLUT_EXT_PATH
# define FREEGLUT_EXT_PATH "GL/freeglut_ext.h" // Optional (used only if glut.h comes from the freeglut library)
#endif //GLEW_PATH
#ifndef GLEW_PATH
# define GLEW_PATH "GL/glew.h" // Mandatory for Windows only
#endif //GLEW_PATH
#ifdef _WIN32
# include "windows.h"
# define USE_GLEW
#endif //_WIN32
#ifdef USE_GLEW
# include GLEW_PATH
#else //USE_GLEW
# define GL_GLEXT_PROTOTYPES
#endif //USE_GLEW
#include GLUT_PATH
#ifdef __FREEGLUT_STD_H__
# include FREEGLUT_EXT_PATH
#endif //__FREEGLUT_STD_H__
#define STR_MACRO(s) #s
#define XSTR_MACRO(s) STR_MACRO(s)
#if (!defined(SHADOW_MAP_BLUR_KERNEL_SIZE) || SHADOW_MAP_BLUR_KERNEL_SIZE<=0)
# undef SHADOW_MAP_BLUR_KERNEL_SIZE
# define SHADOW_MAP_BLUR_KERNEL_SIZE 1
#endif
#if (SHADOW_MAP_BLUR_KERNEL_SIZE==(SHADOW_MAP_BLUR_KERNEL_SIZE/2)*2)
# error SHADOW_MAP_BLUR_KERNEL_SIZE must be an odd number
#endif
#define SHADOW_MAP_OPTIMIZED_MOMENT_QUANTIZATION_USE_TRANSPOSE_MATRIX // Experimental (basically I don't know if this MUST be used or not... my ref code is https://github.com/TheRealMJP/Shadows and it's in Direct3D)
// However with 16 bit textures it definitely works better (so it's probably correct to leave it defined)
#ifdef __EMSCRIPTEN__ // will use a MSM4-16bit texture
# undef SHADOW_MAP_USE_OPTIMIZED_MOMENT_QUANTIZATION
# define SHADOW_MAP_USE_OPTIMIZED_MOMENT_QUANTIZATION // Otherwise some artifacts (even if some uniforms are tweaked for 16-bit textures)
#endif //__EMSCRIPTEN__
#include "helper_functions.h" // please search this .c file for "Helper_":
// only very few of its functions are used.
#include <stdio.h>
#include <math.h>
#include <string.h>
// Config file handling: basically there's an .ini file next to the
// exe that you can tweak. (it's just an extra)
const char* ConfigFileName = PROGRAM_NAME".ini";
typedef struct {
int fullscreen_width,fullscreen_height;
int windowed_width,windowed_height;
int fullscreen_enabled;
int show_fps;
} Config;
void Config_Init(Config* c) {
c->fullscreen_width=c->fullscreen_height=0;
c->windowed_width=960;c->windowed_height=540;
c->fullscreen_enabled=0;
c->show_fps = 0;
}
int Config_Load(Config* c,const char* filePath) {
FILE* f = fopen(filePath, "rt");
char ch='\0';char buf[256]="";
size_t nread=0;
int numParsedItem=0;
if (!f) return -1;
while ((ch = fgetc(f)) !=EOF) {
buf[nread]=ch;
nread++;
if (nread>255) {
nread=0;
continue;
}
if (ch=='\n') {
buf[nread]='\0';
if (nread<2 || buf[0]=='[' || buf[0]=='#') {nread = 0;continue;}
if (nread>2 && buf[0]=='/' && buf[1]=='/') {nread = 0;continue;}
// Parse
switch (numParsedItem) {
case 0:
sscanf(buf, "%d %d", &c->fullscreen_width,&c->fullscreen_height);
break;
case 1:
sscanf(buf, "%d %d", &c->windowed_width,&c->windowed_height);
break;
case 2:
sscanf(buf, "%d", &c->fullscreen_enabled);
break;
case 4:
sscanf(buf, "%d", &c->show_fps);
break;
}
nread=0;
++numParsedItem;
}
}
fclose(f);
if (c->windowed_width<=0) c->windowed_width=720;
if (c->windowed_height<=0) c->windowed_height=405;
return 0;
}
int Config_Save(Config* c,const char* filePath) {
FILE* f = fopen(filePath, "wt");
if (!f) return -1;
fprintf(f, "[Size In Fullscreen Mode (zero means desktop size)]\n%d %d\n",c->fullscreen_width,c->fullscreen_height);
fprintf(f, "[Size In Windowed Mode]\n%d %d\n",c->windowed_width,c->windowed_height);
fprintf(f, "[Fullscreen Enabled (0 or 1) (CTRL+RETURN)]\n%d\n", c->fullscreen_enabled);
fprintf(f, "[Show FPS (0 or 1) (F2)]\n%d\n", c->show_fps);
fprintf(f,"\n");
fclose(f);
return 0;
}
Config config;
// glut has a special fullscreen GameMode that you can toggle with CTRL+RETURN (not in WebGL)
int windowId = 0; // window Id when not in fullscreen mode
int gameModeWindowId = 0; // window Id when in fullscreen mode
// Now we can start with our program
// camera data:
float targetPos[3]; // please set it in resetCamera()
float cameraYaw; // please set it in resetCamera()
float cameraPitch; // please set it in resetCamera()
float cameraDistance; // please set it in resetCamera()
float cameraPos[3]; // Derived value (do not edit)
float vMatrix[16]; // view matrix
float cameraSpeed = 0.5f; // When moving it
// light data
float lightYaw = M_PI*0.425f,lightPitch = M_PI*0.235f; // must be copied to resetLight() too
float lightDirection[4] = {0,1,0,0}; // Derived value (do not edit) [lightDirection[3]==0]
// pMatrix data:
float pMatrix[16]; // projection matrix
const float pMatrixFovyDeg = 45.f; // smaller => better shadow resolution
const float pMatrixNearPlane = 0.5f; // bigger => better shadow resolution
const float pMatrixFarPlane = 20.f; // smaller => better shadow resolution
float instantFrameTime = 16.2f;
// Optional (to speed up Helper_GlutDrawGeometry(...) a bit)
GLuint gDisplayListBase = 0;GLuint* pgDisplayListBase = &gDisplayListBase; // Can be set to 0 as a fallback.
static const char* ShadowPassVertexShader[] = {
"varying vec4 v_position;\n"
"\n"
" void main() {\n"
" gl_Position = ftransform();\n"
" v_position = gl_Position;\n"
" }\n"
};
static const char* ShadowPassFragmentShader[] = {
"varying vec4 v_position;\n"
"\n"
"vec4 ComputeMoments(float FragmentDepth) {\n"
" float Square=FragmentDepth*FragmentDepth;\n"
" vec4 mu = vec4(FragmentDepth,Square,Square*FragmentDepth,Square*Square);\n"
# ifndef SHADOW_MAP_USE_OPTIMIZED_MOMENT_QUANTIZATION
" return mu;\n"
# else //SHADOW_MAP_USE_OPTIMIZED_MOMENT_QUANTIZATION
# ifdef SHADOW_MAP_OPTIMIZED_MOMENT_QUANTIZATION_USE_TRANSPOSE_MATRIX
" const mat4 matr = mat4(-2.07224649, 13.7948857237, 0.105877704, 9.7924062118,\n"
" 32.23703778, -59.4683975703, -1.9077466311, -33.7652110555,\n"
" -68.571074599, 82.0359750338, 9.3496555107, 47.9456096605,\n"
" 39.3703274134,-35.364903257, -6.6543490743, -23.9728048165);\n"
# else //SHADOW_MAP_OPTIMIZED_MOMENT_QUANTIZATION_USE_TRANSPOSE_MATRIX
" const mat4 matr = mat4(-2.07224649, 32.23703778, -68.571074599, 39.3703274134,\n"
" 13.7948857237, -59.4683975703, 82.0359750338, -35.364903257,\n"
" 0.105877704, -1.9077466311, 9.3496555107, -6.6543490743,\n"
" 9.7924062118,-33.7652110555, 47.9456096605, -23.9728048165);\n"
# endif //SHADOW_MAP_OPTIMIZED_MOMENT_QUANTIZATION_USE_TRANSPOSE_MATRIX
" vec4 mo = matr*mu;\n"
" mo[0]+=0.0359558848;\n"
" return mo;\n"
# endif //SHADOW_MAP_USE_OPTIMIZED_MOMENT_QUANTIZATION
"}\n"
"\n"
" void main() {\n"
" float depth = v_position.z/v_position.w;\n"
" depth = depth * 0.5 + 0.5; //Don't forget to move away from unit cube ([-1,1]) to [0,1] coordinate system\n"
"\n"
" gl_FragColor = ComputeMoments(depth);\n"
" }\n"
};
typedef struct {
GLuint fbo;
GLuint depthTextureId;
GLuint colorTextureId;
GLuint program;
} ShadowPass;
ShadowPass shadowPass;
void InitShadowPass(ShadowPass* sp) {
sp->program = Helper_LoadShaderProgramFromSource(*ShadowPassVertexShader,*ShadowPassFragmentShader);
// create depth texture
glGenTextures(1, &sp->depthTextureId);
glBindTexture(GL_TEXTURE_2D, sp->depthTextureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
# ifndef __EMSCRIPTEN__
glTexImage2D( GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, SHADOW_MAP_RESOLUTION, SHADOW_MAP_RESOLUTION, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0);
# else //__EMSCRIPTEN__
glTexImage2D( GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, SHADOW_MAP_RESOLUTION, SHADOW_MAP_RESOLUTION, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, 0);
# undef SHADOW_MAP_CLAMP_MODE
# define SHADOW_MAP_CLAMP_MODE GL_CLAMP_TO_EDGE
# endif //__EMSCRIPTEN__
if (SHADOW_MAP_CLAMP_MODE==GL_CLAMP_TO_BORDER) {
const GLfloat border[] = {1.0f,1.0f,1.0f,0.0f };
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border);
}
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, SHADOW_MAP_CLAMP_MODE );
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, SHADOW_MAP_CLAMP_MODE );
glBindTexture(GL_TEXTURE_2D, 0);
// create texture
glGenTextures(1, &sp->colorTextureId);
glBindTexture(GL_TEXTURE_2D, sp->colorTextureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, SHADOW_MAP_FILTER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
# ifndef __EMSCRIPTEN__
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA32F, SHADOW_MAP_RESOLUTION, SHADOW_MAP_RESOLUTION, 0, GL_RGBA, GL_FLOAT, 0);
# else //__EMSCRIPTEN__
//glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA16, SHADOW_MAP_RESOLUTION, SHADOW_MAP_RESOLUTION, 0, GL_RGBA, GL_UNSIGNED_INT, 0);
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA16F, SHADOW_MAP_RESOLUTION, SHADOW_MAP_RESOLUTION, 0, GL_RGBA, GL_FLOAT, 0);
# undef SHADOW_MAP_CLAMP_MODE
# define SHADOW_MAP_CLAMP_MODE GL_CLAMP_TO_EDGE
# endif //__EMSCRIPTEN__
if (SHADOW_MAP_CLAMP_MODE==GL_CLAMP_TO_BORDER) {
const GLfloat border[] = {1.0f,1.0f,1.0f,0.0f };
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border);
}
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, SHADOW_MAP_CLAMP_MODE );
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, SHADOW_MAP_CLAMP_MODE );
# if (SHADOW_MAP_FILTER==GL_LINEAR_MIPMAP_LINEAR || SHADOW_MAP_FILTER==GL_LINEAR_MIPMAP_NEAREST || SHADOW_MAP_FILTER==GL_NEAREST_MIPMAP_LINEAR || SHADOW_MAP_FILTER==GL_NEAREST_MIPMAP_NEAREST)
glGenerateMipmap(GL_TEXTURE_2D);
# endif
glBindTexture(GL_TEXTURE_2D, 0);
// create depth fbo
glGenFramebuffers(1, &sp->fbo);
glBindFramebuffer(GL_FRAMEBUFFER, sp->fbo);
# ifndef __EMSCRIPTEN__
//glDrawBuffer(GL_NONE); // Instruct openGL that we won't bind a color texture with the currently bound FBO
glReadBuffer(GL_NONE); // Maybe this line can be activated
# endif //__EMSCRIPTEN__
glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D, sp->colorTextureId, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER,GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, sp->depthTextureId, 0);
{
//Does the GPU support current FBO configuration?
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status!=GL_FRAMEBUFFER_COMPLETE) printf("glCheckFramebufferStatus(...) FAILED for shadowPass.fbo.\n");
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void DestroyShadowPass(ShadowPass* sp) {
if (sp->program) {glDeleteProgram(sp->program);sp->program=0;}
if (sp->fbo) {glDeleteBuffers(1,&sp->fbo);sp->fbo=0;}
if (sp->depthTextureId) {glDeleteTextures(1,&sp->depthTextureId);sp->depthTextureId=0;}
if (sp->colorTextureId) {glDeleteTextures(1,&sp->colorTextureId);sp->colorTextureId=0;}
}
static const char* DefaultPassVertexShader[] = {
"uniform mat4 u_biasedShadowMvpMatrix;\n" // (*) Actually it's already multiplied with vMatrixInverse (in C code, so that the multiplication can be easily done with doubles)
"varying vec4 v_shadowCoord;\n"
"varying vec4 v_diffuse;\n"
"\n"
"void main() {\n"
" gl_Position = ftransform();\n"
"\n"
" vec3 normal = gl_NormalMatrix * gl_Normal;\n"
" vec3 lightVector = gl_LightSource[0].position.xyz\n;// - gl_Vertex.xyz;\n"
" float nxDir = max(0.0, dot(normal, lightVector));\n"
" v_diffuse = gl_LightSource[0].diffuse * nxDir; \n"
"\n"
" gl_FrontColor = gl_Color;\n"
"\n"
" v_shadowCoord = u_biasedShadowMvpMatrix*(gl_ModelViewMatrix*gl_Vertex);\n" // (*) We don't pass a 'naked' mMatrix in shaders (not robust to double precision usage). We dress it in a mvMatrix. So here we're passing a mMatrix from camera space to light space (through a mvMatrix).
"}\n" // (the bias just converts clip space to texture space)
};
static const char* DefaultPassFragmentShader[] = {
"//#extension GL_ARB_gpu_shader5 : enable\n" // fma needs it [but if breaks textureGrad(...) if USE_TEXTUREGRAD is defined) We keep the warning.
"\n"
"uniform sampler2D u_shadowMap;\n"
"uniform vec2 u_shadowLightBleedingReductionAndDarkening;\n" // Both values in [0.0-1.0]
"uniform vec2 u_shadowDepthAndMomentBiases;\n"
"\n"
"varying vec4 v_shadowCoord;\n"
"varying vec4 v_diffuse;\n"
"\n"
"float FMA(float a,float b,float c) {\n"
# ifdef USE_GLSL_FMA
" return fma(a,b,c);\n"
# else //USE_GLSL_FMA
" return a*b+c;\n"
# endif //USE_GLSL_FMA
"}\n"
"\n" // Please see https://github.com/TheRealMJP/Shadows:
"float ComputeMSM(vec4 moments,float fragmentDepth,float depthBias,float momentBias) {\n"
" // Bias input data to avoid artifacts\n"
" vec4 b = mix(moments,vec4(0.5, 0.5, 0.5, 0.5),momentBias);\n"
" vec3 z;z[0] = fragmentDepth - depthBias;\n"
" \n"
" // Compute a Cholesky factorization of the Hankel matrix B storing only non-\n"
" // trivial entries or related products\n"
" float L32D22 = FMA(-b[0], b[1], b[2]);\n"
" float D22 = FMA(-b[0], b[0], b[1]);\n"
" float squaredDepthVariance = FMA(-b[1], b[1], b[3]);\n"
" float D33D22 = dot(vec2(squaredDepthVariance, -L32D22), vec2(D22, L32D22));\n"
" float InvD22 = 1.0 / D22;\n"
" float L32 = L32D22 * InvD22;\n"
" \n"
" // Obtain a scaled inverse image of bz = (1,z[0],z[0]*z[0])^T\n"
" vec3 c = vec3(1.0, z[0], z[0] * z[0]);\n"
" \n"
" // Forward substitution to solve L*c1=bz\n"
" c[1] -= b.x;\n"
" c[2] -= b.y + L32 * c[1];\n"
" \n"
" // Scaling to solve D*c2=c1\n"
" c[1] *= InvD22;\n"
" c[2] *= D22 / D33D22;\n"
" \n"
" // Backward substitution to solve L^T*c3=c2\n"
" c[1] -= L32 * c[2];\n"
" c[0] -= dot(c.yz, b.xy);\n"
" \n"
" // Solve the quadratic equation c[0]+c[1]*z+c[2]*z^2 to obtain solutions\n"
" // z[1] and z[2]\n"
" float p = c[1] / c[2];\n"
" float q = c[0] / c[2];\n"
" float D = (p * p * 0.25) - q;\n"
" float r = sqrt(D);\n"
" z[1] =- p * 0.5 - r;\n"
" z[2] =- p * 0.5 + r;\n"
" \n"
# ifndef SHADOW_MAP_USE_MSM_HAUSDORFF // Hamburger here
" // Compute the shadow intensity by summing the appropriate weights\n"
" vec4 switchVal = (z[2] < z[0]) ? vec4(z[1], z[0], 1.0, 1.0) :\n"
" ((z[1] < z[0]) ? vec4(z[0], z[1], 0.0, 1.0) :\n"
" vec4(0.0,0.0,0.0,0.0));\n"
" float quotient = (switchVal[0] * z[2] - b[0] * (switchVal[0] + z[2]) + b[1])/((z[2] - switchVal[1]) * (z[0] - z[1]));\n"
" float shadowIntensity = switchVal[2] + switchVal[3] * quotient;\n"
# else // SHADOW_MAP_USE_MSM_HAUSDORFF // Hausdorff here
" float shadowIntensity = 1.0;\n"
" \n"
" // Use a solution made of four deltas if the solution with three deltas is invalid\n"
" if(z[1] < 0.0 || z[2] > 1.0) {\n"
" float zFree = ((b[2] - b[1]) * z[0] + b[2] - b[3]) / ((b[1] - b[0]) * z[0] + b[1] - b[2]);\n"
" float w1Factor = (z[0] > zFree) ? 1.0 : 0.0;\n"
" shadowIntensity = (b[1] - b[0] + (b[2] - b[0] - (zFree + 1.0) * (b[1] - b[0])) * (zFree - w1Factor - z[0])\n"
" /(z[0] * (z[0] - zFree))) / (zFree - w1Factor) + 1.0 - b[0];\n"
" }\n"
" // Use the solution with three deltas\n"
" else {\n"
" vec4 switchVal = (z[2] < z[0]) ? vec4(z[1], z[0], 1.0, 1.0) :\n"
" ((z[1] < z[0]) ? vec4(z[0], z[1], 0.0, 1.0) :\n"
" vec4(0.0, 0.0, 0.0, 0.0));\n"
" float quotient = (switchVal[0] * z[2] - b[0] * (switchVal[0] + z[2]) + b[1]) / ((z[2] - switchVal[1]) * (z[0] - z[1]));\n"
" shadowIntensity = switchVal[2] + switchVal[3] * quotient;\n"
" }\n"
# endif //SHADOW_MAP_USE_MSM_HAUSDORFF
" return 1.0 - clamp(shadowIntensity,0.0,1.0);\n"
"}\n"
"\n"
"float linstep(float low, float high, float v) {\n"
" return clamp((v-low)/(high-low), 0.0, 1.0);\n"
"}\n"
"\n"
" vec4 ConvertMoments(vec4 optimizedMoments) {\n"
# ifndef SHADOW_MAP_USE_OPTIMIZED_MOMENT_QUANTIZATION
" return optimizedMoments;\n"
# else //SHADOW_MAP_USE_OPTIMIZED_MOMENT_QUANTIZATION
" optimizedMoments[0] -= 0.0359558848;\n"
# ifdef SHADOW_MAP_OPTIMIZED_MOMENT_QUANTIZATION_USE_TRANSPOSE_MATRIX
" const mat4 matr = mat4(0.2227744146, 0.1549679261, 0.1451988946, 0.163127443,\n"
" 0.0771972861, 0.1394629426, 0.2120202157, 0.2591432266,\n"
" 0.7926986636,0.7963415838, 0.7258694464, 0.6539092497,\n"
" 0.0319417555,-0.1722823173,-0.2758014811,-0.3376131734);\n"
# else //SHADOW_MAP_OPTIMIZED_MOMENT_QUANTIZATION_USE_TRANSPOSE_MATRIX
" const mat4 matr = mat4(0.2227744146, 0.0771972861, 0.7926986636, 0.0319417555,\n"
" 0.1549679261, 0.1394629426, 0.7963415838, -0.1722823173,\n"
" 0.1451988946,0.2120202157,0.7258694464, -0.2758014811,\n"
" 0.163127443,0.2591432266,0.6539092497,-0.3376131734);\n"
# endif //SHADOW_MAP_OPTIMIZED_MOMENT_QUANTIZATION_USE_TRANSPOSE_MATRIX
" return matr*optimizedMoments;\n"
# endif //SHADOW_MAP_USE_OPTIMIZED_MOMENT_QUANTIZATION
"}\n"
"\n"
"void main() {\n"
" vec4 shadowCoordinateWdivide = v_shadowCoord/v_shadowCoord.w;\n"
# ifdef USE_GLSL_TEXTUREGRAD // https://github.com/TheRealMJP/Shadows uses this... but I'm not sure if it's really necessary or not...
" vec3 shadowPosDX = dFdx(shadowCoordinateWdivide).xyz;\n" // These seem to work even when they are vec2. What's the difference ?
" vec3 shadowPosDY = dFdy(shadowCoordinateWdivide).xyz;\n"
" vec4 moments = ConvertMoments(textureGrad(u_shadowMap, shadowCoordinateWdivide.xy, shadowPosDX, shadowPosDY));\n"
# else // USE_GLSL_TEXTUREGRAD
" vec4 moments = ConvertMoments(texture2D(u_shadowMap, shadowCoordinateWdivide.xy));\n"
# endif //USE_GLSL_TEXTUREGRAD
" float shadowFactor = ComputeMSM(moments,shadowCoordinateWdivide.z,u_shadowDepthAndMomentBiases.x*0.001,u_shadowDepthAndMomentBiases.y*0.001);\n"
# ifdef SHADOW_MAP_USE_SMOOTHSTEP_FOR_LIGHT_BLEEDING_REDUCTION
" shadowFactor = smoothstep(u_shadowLightBleedingReductionAndDarkening.x,1.0,shadowFactor);\n" // https://github.com/TheRealMJP/Shadows applies this before taking the min(...). Is this the same ?
# else //SHADOW_MAP_USE_SMOOTHSTEP_FOR_LIGHT_BLEEDING_REDUCTION
" shadowFactor = linstep(u_shadowLightBleedingReductionAndDarkening.x,1.0,shadowFactor);\n" // https://github.com/TheRealMJP/Shadows applies this before taking the min(...). Is this the same ?
# endif //SHADOW_MAP_USE_SMOOTHSTEP_FOR_LIGHT_BLEEDING_REDUCTION
" shadowFactor = u_shadowLightBleedingReductionAndDarkening.y + (1.0-u_shadowLightBleedingReductionAndDarkening.y)*shadowFactor;\n"
" \n"
" gl_FragColor = gl_LightSource[0].ambient + (v_diffuse * vec4(gl_Color.rgb*shadowFactor,1.0));\n"
"}\n"
};
typedef struct {
GLuint program;
GLint uniform_location_biasedShadowMvpMatrix;
GLint uniform_location_shadowMap;
GLint uniform_location_shadowLightBleedingReductionAndDarkening;
GLint uniform_location_shadowDepthAndMomentBiases;
} DefaultPass;
DefaultPass defaultPass;
void InitDefaultPass(DefaultPass* dp) {
dp->program = Helper_LoadShaderProgramFromSource(*DefaultPassVertexShader,*DefaultPassFragmentShader);
dp->uniform_location_biasedShadowMvpMatrix = glGetUniformLocation(dp->program,"u_biasedShadowMvpMatrix");
dp->uniform_location_shadowMap = glGetUniformLocation(dp->program,"u_shadowMap");
dp->uniform_location_shadowLightBleedingReductionAndDarkening = glGetUniformLocation(dp->program,"u_shadowLightBleedingReductionAndDarkening");
dp->uniform_location_shadowDepthAndMomentBiases = glGetUniformLocation(dp->program,"u_shadowDepthAndMomentBiases");
glUseProgram(dp->program);
glUniform1i(dp->uniform_location_shadowMap,0);
# ifndef __EMSCRIPTEN__
glUniform2f(dp->uniform_location_shadowLightBleedingReductionAndDarkening,0.0,0.5); // Both values in [0.0-1.0]
glUniform2f(dp->uniform_location_shadowDepthAndMomentBiases,0.00005,0.0002);
# else //__EMSCRIPTEN__
glUniform2f(dp->uniform_location_shadowLightBleedingReductionAndDarkening,0.65,0.5); // Both values in [0.0-1.0]
glUniform2f(dp->uniform_location_shadowDepthAndMomentBiases,0.5,1.0);
# endif //__EMSCRIPTEN__
//glUniformMatrix4fv(dp->uniform_location_biasedShadowMvpMatrix, 1 /*only setting 1 matrix*/, GL_FALSE /*transpose?*/, Matrix);
glUseProgram(0);
}
void DestroyDefaultPass(DefaultPass* dp) {
if (dp->program) {glDeleteProgram(dp->program);dp->program=0;}
}
#if SHADOW_MAP_BLUR_KERNEL_SIZE>1
// Mostly adapted from the Github repository: https://github.com/Jam3/glsl-fast-gaussian-blur/ (MIT license)
// Probably to be optimized a bit... Also there's no penumbra. Why ?
static const char* BlurPassVertexShader[] = {
"varying vec2 v_uv;\n"
"\n"
"void main() {\n"
" gl_Position = gl_Vertex;\n"
" v_uv = gl_MultiTexCoord0.xy;\n"
"}\n"
};
static const char* BlurPassFragmentShader[] = {
"#define SHADOW_MAP_BLUR_KERNEL_SIZE "XSTR_MACRO(SHADOW_MAP_BLUR_KERNEL_SIZE)"\n"
"uniform vec2 u_resolution;\n" // Maybe using the C macro would be faser
"uniform sampler2D u_sampler;\n"
"uniform vec2 u_direction;\n"
"\n"
"varying vec2 v_uv;\n"
"\n"
# ifndef SHADOW_MAP_BLUR_USING_BOX_FILTER
# if SHADOW_MAP_BLUR_KERNEL_SIZE==3
" vec4 blur(sampler2D image,vec2 uv,vec2 resolution,vec2 direction) {\n" // Not in https://github.com/Jam3/glsl-fast-gaussian-blur/. [Not sure code is correct]
" vec4 color = vec4(0.0);\n"
" vec2 off1 = vec2(0.5) * direction / resolution;\n"
" color += texture2D(image, uv + off1) * 0.5;\n"
" color += texture2D(image, uv - off1) * 0.5;\n"
" return color;\n"
" }\n"
"\n"
# elif SHADOW_MAP_BLUR_KERNEL_SIZE==5
" vec4 blur(sampler2D image,vec2 uv,vec2 resolution,vec2 direction) {\n"
" vec4 color = vec4(0.0);\n"
" vec2 off1 = vec2(1.3333333333333333) * direction / resolution;\n"
" color += texture2D(image, uv) * 0.29411764705882354;\n"
" color += texture2D(image, uv + off1) * 0.35294117647058826;\n"
" color += texture2D(image, uv - off1) * 0.35294117647058826;\n"
" return color;\n"
" }\n"
"\n"
# elif SHADOW_MAP_BLUR_KERNEL_SIZE==9
" vec4 blur(sampler2D image,vec2 uv,vec2 resolution,vec2 direction) {\n"
" vec4 color = vec4(0.0);\n"
" vec2 off1 = vec2(1.3846153846) * direction / resolution;\n"
" vec2 off2 = vec2(3.2307692308) * direction / resolution;\n"
" color += texture2D(image, uv) * 0.2270270270;\n"
" color += texture2D(image, uv + off1) * 0.3162162162;\n"
" color += texture2D(image, uv - off1) * 0.3162162162;\n"
" color += texture2D(image, uv + off2) * 0.0702702703;\n"
" color += texture2D(image, uv - off2) * 0.0702702703;\n"
" return color;\n"
" }\n"
"\n"
# elif SHADOW_MAP_BLUR_KERNEL_SIZE==13
" vec4 blur(sampler2D image,vec2 uv,vec2 resolution,vec2 direction) {\n"
" vec4 color = vec4(0.0);\n"
" vec2 off1 = vec2(1.411764705882353) * direction / resolution;\n"
" vec2 off2 = vec2(3.2941176470588234) * direction / resolution;\n"
" vec2 off3 = vec2(5.176470588235294) * direction / resolution;\n"
" color += texture2D(image, uv) * 0.1964825501511404;\n"
" color += texture2D(image, uv + off1) * 0.2969069646728344;\n"
" color += texture2D(image, uv - off1) * 0.2969069646728344;\n"
" color += texture2D(image, uv + off2) * 0.09447039785044732;\n"
" color += texture2D(image, uv - off2) * 0.09447039785044732;\n"
" color += texture2D(image, uv + off3) * 0.010381362401148057;\n"
" color += texture2D(image, uv - off3) * 0.010381362401148057;\n"
" return color;\n"
" }\n"
"\n"
# else // SHADOW_MAP_BLUR_KERNEL_SIZE
# error SHADOW_MAP_BLUR_KERNEL_SIZE unsupported value
# endif // SHADOW_MAP_BLUR_KERNEL_SIZE
# else //SHADOW_MAP_BLUR_USING_BOX_FILTER
" vec4 blur(sampler2D image,vec2 uv,vec2 resolution,vec2 direction) {\n" // Made this myself [Not sure code is correct]
" const float edgeVal = 0.5+float((SHADOW_MAP_BLUR_KERNEL_SIZE/2-1));\n"
" const float startVal = -edgeVal;\n"
" const float endVal = edgeVal+0.5;\n" // we use +0.5 and < instead of <= in the for loop (more robust)
" vec2 off = direction/resolution;\n"
" float x;\n"
" vec4 color = vec4(0.0);\n"
" for (x=startVal;x<endVal;x+=1.0) {\n"
" color+=texture2D(image, uv+vec2(x*off.x,x*off.y));\n"
" }\n"
" color/=float(SHADOW_MAP_BLUR_KERNEL_SIZE-1);\n"
" return color;\n"
" }\n"
# endif //SHADOW_MAP_BLUR_USING_BOX_FILTER
"void main() {\n"
" gl_FragColor = blur(u_sampler,v_uv,u_resolution.xy,u_direction);"
"}\n"
};
typedef struct {
GLuint program;
GLuint textureId;
GLuint fbo;
GLint uniform_location_resolution;
GLint uniform_location_sampler;
GLint uniform_location_direction;
} BlurPass;
BlurPass blurPass;
void InitBlurPass(BlurPass* bp) {
bp->program = Helper_LoadShaderProgramFromSource(*BlurPassVertexShader,*BlurPassFragmentShader);
bp->uniform_location_resolution = glGetUniformLocation(bp->program,"u_resolution");
bp->uniform_location_sampler = glGetUniformLocation(bp->program,"u_sampler");
bp->uniform_location_direction = glGetUniformLocation(bp->program,"u_direction");
glUseProgram(bp->program);
glUniform1i(bp->uniform_location_sampler,0);
glUniform2f(bp->uniform_location_resolution,(float)(SHADOW_MAP_RESOLUTION),(float)(SHADOW_MAP_RESOLUTION));
glUniform2f(bp->uniform_location_direction,1.0f,0.0f);
glUseProgram(0);
// create texture
glGenTextures(1, &bp->textureId);
glBindTexture(GL_TEXTURE_2D, bp->textureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
# ifndef __EMSCRIPTEN__
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA32F, SHADOW_MAP_RESOLUTION, SHADOW_MAP_RESOLUTION, 0, GL_RGBA, GL_FLOAT, 0);
# else //__EMSCRIPTEN__
//glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA16, SHADOW_MAP_RESOLUTION, SHADOW_MAP_RESOLUTION, 0, GL_RGBA, GL_UNSIGNED_INT, 0);
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA16F, SHADOW_MAP_RESOLUTION, SHADOW_MAP_RESOLUTION, 0, GL_RGBA, GL_FLOAT, 0);
# undef SHADOW_MAP_CLAMP_MODE
# define SHADOW_MAP_CLAMP_MODE GL_CLAMP_TO_EDGE
# endif //__EMSCRIPTEN__
if (SHADOW_MAP_CLAMP_MODE==GL_CLAMP_TO_BORDER) {
const GLfloat border[] = {1.0f,1.0f,1.0f,0.0f };
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border);
}
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, SHADOW_MAP_CLAMP_MODE );
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, SHADOW_MAP_CLAMP_MODE );
glBindTexture(GL_TEXTURE_2D, 0);
// create depth fbo
glGenFramebuffers(1, &bp->fbo);
glBindFramebuffer(GL_FRAMEBUFFER, bp->fbo);
# ifndef __EMSCRIPTEN__
//glDrawBuffer(GL_NONE); // Instruct openGL that we won't bind a color texture with the currently bound FBO
glReadBuffer(GL_NONE); // Maybe this line can be activated
# endif //__EMSCRIPTEN__
glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D, bp->textureId, 0);
{
//Does the GPU support current FBO configuration?
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status!=GL_FRAMEBUFFER_COMPLETE) printf("glCheckFramebufferStatus(...) FAILED for blurPass.fbo.\n");
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void DestroyBlurPass(BlurPass* bp) {
if (bp->program) {glDeleteProgram(bp->program);bp->program=0;}
if (bp->fbo) {glDeleteBuffers(1,&bp->fbo);bp->fbo=0;}
if (bp->textureId) {glDeleteTextures(1,&bp->textureId);bp->textureId=0;}
}
#endif //SHADOW_MAP_BLUR_KERNEL_SIZE
float current_width=0,current_height=0,current_aspect_ratio=1; // Not sure when I've used these...
void ResizeGL(int w,int h) {
current_width = (float) w;
current_height = (float) h;
if (current_height!=0) current_aspect_ratio = current_width/current_height;
if (h>0) {
// We set our pMatrix
Helper_Perspective(pMatrix,pMatrixFovyDeg,(float)w/(float)h,pMatrixNearPlane,pMatrixFarPlane);
glMatrixMode(GL_PROJECTION);glLoadMatrixf(pMatrix);glMatrixMode(GL_MODELVIEW);
}
if (w>0 && h>0 && !config.fullscreen_enabled) {
// On exiting we'll like to save these data back
config.windowed_width=w;
config.windowed_height=h;
}
glViewport(0,0,w,h); // This is what people often call in ResizeGL()
}
void InitGL(void) {
// These are important, but often overlooked OpenGL calls
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Otherwise transparent objects are not displayed correctly
glClearColor(0.3f, 0.6f, 1.0f, 1.0f);
glEnable(GL_TEXTURE_2D); // Only needed for ffp, when VISUALIZE_DEPTH_TEXTURE is defined
// ffp stuff
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_NORMALIZE);
// New
InitShadowPass(&shadowPass);
InitDefaultPass(&defaultPass);
# if SHADOW_MAP_BLUR_KERNEL_SIZE>1
InitBlurPass(&blurPass);
# endif
// New
# ifdef USE_GLSL_TEXTUREGRAD
//glHint(GL_FRAGMENT_SHADER_DERIVATIVE_HINT,GL_NICEST); // Optional if USE_GLSL_TEXTUREGRAD is defined in the default pass fragment shader (GL_FASTEST, GL_NICEST, and GL_DONT_CARE)
# endif //USE_GLSL_TEXTUREGRAD
// Please note that after InitGL(), this implementation calls ResizeGL(...,...).
// If you copy/paste this code you can call it explicitly...
}
void DestroyGL() {
// New
DestroyShadowPass(&shadowPass);
DestroyDefaultPass(&defaultPass);
# if SHADOW_MAP_BLUR_KERNEL_SIZE>1
DestroyBlurPass(&blurPass);
# endif
// 40 display lists are generated by Helper_GlutDrawGeometry(...) if pgDisplayListBase!=0
if (pgDisplayListBase && *pgDisplayListBase) {glDeleteLists(*pgDisplayListBase,40);*pgDisplayListBase=0;}
}
void DrawGL(void)
{
// All the things about time are just used to display FPS (F2)
// or to move objects around (NOT for shadow)
static unsigned begin = 0;
static unsigned cur_time = 0;
unsigned elapsed_time,delta_time;
float elapsedMs;float cosAlpha,sinAlpha; // used to move objects around
// These two instead are necessary for shadow mapping
static float vMatrixInverse[16]; // view Matrix inverse (it's the camera matrix).
static float lvpMatrix[16]; // = light_pMatrix*light_vMatrix
// Just some time stuff here
if (begin==0) begin = glutGet(GLUT_ELAPSED_TIME);
elapsed_time = glutGet(GLUT_ELAPSED_TIME) - begin;
delta_time = elapsed_time - cur_time;
instantFrameTime = (float)delta_time*0.001f;
cur_time = elapsed_time;
elapsedMs = (float)elapsed_time;
cosAlpha = cos(elapsedMs*0.0005f);
sinAlpha = sin(elapsedMs*0.00075f);
// view Matrix
Helper_LookAt(vMatrix,cameraPos[0],cameraPos[1],cameraPos[2],targetPos[0],targetPos[1],targetPos[2],0,1,0);
glLoadMatrixf(vMatrix);
glLightfv(GL_LIGHT0,GL_POSITION,lightDirection); // Important: the ffp must recalculate internally lightDirectionEyeSpace based on vMatrix [=> every frame]
// view Matrix inverse (it's the camera matrix). Used twice below (and very important to keep in any case).
Helper_InvertMatrixFast(vMatrixInverse,vMatrix); // We can use Helper_InvertMatrixFast(...) instead of Helper_InvertMatrix(...) here [No scaling inside and no projection matrix]
// Draw to Shadow Map------------------------------------------------------------------------------------------
{
Helper_GetLightViewProjectionMatrix(lvpMatrix,
vMatrixInverse,pMatrixNearPlane,pMatrixFarPlane,pMatrixFovyDeg,current_aspect_ratio,
lightDirection,1.0f/(float)SHADOW_MAP_RESOLUTION);
// Draw to shadow map texture
glMatrixMode(GL_PROJECTION);glPushMatrix();glLoadIdentity();glMatrixMode(GL_MODELVIEW); // We'll set the combined light view-projection matrix in GL_MODELVIEW (do you know that it's the same?)
glBindFramebuffer(GL_FRAMEBUFFER, shadowPass.fbo);
glViewport(0, 0, SHADOW_MAP_RESOLUTION,SHADOW_MAP_RESOLUTION);
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glCullFace(GL_FRONT);
//glEnable(GL_POLYGON_OFFSET_FILL);glPolygonOffset(-2.0f, -2.0f);
glEnable(GL_DEPTH_CLAMP);
glDisable(GL_LIGHTING);
glUseProgram(shadowPass.program); // we can just use glUseProgram(0) here
glPushMatrix();glLoadMatrixf(lvpMatrix); // we load both (light) projection and view matrices here (it's the same after all)
Helper_GlutDrawGeometry(elapsedMs,cosAlpha,sinAlpha,targetPos,pgDisplayListBase); // Done SHADOW_MAP_NUM_CASCADES times!
glPopMatrix();
glUseProgram(0);
glEnable(GL_LIGHTING);
glDisable(GL_DEPTH_CLAMP);
//glDisable(GL_POLYGON_OFFSET_FILL);
glCullFace(GL_BACK);
glBindFramebuffer(GL_FRAMEBUFFER,0);
glMatrixMode(GL_PROJECTION);glPopMatrix();glMatrixMode(GL_MODELVIEW);
}
# if SHADOW_MAP_BLUR_KERNEL_SIZE>1
// Blur shadow map
{
int i;
glMatrixMode(GL_PROJECTION);glPushMatrix();glLoadIdentity();
glMatrixMode(GL_MODELVIEW);glPushMatrix();glLoadIdentity();
glDisable(GL_DEPTH_TEST);glDepthMask(GL_FALSE);glDisable(GL_CULL_FACE);glDisable(GL_LIGHTING);
glViewport(0, 0, SHADOW_MAP_RESOLUTION,SHADOW_MAP_RESOLUTION);
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
// Two passes: horizontal + vertical are faster
for (i=0;i<2;i++) {
const GLuint FBOs[2] = {blurPass.fbo,shadowPass.fbo}; // Target texture
const GLuint TEXTs[2] = {shadowPass.colorTextureId,blurPass.textureId}; // Source texture
glBindFramebuffer(GL_FRAMEBUFFER, FBOs[i]);
glUseProgram(blurPass.program);
glClear(GL_COLOR_BUFFER_BIT);
glBindTexture(GL_TEXTURE_2D,TEXTs[i]);
if (i==0) glUniform2f(blurPass.uniform_location_direction,1.0f,0.0f); // Horizontal
else glUniform2f(blurPass.uniform_location_direction,0.0f,1.0f); // Vertical
glColor3f(1,1,1);
glBegin(GL_QUADS);
glTexCoord2f(0,0);glVertex2f(-1, -1);
glTexCoord2f(1,0);glVertex2f( 1, -1);
glTexCoord2f(1,1);glVertex2f( 1, 1);
glTexCoord2f(0,1);glVertex2f(-1, 1);
glEnd();
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glUseProgram(0);
glBindTexture(GL_TEXTURE_2D,0);
glEnable(GL_DEPTH_TEST);glDepthMask(GL_TRUE);glEnable(GL_CULL_FACE);glEnable(GL_LIGHTING);
glMatrixMode(GL_PROJECTION);glPopMatrix();
glMatrixMode(GL_MODELVIEW);glPopMatrix();
}
# endif //SHADOW_MAP_BLUR_KERNEL_SIZE>1
// Draw world
{
// biasedShadowMvpMatrix is used only in the DefaultPass:
static float bias[16] = {0.5,0,0,0, 0,0.5,0,0, 0,0,0.5,0, 0.5,0.5,0.5,1}; // Moving from unit cube [-1,1] to [0,1]
static float biasedShadowMvpMatrix[16]; // multiplied per vMatrixInverse
Helper_MultMatrix(biasedShadowMvpMatrix,bias,lvpMatrix);
Helper_MultMatrix(biasedShadowMvpMatrix,biasedShadowMvpMatrix,vMatrixInverse); // We do this, so that when in the vertex shader we multiply it with the camera mvMatrix, we get: biasedShadowMvpMatrix * mMatrix (using mMatrices directly in the shaders prevents the usage of double precision matrices: mvMatrices are good when converted to float to feed the shader, mMatrices are bad)
// Draw to world
glViewport(0, 0, current_width,current_height);
glClearColor(0.3f, 0.6f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBindTexture(GL_TEXTURE_2D,shadowPass.colorTextureId); // or shadowPass.colorTextureId ???
# if (SHADOW_MAP_FILTER==GL_LINEAR_MIPMAP_LINEAR || SHADOW_MAP_FILTER==GL_LINEAR_MIPMAP_NEAREST || SHADOW_MAP_FILTER==GL_NEAREST_MIPMAP_LINEAR || SHADOW_MAP_FILTER==GL_NEAREST_MIPMAP_NEAREST)
glGenerateMipmap(GL_TEXTURE_2D);
# endif
glUseProgram(defaultPass.program);
glUniformMatrix4fv(defaultPass.uniform_location_biasedShadowMvpMatrix, 1 /*only setting 1 matrix*/, GL_FALSE /*transpose?*/,biasedShadowMvpMatrix);
Helper_GlutDrawGeometry(elapsedMs,cosAlpha,sinAlpha,targetPos,pgDisplayListBase); // Done SHADOW_MAP_NUM_CASCADES times!
glUseProgram(0);
glBindTexture(GL_TEXTURE_2D,0);
}
if (config.show_fps && instantFrameTime>0) {
if ((elapsed_time/1000)%2==0) {
printf("FPS=%1.0f\n",1.f/instantFrameTime);fflush(stdout);
config.show_fps=0;
}
}
# ifdef VISUALIZE_DEPTH_TEXTURE
{
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glDepthMask(GL_FALSE);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glColor3f(1,1,1);
glDisable(GL_LIGHTING);
glEnable(GL_BLEND);
glBindTexture(GL_TEXTURE_2D,shadowPass.colorTextureId);
glColor4f(1,1,1,0.9f);
glBegin(GL_QUADS);
glTexCoord2f(0,0);glVertex2f(-1, -1);
glTexCoord2f(1,0);glVertex2f(-0.25*current_aspect_ratio, -1);
glTexCoord2f(1,1);glVertex2f(-0.25*current_aspect_ratio, -0.25/current_aspect_ratio);
glTexCoord2f(0,1);glVertex2f(-1, -0.25/current_aspect_ratio);
glEnd();
glBindTexture(GL_TEXTURE_2D,0);
glDisable(GL_BLEND);
glEnable(GL_LIGHTING);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glDepthMask(GL_TRUE);
}
# endif //VISUALIZE_DEPTH_TEXTURE
}
static void GlutDestroyWindow(void);
static void GlutCreateWindow();
void GlutCloseWindow(void) {Config_Save(&config,ConfigFileName);}
void GlutNormalKeys(unsigned char key, int x, int y) {
const int mod = glutGetModifiers();
switch (key) {
case 27: // esc key
Config_Save(&config,ConfigFileName);
GlutDestroyWindow();
# ifdef __FREEGLUT_STD_H__
glutLeaveMainLoop();
# else
exit(0);
# endif
break;
case 13: // return key
{
if (mod&GLUT_ACTIVE_CTRL) {
config.fullscreen_enabled = gameModeWindowId ? 0 : 1;
GlutDestroyWindow();
GlutCreateWindow();
}
}
break;
}
}
static void updateCameraPos() {
const float distanceY = sin(cameraPitch)*cameraDistance;
const float distanceXZ = cos(cameraPitch)*cameraDistance;
cameraPos[0] = targetPos[0] + sin(cameraYaw)*distanceXZ;
cameraPos[1] = targetPos[1] + distanceY;
cameraPos[2] = targetPos[2] + cos(cameraYaw)*distanceXZ;
}
static void updateDirectionalLight() {
const float distanceY = sin(lightPitch);
const float distanceXZ = cos(lightPitch);
lightDirection[0] = sin(lightYaw)*distanceXZ;
lightDirection[1] = distanceY;
lightDirection[2] = cos(lightYaw)*distanceXZ;
Helper_Vector3Normalize(lightDirection);
lightDirection[3]=0.f;
}
static void resetCamera() {
// You can set the initial camera position here through:
targetPos[0]=0; targetPos[1]=0; targetPos[2]=0; // The camera target point
cameraYaw = 2*M_PI; // The camera rotation around the Y axis
cameraPitch = M_PI*0.125f; // The camera rotation around the XZ plane
cameraDistance = 5; // The distance between the camera position and the camera target point
updateCameraPos();
}
static void resetLight() {
lightYaw = M_PI*0.425f;
lightPitch = M_PI*0.235f;