-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathboxplorer2.cc
executable file
·3398 lines (2880 loc) · 113 KB
/
boxplorer2.cc
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <time.h>
#include <assert.h>
#include <sys/stat.h>
#if !defined(_WIN32)
#include <float.h>
#include <unistd.h>
#define _strdup strdup
#define __FUNCTION__ "boxplorer2"
#define MAX_PATH 256
#else // _WIN32
#include <winsock2.h>
#include <CommDlg.h>
#pragma warning(disable: 4996) // unsafe function
#pragma warning(disable: 4244) // double / float conversion
#pragma warning(disable: 4305) // double / float truncation
#pragma warning(disable: 4800) // forcing value to bool
#pragma comment(lib, "SDL2.lib")
#pragma comment(lib, "SDL2main.lib")
#pragma comment(lib, "opengl32.lib")
#pragma comment(lib, "glu32.lib")
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "shell32.lib")
#pragma comment(lib, "comdlg32.lib")
#include "oculus_sdk4.h"
#if defined(HYDRA)
#include <sixense.h>
#pragma comment(lib, "sixense.lib")
#pragma comment(lib, "sixense_utils.lib")
#endif
#endif // _WIN32
#include <vector>
#include <string>
#include <map>
#include <iostream>
#include <fstream>
#include <sstream>
#include <utility>
using namespace std;
#define NO_SDL_GLEXT
#include <SDL_opengl.h>
#include <SDL.h>
#include <SDL_thread.h>
#include <SDL_main.h>
#include <AntTweakBar.h>
#include "shader_procs.h"
#include "default_shaders.h"
#include "TGA.h"
#include "interpolate.h"
#include "uniforms.h"
#include "camera.h"
#include "shader.h"
#define DEFAULT_CONFIG_FILE "default.cfg"
#define DEFAULT_CONFIG "cfgs/rrrola/" DEFAULT_CONFIG_FILE
#define VERTEX_SHADER_FILE "vertex.glsl"
#define FRAGMENT_SHADER_FILE "fragment.glsl"
#define EFFECTS_VERTEX_SHADER_FILE "effects_vertex.glsl"
#define EFFECTS_FRAGMENT_SHADER_FILE "effects_fragment.glsl"
#define DOF_VERTEX_SHADER_FILE "dof_vertex.glsl"
#define DOF_FRAGMENT_SHADER_FILE "dof_fragment.glsl"
#define FXAA_VERTEX_SHADER_FILE "fxaa_vertex.glsl"
#define FXAA_FRAGMENT_SHADER_FILE "fxaa_fragment.glsl"
#define die(...) ( fprintf(stderr, __VA_ARGS__), _exit(1), 1 )
#ifndef ARRAYSIZE
#define ARRAYSIZE(x) ( sizeof(x)/sizeof((x)[0]) )
#endif
#define CHECK_STATUS(f, v) { \
GLenum __s; \
if ((__s = (f)) != (v)) { \
printf(__FUNCTION__ "[%d] : %s() : %04x\n", __LINE__, #f, __s); \
}}
#define CHECK_ERROR \
CHECK_STATUS(glGetError(), GL_NO_ERROR)
#define CHECK_FRAMEBUFFER \
CHECK_STATUS(glCheckFramebufferStatus(GL_FRAMEBUFFER), \
GL_FRAMEBUFFER_COMPLETE)
#ifdef max
#undef max
#endif
#ifdef min
#undef min
#endif
#include "glsl.h"
// Hackery to get the list of DE and COLORING funcs from the glsl.
map<string, float (*)(GLSL::vec3)> DE_funcs;
map<string, double (*)(GLSL::dvec3)> DE64_funcs;
map<string, GLSL::vec3 (*)(GLSL::vec3)> COLOR_funcs;
class DE_initializer {
public:
DE_initializer(string name, float (*func)(GLSL::vec3)) {
printf("DECLARE_DE(%s)\n", name.c_str());
DE_funcs[name] = func;
}
DE_initializer(string name, double (*func)(GLSL::dvec3)) {
printf("DECLARE_DE(%s)\n", name.c_str());
// Strip _64 from name.
size_t x64 = name.find("_64");
if (x64 != string::npos) name.erase(x64);
DE64_funcs[name] = func;
}
};
#define DECLARE_DE(a) DE_initializer _init##a(#a, &a);
#define DECLARE_COLORING(a) // not interested in color funcs here
string de_func_name;
double (*de_func_64)(GLSL::dvec3) = NULL;
float (*de_func)(GLSL::vec3) = NULL;
namespace GLSL {
// 'globals' capturing the fragment shader output or providing context.
float gl_FragDepth;
vec4 gl_FragColor;
vec4 gl_FragCoord;
// In the c++ version, these are func ptrs, not straight #defines.
// We assign them based on values in .cfg
float (*d)(vec3);
vec3 (*c)(vec3);
// Compile the fragment shader right here.
// This defines a bunch more 'globals' and functions.
#define ST_NONE
#include "cfgs/menger.cfg.data/fragment.glsl"
#undef ST_NONE
} // namespace GLSL
#if defined(_WIN32)
#pragma warning(disable: 4244) // conversion loss
#pragma warning(disable: 4305) // truncation
#endif // _WIN32
#define sign(a) GLSL::sign(a)
#define FPS_FRAMES_TO_AVERAGE 20
const char* kKEYFRAME = "keyframe";
static const char *kHand[] = {
" XX ",
" X..X ",
" X..X ",
" X..X ",
" X..XXXXXX ",
" X..X..X..XXX ",
"XXX X..X..X..X..X ",
"X..XX..X..X..X..X ",
"X...X..X..X..X..X ",
" X..X..X..X..X..X ",
" X..X........X..X ",
" X..X...........X ",
" X..............X ",
" X.............X ",
" X.............X ",
" X...........X ",
" X.........X ",
" X........X ",
" X........X ",
" XXXXXXXXXX ",
};
static SDL_Cursor *init_system_cursor(const char *image[]) {
int i = -1;
Uint8 data[3*20];
Uint8 mask[3*20];
for ( int row=0; row<20; ++row ) {
for ( int col=0; col<24; ++col ) {
if ( col % 8 ) {
data[i] <<= 1; mask[i] <<= 1;
} else {
++i;
data[i] = mask[i] = 0;
}
switch (image[row][col]) {
case '.':
data[i] |= 0x01; mask[i] |= 0x01;
break;
case 'X':
mask[i] |= 0x01;
break;
case ' ':
break;
}
}
}
return SDL_CreateCursor(data, mask, 24, 20, 5, 0);
}
// SDL cursors.
SDL_Cursor* arrow_cursor;
SDL_Cursor* hand_cursor;
void clearGlContext(); // fwd decl.
// Our OpenGL SDL2 window.
static const int kMAXDISPLAYS = 6;
class GFX {
public:
GFX() : display_(-1),
width_(0), height_(0),
last_x_(SDL_WINDOWPOS_CENTERED),
last_y_(SDL_WINDOWPOS_CENTERED),
last_width_(0), last_height_(0),
fullscreen_(false),
window_(NULL),
glcontext_(0) {}
void init() {
//requires SDL_Init(SDL_INIT_VIDEO);
for (ndisplays_ = 0; ndisplays_ < SDL_GetNumVideoDisplays() &&
ndisplays_ < kMAXDISPLAYS; ++ndisplays_) {
SDL_GetCurrentDisplayMode(ndisplays_, &mode_[ndisplays_]);
SDL_GetDisplayBounds(ndisplays_, &rect_[ndisplays_]);
}
}
~GFX() { reset(); }
void reset() {
if (glcontext_) {
clearGlContext();
SDL_GL_DeleteContext(glcontext_);
glcontext_ = 0;
}
if (window_) {
SDL_DestroyWindow(window_);
window_ = NULL;
}
display_ = -1;
}
bool resize(int w, int h) {
int d = display_;
// ignore resize events when fullscreen.
if (fullscreen_) return false;
// ignore resize events for fullscreen width.
if (d != -1 && w == rect_[d].w) return false;
if (window_) {
// capture current display.
d = SDL_GetWindowDisplayIndex(window_);
// capture current window position.
SDL_GetWindowPosition(window_, &last_x_, &last_y_);
}
reset();
printf(__FUNCTION__ ": %dx%d display %d\n", w, h, d);
window_ = SDL_CreateWindow("test",
last_x_, last_y_,
w, h,
SDL_WINDOW_OPENGL|SDL_WINDOW_RESIZABLE);
glcontext_ = SDL_GL_CreateContext(window_);
display_ = d;
last_width_ = width_ = w;
last_height_ = height_ = h;
return enableShaderProcs(); // re-fetch ptrs in new context.
}
bool toggleFullscreen() {
if (!window_) return false;
// capture current display.
int d = SDL_GetWindowDisplayIndex(window_);
if (!fullscreen_) {
// capture current window position.
SDL_GetWindowPosition(window_, &last_x_, &last_y_);
}
reset();
// Oculus / Acer hackery:
// if current resolution matches a display, go
// fullscreen on that display.
// Otherwise, stick with current.
bool likelyOculus = (height_ == 800);
bool foundMatch = false;
int alternate1080p = -1;
for (int i = 0; i < ndisplays_; ++i) {
if ((width_ == rect_[i].w && height_ == rect_[i].h)) {
d = i; // exact match, done.
foundMatch = true;
break;
}
if (rect_[i].h == 1080) alternate1080p = i;
printf("screen %d: %dx%d\n", i, rect_[i].w, rect_[i].h);
}
int targetWidth = rect_[d].w;
int targetHeight = rect_[d].h;
if (!foundMatch && likelyOculus && alternate1080p != -1) {
// Could not find exact match.
// Oculus might be duplicating a 1080p desktop.
d = alternate1080p;
// Stick w/ oculus resolution, rather than native screen one.
targetWidth = width_;
targetHeight = height_;
}
if (!fullscreen_) {
printf(__FUNCTION__ ": to fullscreen %dx%d display %d\n",
targetWidth, targetHeight, d);
window_ = SDL_CreateWindow("boxplorer2",
rect_[d].x, rect_[d].y,
targetWidth, targetHeight,
SDL_WINDOW_OPENGL|SDL_WINDOW_FULLSCREEN);
width_ = targetWidth;
height_ = targetHeight;
} else {
printf(__FUNCTION__ ": from fullscreen %dx%d display %d\n",
last_width_, last_height_, d);
window_ = SDL_CreateWindow("boxplorer2",
last_x_, last_y_,
last_width_, last_height_,
SDL_WINDOW_OPENGL|SDL_WINDOW_RESIZABLE);
width_ = last_width_;
height_ = last_height_;
}
glcontext_ = SDL_GL_CreateContext(window_);
display_ = d;
fullscreen_ = !fullscreen_;
return enableShaderProcs(); // re-fetch ptrs in new context.
}
SDL_Window* window() { return window_; }
int width() const { return width_; }
int height() const { return height_; }
private:
int display_;
int width_, height_; // current dimensions, window or fullscreen.
int last_x_,last_y_; // last known position of window
int last_width_, last_height_; // last known dimension of window.
bool fullscreen_;
int ndisplays_;
SDL_Window* window_;
SDL_GLContext glcontext_;
SDL_DisplayMode mode_[kMAXDISPLAYS];
SDL_Rect rect_[kMAXDISPLAYS];
} window;
// Optional #defines for glsl compilation from .cfg file.
string defines;
// Pinhole camera modes.
enum StereoMode { ST_NONE=0,
ST_OVERUNDER,
ST_XEYED,
ST_INTERLACED,
ST_SIDEBYSIDE,
ST_QUADBUFFER,
ST_OCULUS,
ST_ANAGLYPH,
ST_SPHERICAL,
ST_DOME,
ST_COMPUTE_DE_ONLY
} stereoMode = ST_NONE;
// For seamless cube rendering.
typedef int ViewQuadrant;
#define VQ_FRONT 0
#define VQ_BACK 1
#define VQ_UP 2
#define VQ_DOWN 3
#define VQ_RIGHT 4
#define VQ_LEFT 5
#define VQ_DONE 6
#define VQ_LETTER "fbudrl"
#define NFBO 2
// ogl framebuffer object(s).
// At least two are needed for the life and accumulation shaders.
GLuint mainFbo[NFBO];
// texture that frame got rendered to
GLuint mainTex[NFBO];
// depth buffer attached to fbo
GLuint mainDepth[NFBO];
// Fbo and texture for fxaa output.
GLuint fxaaFbo = -1;
GLuint fxaaTex = -1;
// Fbo and texture for tmp rendering pass.
GLuint scratchFbo = -1;
GLuint scratchTex = -1;
// framebuffer(s) for post-process blur.
// We have 2: one holding square and one a diamond.
// TODO: per eye for xfire?
#define NBLUR 2
GLuint blurFbo[NBLUR];
GLuint blurTex[NBLUR];
Shader fractal;
Shader effects;
Shader dof;
Shader de_shader;
GLuint de_fbo;
GLuint de_texture;
Shader fxaa;
Uniforms uniforms;
string BaseDir; // Where our executable and include dirs live.
string WorkingDir; // Where current fractal code & data lives.
string BaseFile; // Initial argument filename.
string lifeform; // Conway's Game of Life creature, if any.
// texture holding background image
GLuint background_texture;
// Try release everything that might have been allocated within
// current glContext. Leaks detected with AMD CodeXL.
void clearGlContext() {
// release shaders.
fractal.clear();
effects.clear();
dof.clear();
de_shader.clear();
fxaa.clear();
// delete fbos and textures.
glDeleteTextures(1, &de_texture);
glDeleteFramebuffers(1, &de_fbo);
glDeleteTextures(1, &background_texture); // free existing
glDeleteFramebuffers(ARRAYSIZE(mainFbo), mainFbo);
glDeleteTextures(ARRAYSIZE(mainDepth), mainDepth);
glDeleteTextures(ARRAYSIZE(mainTex), mainTex);
glDeleteFramebuffers(ARRAYSIZE(blurFbo), blurFbo);
glDeleteTextures(ARRAYSIZE(blurTex), blurTex);
glDeleteFramebuffers(1, &scratchFbo);
glDeleteTextures(1, &scratchTex);
glDeleteFramebuffers(1, &fxaaFbo);
glDeleteTextures(1, &fxaaTex);
}
// DLP-Link or interlaced L/R eye polarity
int polarity = 1;
SDL_Joystick* joystick = NULL;
////////////////////////////////////////////////////////////////
// Helper functions
// Allocate a char[] and read a text file into it. Return 0 on error.
char* _readFile(char const* name) {
FILE* f;
size_t len;
char* s = 0;
// open file an get its length
if (!(f = fopen(name, "r"))) goto readFileError1;
fseek(f, 0, SEEK_END);
len = ftell(f);
// read the file in an allocated buffer
if (!(s = (char*)malloc(len+1))) goto readFileError2;
rewind(f);
len = fread(s, 1, len, f);
s[len] = '\0';
readFileError2: fclose(f);
readFileError1: return s;
}
bool readFile(const string& name, string* content) {
string filename(WorkingDir + name);
char* s = _readFile(filename.c_str());
if (!s) {
filename = BaseDir + "include/" + name;
s = _readFile(filename.c_str());
if (!s) return false;
}
content->assign(s);
free(s);
printf(__FUNCTION__ " : read '%s'\n", filename.c_str());
return true;
}
////////////////////////////////////////////////////////////////
// FPS tracking.
int framesToAverage;
Uint32* frameDurations;
int frameDurationsIndex = 0;
Uint32 lastFrameTime;
double now() {
return (double)SDL_GetTicks() / 1000.0;
}
// Initialize the FPS structure.
void initFPS(int framesToAverage_) {
assert(framesToAverage_ > 1);
framesToAverage = framesToAverage_;
frameDurations = (Uint32*)malloc(sizeof(Uint32) * framesToAverage_);
frameDurations[0] = 0;
lastFrameTime = SDL_GetTicks();
}
// Update the FPS structure after drawing a frame.
void updateFPS(void) {
Uint32 time = SDL_GetTicks();
frameDurations[frameDurationsIndex++ % framesToAverage] =
time - lastFrameTime;
lastFrameTime = time;
}
// Return the duration of the last frame.
Uint32 getLastFrameDuration(void) {
return frameDurations[(frameDurationsIndex+framesToAverage-1) %
framesToAverage];
}
// Return the average FPS over the last X frames.
float getFPS(void) {
if (frameDurationsIndex < framesToAverage) return 0; // not enough data
int i; Uint32 sum;
for (i=sum=0; i<framesToAverage; i++) sum += frameDurations[i];
float fps = framesToAverage * 1000.f / sum;
static Uint32 lastfps = 0;
if (lastFrameTime - lastfps > 5000) {
// Once per 5 seconds.
#if defined(_WIN32)
SetOculusPrediction(0.9 / fps); // A bit lower than latency.
#endif
printf("fps %f\n", fps);
lastfps = lastFrameTime;
}
return fps;
}
////////////////////////////////////////////////////////////////
// Current logical state of the program.
#include "params.h"
class Camera : public KeyFrame {
public:
Camera& operator=(const KeyFrame& other) {
*((KeyFrame*)this) = other;
iBackbufferCount = 0; // reset progressive rendering count.
return *this;
}
// Set the OpenGL modelview matrix to the camera matrix, for shader.
void activate(ViewQuadrant vq = VQ_FRONT) {
orthogonalize();
glMatrixMode(GL_MODELVIEW);
// Tweak view for desired quadrant.
double m[16];
memcpy(m, v, sizeof(m));
switch (vq) {
case VQ_FRONT:
//m[0] = v[0]; m[1] = v[1]; m[2] = v[2]; // right
//m[4] = v[4]; m[5] = v[5]; m[6] = v[6]; // up
//m[8] = v[8]; m[9] = v[9]; m[10] = v[10]; // ahead
break;
case VQ_BACK:
// ahead = -ahead; right = -right
m[0] = -v[0]; m[1] = -v[1]; m[2] = -v[2];
m[8] = -v[8]; m[9] = -v[9]; m[10] = -v[10];
break;
case VQ_UP:
// ahead = up; up = -ahead;
m[4] = -v[8]; m[5] = -v[9]; m[6] = -v[10];
m[8] = v[4]; m[9] = v[5]; m[10] = v[6];
break;
case VQ_DOWN:
// ahead = -up; up = ahead
m[4] = v[8]; m[5] = v[9]; m[6] = v[10];
m[8] = -v[4]; m[9] = -v[5]; m[10] = -v[6];
break;
case VQ_RIGHT:
// ahead = right; right = -ahead
m[0] = -v[8]; m[1] = -v[9]; m[2] = -v[10];
m[8] = v[0]; m[9] = v[1]; m[10] = v[2];
break;
case VQ_LEFT:
// ahead = -right; right = ahead
m[0] = v[8]; m[1] = v[9]; m[2] = v[10];
m[8] = -v[0]; m[9] = -v[1]; m[10] = -v[2];
break;
}
glLoadMatrixd(m);
}
// Set the OpenGL modelview and projection for gl*() functions.
void activateGl() {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
double z_near = fabs(speed);
double z_far = speed * 65535.0;
double fH = tan( fov_y * PI / 360.0f ) * z_near;
double fW = tan( fov_x * PI / 360.0f ) * z_near;
glFrustum(-fW, fW, -fH, fH, z_near, z_far);
orthogonalize();
double matrix[16] = {
right()[0], up()[0], -ahead()[0], 0,
right()[1], up()[1], -ahead()[1], 0,
right()[2], up()[2], -ahead()[2], 0,
0, 0, 0, 1
};
glMatrixMode(GL_MODELVIEW);
glLoadMatrixd(matrix);
// Do not translate, keep eye at 0 to retain drawing precision.
//glTranslated(-pos()[0], -pos()[1], -pos()[2]);
}
// Load configuration.
bool loadConfig(const string& configFile, string* defines = NULL) {
bool result = false;
string filename(WorkingDir + configFile);
FILE* f;
if ((f = fopen(filename.c_str(), "r")) != 0) {
size_t i;
char s[32768]; // max line length
while (fscanf(f, " %s", s) == 1) { // read word
if (s[0] == 0 || s[0] == '#') continue;
int v;
// Parse #defines out of config.cfg to prepend to .glsl
if (defines) {
if (!strcmp(s, "d") || !strcmp(s, "c")) {
string a(s);
v = fscanf(f, " %s", s);
if (v == 1) {
string define = "#define " + a + " " + s + "\n";
printf(__FUNCTION__ " : %s", define.c_str());
defines->append(define);
if (!a.compare("d")) {
de_func_name.assign(s);
printf(__FUNCTION__" : de_func %s\n", de_func_name.c_str());
}
}
}
}
double val;
if (!strcmp(s, "position")) { v=fscanf(f, " %lf %lf %lf", &pos()[0], &pos()[1], &pos()[2]); continue; }
if (!strcmp(s, "direction")) { v=fscanf(f, " %lf %lf %lf", &ahead()[0], &ahead()[1], &ahead()[2]); continue; }
if (!strcmp(s, "upDirection")) { v=fscanf(f, " %lf %lf %lf", &up()[0], &up()[1], &up()[2]); continue; }
// Parse common parameters.
#define PROCESS(type, name, nameString, doSpline) \
if (!strcmp(s, nameString)) { v=fscanf(f, " %lf", &val); name = val; continue; }
PROCESS_COMMON_PARAMS
#undef PROCESS
for (i=0; i<ARRAYSIZE(par); i++) {
char p[256];
sprintf(p, "par%lu", (unsigned long)i);
if (!strcmp(s, p)) {
v=fscanf(f, " %f %f %f", &par[i][0], &par[i][1], &par[i][2]);
break;
}
}
}
fclose(f);
printf(__FUNCTION__ " : read '%s'\n", configFile.c_str());
result = true;
} else {
printf(__FUNCTION__ " : failed to open '%s'\n", configFile.c_str());
}
if (result) sanitizeParameters();
return result;
}
// Make sure parameters are OK.
void sanitizeParameters(void) {
// Resolution: if only one coordinate is set, keep 4:3 aspect ratio.
if (width < 1) {
if (height < 1) { height = 480; }
width = height*4/3;
}
if (height < 1) height = width*3/4;
// FOV: keep pixels square unless stated otherwise.
// Default FOV_y is 42 degrees.
if (fov_x <= 0) {
if (fov_y <= 0) {
// ~60x42 degrees is fov for normal position in front of a monitor.
fov_y = 42;
}
fov_x = atan(tan(fov_y*PI/180/2)*width/height)/PI*180*2;
}
if (fov_y <= 0) fov_y = atan(tan(fov_x*PI/180/2)*height/width)/PI*180*2;
// Fullscreen: 0=off, anything else=on.
if (fullscreen != 0 && fullscreen != 1) fullscreen = 1;
// The others are easy.
if (multisamples < 1) multisamples = 1;
//if (speed <= 0) speed = 0.005; // units/frame
if (keyb_rot_speed <= 0) keyb_rot_speed = 5; // degrees/frame
if (mouse_rot_speed <= 0) mouse_rot_speed = 1; // degrees/pixel
if (max_steps < 1) max_steps = 128;
if (min_dist <= 0) min_dist = 0.0001;
if (iters < 1) iters = 13;
if (color_iters < 0) color_iters = 9;
if (ao_eps <= 0) ao_eps = 0.0005;
if (ao_strength <= 0) ao_strength = 0.1;
if (glow_strength <= 0) glow_strength = 0.25;
if (dist_to_color <= 0) dist_to_color = 0.2;
if (exposure == 0) exposure = 1.0;
if (maxBright == 0) maxBright = 1.0;
if (gamma == 0) gamma = 1.0;
iBackbufferCount = 0; // No samples in backbuffer yet.
orthogonalize();
mat2quat(this->v, this->q);
// Don't do anything with user parameters - they must be
// sanitized (clamped, ...) in the shader.
}
// Save configuration.
void saveConfig(const string& configFile, string* defines = NULL) {
FILE* f;
string filename(WorkingDir + configFile);
if ((f = fopen(filename.c_str(), "w")) != 0) {
if (defines != NULL)
fprintf(f, "%s", defines->c_str());
// Write common parameters.
#define PROCESS(type, name, nameString, doSpline) \
fprintf(f, nameString " %g\n", (double)name);
PROCESS_COMMON_PARAMS
#undef PROCESS
fprintf(f, "position %12.12e %12.12e %12.12e\n", pos()[0], pos()[1], pos()[2]);
fprintf(f, "direction %g %g %g\n", ahead()[0], ahead()[1], ahead()[2]);
fprintf(f, "upDirection %g %g %g\n", up()[0], up()[1], up()[2]);
for (size_t i=0; i<ARRAYSIZE(par); i++) {
fprintf(f, "par%lu %g %g %g\n", (unsigned long)i, par[i][0], par[i][1], par[i][2]);
}
fclose(f);
printf(__FUNCTION__ " : wrote '%s'\n", filename.c_str());
}
}
// Send parameters to gpu.
void setUniforms(float x_scale, float x_offset,
float y_scale, float y_offset,
double spd, GLuint program = 0) {
#define glSetUniformf(name) \
glUniform1f(glGetUniformLocation(program, #name), name);
#define glSetUniformfv(name) \
glUniform3fv(glGetUniformLocation(program, #name), ARRAYSIZE(name), (float*)name);
#define glSetUniformi(name) \
glUniform1i(glGetUniformLocation(program, #name), name);
if (program == 0) program = fractal.program();
// These might be dupes w/ uniforms.send() below.
// Leave for now until all .cfg got updated.
glSetUniformi(max_steps); glSetUniformf(min_dist);
glSetUniformi(iters); glSetUniformi(color_iters);
glSetUniformf(ao_eps); glSetUniformf(ao_strength);
glSetUniformf(glow_strength); glSetUniformf(dist_to_color);
glSetUniformi(nrays); glSetUniformf(focus);
// Non-user uniforms.
glSetUniformf(fov_x); glSetUniformf(fov_y);
glSetUniformf(x_scale); glSetUniformf(x_offset);
glSetUniformf(y_scale); glSetUniformf(y_offset);
glSetUniformf(time);
glUniform1f(glGetUniformLocation(program, "speed"), spd);
glUniform1f(glGetUniformLocation(program, "ipd"), ipd);
glUniform1f(glGetUniformLocation(program, "xres"), width);
glUniform1f(glGetUniformLocation(program, "yres"), height);
// Also pass in some double precision values, if supported.
if (glUniform1d) {
glUniform1d(glGetUniformLocation(program, "dspeed"), spd);
// For some reason 3dv below stopped working reliably..
glUniform1d(glGetUniformLocation(program, "deyex"), pos()[0]);
glUniform1d(glGetUniformLocation(program, "deyey"), pos()[1]);
glUniform1d(glGetUniformLocation(program, "deyez"), pos()[2]);
}
if (glUniform3dv) {
glUniform3dv(glGetUniformLocation(program, "deye"), 3, pos());
}
// Old-style par[] list.
glSetUniformfv(par);
#undef glSetUniformf
#undef glSetUniformfv
#undef glUniform1i
// New-style discovered && active uniforms only.
uniforms.send(program);
}
void render(enum StereoMode stereo, ViewQuadrant vq = VQ_FRONT) {
activate(vq); // Load view matrix for shader.
switch(stereo) {
case ST_OVERUNDER: { // left / right
setUniforms(1.0, 0.0, 2.0, 1.0, +speed);
glRects(-1,-1,1,0); // draw bottom half of screen
setUniforms(1.0, 0.0, 2.0, -1.0, -speed);
glRects(-1,0,1,1); // draw top half of screen
} break;
case ST_QUADBUFFER: { // left - right
glDrawBuffer(GL_BACK_LEFT);
setUniforms(1.0, 0.0, 1.0, 0.0, -speed*polarity);
glRects(-1,-1,1,1);
glDrawBuffer(GL_BACK_RIGHT);
setUniforms(1.0, 0.0, 1.0, 0.0, +speed*polarity);
glRects(-1,-1,1,1);
} break;
case ST_XEYED: { // right | left
setUniforms(2.0, +1.0, 1.0, 0.0, +speed);
glRectf(-1,-1,0,1); // draw left half of screen
setUniforms(2.0, -1.0, 1.0, 0.0, -speed);
glRectf(0,-1,1,1); // draw right half of screen
} break;
case ST_SIDEBYSIDE: { // left | right
setUniforms(2.0, +1.0, 1.0, 0.0, -speed);
glRectf(-1,-1,0,1); // draw left half of screen
setUniforms(2.0, -1.0, 1.0, 0.0, +speed);
glRectf(0,-1,1,1); // draw right half of screen
} break;
case ST_NONE:
case ST_SPHERICAL:
case ST_DOME:
setUniforms(1.0, 0.0, 1.0, 0.0, speed);
glRects(-1,-1,0,1); // draw left half
glRects(0,-1,1,1); // draw right half
break;
case ST_INTERLACED:
case ST_ANAGLYPH:
setUniforms(1.0, 0.0, 1.0, 0.0, speed*polarity);
glRects(-1,-1,0,1); // draw left half
glRects(0,-1,1,1); // draw right half
break;
case ST_OCULUS:
setUniforms(2.0, +1.0, 1.0, 0.0, -speed);
glRectf(-1,-1,0,1); // draw left half of screen
setUniforms(2.0, -1.0, 1.0, 0.0, +speed);
glRectf(0,-1,1,1); // draw right half of screen
break;
case ST_COMPUTE_DE_ONLY:
setUniforms(1.0, 0.0, 1.0, 0.0, speed, de_shader.program());
float xrange = 4.0 / window.width(); // Aim for ~8x8 pixels.
float yrange = 4.0 / window.height();
glRectf(-1, 1, -1+xrange, 1-yrange); // Only care about top corner.
break;
}
}
void mixHydraOrientation(float* quat) {
double q[4];
q[0] = quat[0];
q[1] = quat[1];
q[2] = quat[2];
q[3] = quat[3];
qnormalize(q);
qmul(q, this->q);
quat2mat(q, this->v);
}
// take this->q and q and produce this->v,q := this->q + q
void mixSensorOrientation(float q[4]) {
double q1[4];
q1[0] = q[0];
q1[1] = q[1];
q1[2] = q[2];
q1[3] = q[3];
q1[2] = -q1[2]; // We roll other way
qnormalize(q1);
// combine current view quat with sensor quat.
qmul(q1, this->q);
quat2mat(q1, this->v);
// this->q = q1;
this->q[0] = q1[0];
this->q[1] = q1[1];
this->q[2] = q1[2];
this->q[3] = q1[3];
}
// take this->v and q and produce this->v,q := this->v - q
void unmixSensorOrientation(float q[4]) {
double q1[4];
q1[0] = q[0];
q1[1] = q[1];
q1[2] = q[2];
q1[3] = q[3];
q1[2] = -q1[2]; // We roll other way
qnormalize(q1);
// apply inverse current view.
qinvert(q1, q1);
mat2quat(this->v, this->q);
qmul(q1, this->q);
quat2mat(q1, this->v);
// this->q = q1;
this->q[0] = q1[0];
this->q[1] = q1[1];
this->q[2] = q1[2];
this->q[3] = q1[3];
}
} camera, // Active camera view.
config; // Global configuration set.
vector<KeyFrame> keyframes; // Keyframes
void suggestDeltaTime(KeyFrame& camera, const vector<KeyFrame>& keyframes) {
if (keyframes.empty()) {
camera.delta_time = 0;
} else {
double dist = camera.distanceTo(keyframes[keyframes.size() - 1]);
double steps = dist / camera.speed;
camera.delta_time = steps / config.fps;
}
}
#define NSUBFRAMES 100 // # splined subframes between keyframes.
// TODO: make relative to delta_time, thus more like max fps.
void CatmullRom(const vector<KeyFrame>& keyframes,
vector<KeyFrame>* output,
bool loop = false,
int nsubframes = NSUBFRAMES) {
output->clear();
if (keyframes.size() < 2) return; // Need at least two points.
vector<KeyFrame> controlpoints(keyframes);