dc87024aa39f4265dd4b319e5f0baa18940ebd40
[laserbrain_demo] / src / app.cc
1 #include <stdio.h>
2 #include <assert.h>
3 #include <goatvr.h>
4 #include "app.h"
5 #include "opengl.h"
6 #include "sdr.h"
7 #include "texture.h"
8 #include "mesh.h"
9 #include "meshgen.h"
10 #include "scene.h"
11 #include "metascene.h"
12 #include "datamap.h"
13 #include "ui.h"
14 #include "opt.h"
15 #include "post.h"
16 #include "renderer.h"
17 #include "avatar.h"
18 #include "vrinput.h"
19 #include "exman.h"
20 #include "blob_exhibit.h"
21
22 #define NEAR_CLIP       5.0
23 #define FAR_CLIP        10000.0
24
25 static void draw_scene();
26 static void toggle_flight();
27 static void calc_framerate();
28
29 long time_msec;
30 int win_width, win_height;
31 float win_aspect;
32 bool fb_srgb;
33 bool opt_gear_wireframe;
34
35 TextureSet texman;
36 SceneSet sceneman;
37
38 unsigned int sdr_ltmap, sdr_ltmap_notex;
39
40 static Avatar avatar;
41
42 static float cam_dist = 0.0;
43 static float floor_y;   // last floor height
44 static float user_eye_height = 165;
45
46 static float walk_speed = 300.0f;
47 static float mouse_speed = 0.5f;
48 static bool show_walk_mesh, noclip = false;
49
50 static bool have_headtracking, have_handtracking, should_swap;
51
52 static int prev_mx, prev_my;
53 static bool bnstate[8];
54 static bool keystate[256];
55 static bool gpad_bnstate[64];
56 static Vec2 joy_move, joy_look;
57 static float joy_deadzone = 0.01;
58
59 static float framerate;
60
61 static Mat4 view_matrix, mouse_view_matrix, proj_matrix;
62 static MetaScene *mscn;
63 static unsigned int sdr_post_gamma;
64
65 static long prev_msec;
66
67 static ExhibitManager *exman;
68 static BlobExhibit *blobs;
69 static bool show_blobs;
70
71 static Renderer *rend;
72
73
74 bool app_init(int argc, char **argv)
75 {
76         if(!init_options(argc, argv, "demo.conf")) {
77                 return false;
78         }
79         app_resize(opt.width, opt.height);
80         app_fullscreen(opt.fullscreen);
81
82         if(opt.vr) {
83                 if(goatvr_init() == -1) {
84                         return false;
85                 }
86                 goatvr_set_origin_mode(GOATVR_HEAD);
87                 goatvr_set_units_scale(100.0f);
88
89                 goatvr_startvr();
90                 should_swap = goatvr_should_swap() != 0;
91                 user_eye_height = goatvr_get_eye_height();
92                 have_headtracking = goatvr_have_headtracking();
93                 have_handtracking = goatvr_have_handtracking();
94
95                 goatvr_recenter();
96         }
97
98         int srgb_capable;
99         glGetIntegerv(GL_FRAMEBUFFER_SRGB_CAPABLE_EXT, &srgb_capable);
100         printf("Framebuffer %s sRGB-capable\n", srgb_capable ? "is" : "is not");
101         fb_srgb = srgb_capable != 0;
102         glEnable(GL_FRAMEBUFFER_SRGB);
103
104         glEnable(GL_MULTISAMPLE);
105         glEnable(GL_DEPTH_TEST);
106         glEnable(GL_CULL_FACE);
107         glEnable(GL_LIGHTING);
108         glEnable(GL_NORMALIZE);
109
110         Mesh::use_custom_sdr_attr = false;
111
112         float ambient[] = {0.0, 0.0, 0.0, 0.0};
113         glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);
114
115         glClearColor(1, 1, 1, 1);
116
117         if(!init_vrhands()) {
118                 return false;
119         }
120
121         mscn = new MetaScene;
122         if(!mscn->load(opt.scenefile ? opt.scenefile : "data/museum.scene")) {
123                 return false;
124         }
125
126         avatar.pos = mscn->start_pos;
127         Vec3 dir = rotate(Vec3(0, 0, 1), mscn->start_rot);
128         dir.y = 0;
129         avatar.body_rot = rad_to_deg(acos(dot(dir, Vec3(0, 0, 1))));
130
131         exman = new ExhibitManager;
132         if(!exman->load(mscn, "data/exhibits")) {
133                 //return false;
134         }
135
136         blobs = new BlobExhibit;
137         blobs->node = new SceneNode;
138         blobs->init();
139         blobs->node->set_position(Vec3(-680, 160, -100));
140         blobs->node->set_scaling(Vec3(28, 28, 28));
141         blobs->node->update(0);
142
143         exman->add(blobs);
144
145         if(!(sdr_ltmap_notex = create_program_load("sdr/lightmap.v.glsl", "sdr/lightmap-notex.p.glsl"))) {
146                 return false;
147         }
148         set_uniform_int(sdr_ltmap_notex, "texmap", MTL_TEX_DIFFUSE);
149         set_uniform_int(sdr_ltmap_notex, "lightmap", MTL_TEX_LIGHTMAP);
150
151         if(!(sdr_ltmap = create_program_load("sdr/lightmap.v.glsl", "sdr/lightmap-tex.p.glsl"))) {
152                 return false;
153         }
154         set_uniform_int(sdr_ltmap, "texmap", MTL_TEX_DIFFUSE);
155         set_uniform_int(sdr_ltmap, "lightmap", MTL_TEX_LIGHTMAP);
156
157         if(!fb_srgb) {
158                 sdr_post_gamma = create_program_load("sdr/post_gamma.v.glsl", "sdr/post_gamma.p.glsl");
159         }
160
161         rend = new Renderer;
162         rend->set_scene(mscn);
163
164         glUseProgram(0);
165
166         if(opt.vr || opt.fullscreen) {
167                 app_grab_mouse(true);
168         }
169         return true;
170 }
171
172 void app_cleanup()
173 {
174         app_grab_mouse(false);
175         if(opt.vr) {
176                 goatvr_shutdown();
177         }
178         destroy_vrhands();
179
180         delete rend;
181
182         delete exman;
183
184         texman.clear();
185         sceneman.clear();
186 }
187
188 static bool constrain_walk_mesh(const Vec3 &v, Vec3 *newv)
189 {
190         Mesh *wm = mscn->walk_mesh;
191         if(!wm) {
192                 *newv = v;
193                 return true;
194         }
195
196         Ray downray = Ray(v, Vec3(0, -1, 0));
197         HitPoint hit;
198         if(mscn->walk_mesh->intersect(downray, &hit)) {
199                 *newv = hit.pos;
200                 newv->y += user_eye_height;
201                 return true;
202         }
203         return false;
204 }
205
206 static void update(float dt)
207 {
208         texman.update();
209         sceneman.update();
210
211         mscn->update(dt);
212         exman->update(dt);
213
214         float speed = walk_speed * dt;
215         Vec3 dir;
216
217         // joystick
218         float jdeadsq = joy_deadzone * joy_deadzone;
219         float jmove_lensq = length_sq(joy_move);
220         float jlook_lensq = length_sq(joy_look);
221
222         if(jmove_lensq > jdeadsq) {
223                 float len = sqrt(jmove_lensq);
224                 jmove_lensq -= jdeadsq;
225
226                 float mag = len * len;
227                 dir.x += mag * joy_move.x / len * 2.0 * speed;
228                 dir.z += mag * joy_move.y / len * 2.0 * speed;
229         }
230         if(jlook_lensq > jdeadsq) {
231                 float len = sqrt(jlook_lensq);
232                 jlook_lensq -= jdeadsq;
233
234                 float mag = len * len;
235                 avatar.body_rot += mag * joy_look.x / len * 200.0 * dt;
236                 avatar.head_alt += mag * joy_look.y / len * 100.0 * dt;
237                 if(avatar.head_alt < -90.0f) avatar.head_alt = -90.0f;
238                 if(avatar.head_alt > 90.0f) avatar.head_alt = 90.0f;
239         }
240
241         // keyboard move
242         if(keystate[(int)'w']) {
243                 dir.z -= speed;
244         }
245         if(keystate[(int)'s']) {
246                 dir.z += speed;
247         }
248         if(keystate[(int)'d']) {
249                 dir.x += speed;
250         }
251         if(keystate[(int)'a']) {
252                 dir.x -= speed;
253         }
254         if(keystate[(int)'q'] || gpad_bnstate[GPAD_UP]) {
255                 avatar.pos.y += speed;
256         }
257         if(keystate[(int)'z'] || gpad_bnstate[GPAD_DOWN]) {
258                 avatar.pos.y -= speed;
259         }
260
261         float theta = M_PI * avatar.body_rot / 180.0f;
262         Vec3 newpos;
263         newpos.x = avatar.pos.x + cos(theta) * dir.x - sin(theta) * dir.z;
264         newpos.y = avatar.pos.y;
265         newpos.z = avatar.pos.z + sin(theta) * dir.x + cos(theta) * dir.z;
266
267         if(noclip) {
268                 avatar.pos = newpos;
269         } else {
270                 if(!constrain_walk_mesh(newpos, &avatar.pos)) {
271                         float dtheta = M_PI / 32.0;
272                         float theta = dtheta;
273                         Vec2 dir2d = newpos.xz() - avatar.pos.xz();
274
275                         for(int i=0; i<16; i++) {
276                                 Vec2 dvec = rotate(dir2d, theta);
277                                 Vec3 pos = avatar.pos + Vec3(dvec.x, 0, dvec.y);
278                                 if(constrain_walk_mesh(pos, &avatar.pos)) {
279                                         break;
280                                 }
281                                 dvec = rotate(dir2d, -theta);
282                                 pos = avatar.pos + Vec3(dvec.x, 0, dvec.y);
283                                 if(constrain_walk_mesh(pos, &avatar.pos)) {
284                                         break;
285                                 }
286                                 theta += dtheta;
287                         }
288                 }
289                 floor_y = avatar.pos.y - user_eye_height;
290         }
291
292         // TODO move to avatar
293         // calculate mouselook view matrix
294         mouse_view_matrix = Mat4::identity;
295         mouse_view_matrix.pre_translate(0, 0, -cam_dist);
296         if(!have_headtracking) {
297                 mouse_view_matrix.pre_rotate_x(deg_to_rad(avatar.head_alt));
298         }
299         mouse_view_matrix.pre_rotate_y(deg_to_rad(avatar.body_rot));
300         mouse_view_matrix.pre_translate(-avatar.pos.x, -avatar.pos.y, -avatar.pos.z);
301
302         // update hand-tracking
303         if(have_handtracking) {
304                 update_vrhands(&avatar);
305         }
306 }
307
308 static void set_light(int idx, const Vec3 &pos, const Vec3 &color)
309 {
310         unsigned int lt = GL_LIGHT0 + idx;
311         float posv[] = { pos.x, pos.y, pos.z, 1 };
312         float colv[] = { color.x, color.y, color.z, 1 };
313
314         glEnable(lt);
315         glLightfv(lt, GL_POSITION, posv);
316         glLightfv(lt, GL_DIFFUSE, colv);
317         glLightfv(lt, GL_SPECULAR, colv);
318 }
319
320 void app_display()
321 {
322         float dt = (float)(time_msec - prev_msec) / 1000.0f;
323         prev_msec = time_msec;
324
325         if(opt.vr) {
326                 // VR mode
327                 goatvr_draw_start();
328                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
329
330                 update(dt);
331
332                 for(int i=0; i<2; i++) {
333                         // for each eye
334                         goatvr_draw_eye(i);
335
336                         proj_matrix = goatvr_projection_matrix(i, NEAR_CLIP, FAR_CLIP);
337                         glMatrixMode(GL_PROJECTION);
338                         glLoadMatrixf(proj_matrix[0]);
339
340                         view_matrix = mouse_view_matrix * Mat4(goatvr_view_matrix(i));
341                         glMatrixMode(GL_MODELVIEW);
342                         glLoadMatrixf(view_matrix[0]);
343
344                         draw_scene();
345                         if(have_handtracking) {
346                                 draw_vrhands();
347                         }
348                 }
349                 goatvr_draw_done();
350
351                 if(should_swap) {
352                         app_swap_buffers();
353                 }
354
355         } else {
356                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
357
358                 update(dt);
359
360                 proj_matrix.perspective(deg_to_rad(50.0), win_aspect, NEAR_CLIP, FAR_CLIP);
361                 glMatrixMode(GL_PROJECTION);
362                 glLoadMatrixf(proj_matrix[0]);
363
364                 view_matrix = mouse_view_matrix;
365                 glMatrixMode(GL_MODELVIEW);
366                 glLoadMatrixf(view_matrix[0]);
367
368                 draw_scene();
369                 draw_vrhands(); // XXX
370
371                 if(!fb_srgb && sdr_post_gamma) {
372                         slow_post(sdr_post_gamma);
373                         glUseProgram(0);
374                 }
375                 app_swap_buffers();
376         }
377         assert(glGetError() == GL_NO_ERROR);
378
379         calc_framerate();
380 }
381
382
383 static void draw_scene()
384 {
385         static const Vec3 lpos[] = { Vec3(-50, 75, 100), Vec3(100, 0, 30), Vec3(-10, -10, 60) };
386         set_light(0, lpos[0], Vec3(1.0, 0.8, 0.7) * 0.8);
387         set_light(1, lpos[1], Vec3(0.6, 0.7, 1.0) * 0.6);
388         set_light(2, lpos[2], Vec3(0.8, 1.0, 0.8) * 0.3);
389
390         rend->draw();
391
392         if(show_blobs) {
393                 blobs->draw();
394         }
395
396         /*
397         if(have_handtracking) {
398                 Mat4 head_xform = inverse(mouse_view_matrix);//goatvr_head_matrix();
399                 Mat4 head_dir_xform = head_xform.upper3x3();
400
401                 glUseProgram(0);
402                 glPushAttrib(GL_ENABLE_BIT);
403                 glDisable(GL_LIGHTING);
404                 glBegin(GL_LINES);
405                 for(int i=0; i<2; i++) {
406                         if(hand[i].valid) {
407                                 glColor3f(i, 1 - i, i);
408                         } else {
409                                 glColor3f(0.5, 0.5, 0.5);
410                         }
411                         Vec3 v = head_xform * hand[i].pos;
412                         Vec3 dir = head_dir_xform * rotate(Vec3(0, 0, -1), hand[i].rot) * 20.0f;
413                         Vec3 up = head_dir_xform * rotate(Vec3(0, 1, 0), hand[i].rot) * 10.0f;
414                         Vec3 right = head_dir_xform * rotate(Vec3(1, 0, 0), hand[i].rot) * 10.0f;
415
416                         glVertex3f(v.x, v.y, v.z);
417                         glVertex3f(v.x + dir.x, v.y + dir.y, v.z + dir.z);
418                         glVertex3f(v.x - right.x, v.y - right.y, v.z - right.z);
419                         glVertex3f(v.x + right.x, v.y + right.y, v.z + right.z);
420                         glVertex3f(v.x - up.x, v.y - up.y, v.z - up.z);
421                         glVertex3f(v.x + up.x, v.y + up.y, v.z + up.z);
422                 }
423                 glEnd();
424                 glPopAttrib();
425         }
426         */
427
428         if(show_walk_mesh && mscn->walk_mesh) {
429                 glPushAttrib(GL_ENABLE_BIT);
430                 glEnable(GL_BLEND);
431                 glBlendFunc(GL_ONE, GL_ONE);
432                 glDisable(GL_LIGHTING);
433                 glEnable(GL_POLYGON_OFFSET_FILL);
434
435                 glUseProgram(0);
436
437                 glPolygonOffset(-1, 1);
438                 glDepthMask(0);
439
440                 glColor3f(0.3, 0.08, 0.01);
441                 mscn->walk_mesh->draw();
442
443                 glDepthMask(1);
444
445                 glPopAttrib();
446         }
447
448         print_text(Vec2(9 * win_width / 10, 20), Vec3(1, 1, 0), "fps: %.1f", framerate);
449         draw_ui();
450 }
451
452
453 void app_reshape(int x, int y)
454 {
455         glViewport(0, 0, x, y);
456         goatvr_set_fb_size(x, y, 1.0f);
457 }
458
459 void app_keyboard(int key, bool pressed)
460 {
461         unsigned int mod = app_get_modifiers();
462
463         if(pressed) {
464                 switch(key) {
465                 case 27:
466                         app_quit();
467                         break;
468
469                 case '\n':
470                 case '\r':
471                         if(mod & MOD_ALT) {
472                                 app_toggle_fullscreen();
473                         }
474                         break;
475
476                 case '`':
477                         app_toggle_grab_mouse();
478                         show_message("mouse %s", app_is_mouse_grabbed() ? "grabbed" : "released");
479                         break;
480
481                 case 'w':
482                         if(mod & MOD_CTRL) {
483                                 show_walk_mesh = !show_walk_mesh;
484                                 show_message("walk mesh: %s", show_walk_mesh ? "on" : "off");
485                         }
486                         break;
487
488                 case 'c':
489                         if(mod & MOD_CTRL) {
490                                 noclip = !noclip;
491                                 show_message(noclip ? "no clip" : "clip");
492                         }
493                         break;
494
495                 case 'f':
496                         toggle_flight();
497                         break;
498
499                 case 'p':
500                         if(mod & MOD_CTRL) {
501                                 fb_srgb = !fb_srgb;
502                                 show_message("gamma correction for non-sRGB framebuffers: %s\n", fb_srgb ? "off" : "on");
503                         }
504                         break;
505
506                 case '=':
507                         walk_speed *= 1.25;
508                         show_message("walk speed: %g", walk_speed);
509                         break;
510
511                 case '-':
512                         walk_speed *= 0.75;
513                         show_message("walk speed: %g", walk_speed);
514                         break;
515
516                 case ']':
517                         mouse_speed *= 1.2;
518                         show_message("mouse speed: %g", mouse_speed);
519                         break;
520
521                 case '[':
522                         mouse_speed *= 0.8;
523                         show_message("mouse speed: %g", mouse_speed);
524                         break;
525
526                 case 'b':
527                         show_blobs = !show_blobs;
528                         show_message("blobs: %s\n", show_blobs ? "on" : "off");
529                         break;
530
531                 case ' ':
532                         goatvr_recenter();
533                         show_message("VR recenter\n");
534                         break;
535                 }
536         }
537
538         if(key < 256 && !(mod & (MOD_CTRL | MOD_ALT))) {
539                 keystate[key] = pressed;
540         }
541 }
542
543 void app_mouse_button(int bn, bool pressed, int x, int y)
544 {
545         prev_mx = x;
546         prev_my = y;
547         bnstate[bn] = pressed;
548 }
549
550 static inline void mouse_look(float dx, float dy)
551 {
552         float scrsz = (float)win_height;
553         avatar.body_rot += dx * 512.0 / scrsz;
554         avatar.head_alt += dy * 512.0 / scrsz;
555
556         if(avatar.head_alt < -90) avatar.head_alt = -90;
557         if(avatar.head_alt > 90) avatar.head_alt = 90;
558 }
559
560 static void mouse_zoom(float dx, float dy)
561 {
562         cam_dist += dy * 0.1;
563         if(cam_dist < 0.0) cam_dist = 0.0;
564 }
565
566 void app_mouse_motion(int x, int y)
567 {
568         int dx = x - prev_mx;
569         int dy = y - prev_my;
570         prev_mx = x;
571         prev_my = y;
572
573         if(!dx && !dy) return;
574
575         if(bnstate[0]) {
576                 mouse_look(dx, dy);
577         }
578         if(bnstate[2]) {
579                 mouse_zoom(dx, dy);
580         }
581 }
582
583 void app_mouse_delta(int dx, int dy)
584 {
585         if(bnstate[2]) {
586                 mouse_zoom(dx * mouse_speed, dy * mouse_speed);
587         } else {
588                 mouse_look(dx * mouse_speed, dy * mouse_speed);
589         }
590 }
591
592 void app_gamepad_axis(int axis, float val)
593 {
594         switch(axis) {
595         case 0:
596                 joy_move.x = val;
597                 break;
598         case 1:
599                 joy_move.y = val;
600                 break;
601
602         case 2:
603                 joy_look.x = val;
604                 break;
605         case 3:
606                 joy_look.y = val;
607                 break;
608         }
609 }
610
611 void app_gamepad_button(int bn, bool pressed)
612 {
613         gpad_bnstate[bn] = pressed;
614
615         if(pressed) {
616                 switch(bn) {
617                 case GPAD_LSTICK:
618                         toggle_flight();
619                         break;
620
621                 case GPAD_X:
622                         show_blobs = !show_blobs;
623                         show_message("blobs: %s\n", show_blobs ? "on" : "off");
624                         break;
625
626                 case GPAD_START:
627                         goatvr_recenter();
628                         show_message("VR recenter\n");
629                         break;
630
631                 default:
632                         break;
633                 }
634         }
635 }
636
637 static void toggle_flight()
638 {
639         static float prev_walk_speed = -1.0;
640         if(prev_walk_speed < 0.0) {
641                 noclip = true;
642                 prev_walk_speed = walk_speed;
643                 walk_speed = 1000.0;
644                 show_message("fly mode\n");
645         } else {
646                 noclip = false;
647                 walk_speed = prev_walk_speed;
648                 prev_walk_speed = -1.0;
649                 show_message("walk mode\n");
650         }
651 }
652
653 static void calc_framerate()
654 {
655         static int ncalc;
656         static int nframes;
657         static long prev_upd;
658
659         long elapsed = time_msec - prev_upd;
660         if(elapsed >= 1000) {
661                 framerate = (float)nframes / (float)(elapsed * 0.001);
662                 nframes = 1;
663                 prev_upd = time_msec;
664
665                 /*if(++ncalc >= 5) {
666                         printf("fps: %f\n", framerate);
667                         ncalc = 0;
668                 }*/
669         } else {
670                 ++nframes;
671         }
672 }