don't draw hands if we don't have hand-tracking
[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
370                 if(!fb_srgb && sdr_post_gamma) {
371                         slow_post(sdr_post_gamma);
372                         glUseProgram(0);
373                 }
374                 app_swap_buffers();
375         }
376         assert(glGetError() == GL_NO_ERROR);
377
378         calc_framerate();
379 }
380
381
382 static void draw_scene()
383 {
384         static const Vec3 lpos[] = { Vec3(-50, 75, 100), Vec3(100, 0, 30), Vec3(-10, -10, 60) };
385         set_light(0, lpos[0], Vec3(1.0, 0.8, 0.7) * 0.8);
386         set_light(1, lpos[1], Vec3(0.6, 0.7, 1.0) * 0.6);
387         set_light(2, lpos[2], Vec3(0.8, 1.0, 0.8) * 0.3);
388
389         rend->draw();
390
391         if(show_blobs) {
392                 blobs->draw();
393         }
394
395         /*
396         if(have_handtracking) {
397                 Mat4 head_xform = inverse(mouse_view_matrix);//goatvr_head_matrix();
398                 Mat4 head_dir_xform = head_xform.upper3x3();
399
400                 glUseProgram(0);
401                 glPushAttrib(GL_ENABLE_BIT);
402                 glDisable(GL_LIGHTING);
403                 glBegin(GL_LINES);
404                 for(int i=0; i<2; i++) {
405                         if(hand[i].valid) {
406                                 glColor3f(i, 1 - i, i);
407                         } else {
408                                 glColor3f(0.5, 0.5, 0.5);
409                         }
410                         Vec3 v = head_xform * hand[i].pos;
411                         Vec3 dir = head_dir_xform * rotate(Vec3(0, 0, -1), hand[i].rot) * 20.0f;
412                         Vec3 up = head_dir_xform * rotate(Vec3(0, 1, 0), hand[i].rot) * 10.0f;
413                         Vec3 right = head_dir_xform * rotate(Vec3(1, 0, 0), hand[i].rot) * 10.0f;
414
415                         glVertex3f(v.x, v.y, v.z);
416                         glVertex3f(v.x + dir.x, v.y + dir.y, v.z + dir.z);
417                         glVertex3f(v.x - right.x, v.y - right.y, v.z - right.z);
418                         glVertex3f(v.x + right.x, v.y + right.y, v.z + right.z);
419                         glVertex3f(v.x - up.x, v.y - up.y, v.z - up.z);
420                         glVertex3f(v.x + up.x, v.y + up.y, v.z + up.z);
421                 }
422                 glEnd();
423                 glPopAttrib();
424         }
425         */
426
427         if(show_walk_mesh && mscn->walk_mesh) {
428                 glPushAttrib(GL_ENABLE_BIT);
429                 glEnable(GL_BLEND);
430                 glBlendFunc(GL_ONE, GL_ONE);
431                 glDisable(GL_LIGHTING);
432                 glEnable(GL_POLYGON_OFFSET_FILL);
433
434                 glUseProgram(0);
435
436                 glPolygonOffset(-1, 1);
437                 glDepthMask(0);
438
439                 glColor3f(0.3, 0.08, 0.01);
440                 mscn->walk_mesh->draw();
441
442                 glDepthMask(1);
443
444                 glPopAttrib();
445         }
446
447         print_text(Vec2(9 * win_width / 10, 20), Vec3(1, 1, 0), "fps: %.1f", framerate);
448         draw_ui();
449 }
450
451
452 void app_reshape(int x, int y)
453 {
454         glViewport(0, 0, x, y);
455         goatvr_set_fb_size(x, y, 1.0f);
456 }
457
458 void app_keyboard(int key, bool pressed)
459 {
460         unsigned int mod = app_get_modifiers();
461
462         if(pressed) {
463                 switch(key) {
464                 case 27:
465                         app_quit();
466                         break;
467
468                 case '\n':
469                 case '\r':
470                         if(mod & MOD_ALT) {
471                                 app_toggle_fullscreen();
472                         }
473                         break;
474
475                 case '`':
476                         app_toggle_grab_mouse();
477                         show_message("mouse %s", app_is_mouse_grabbed() ? "grabbed" : "released");
478                         break;
479
480                 case 'w':
481                         if(mod & MOD_CTRL) {
482                                 show_walk_mesh = !show_walk_mesh;
483                                 show_message("walk mesh: %s", show_walk_mesh ? "on" : "off");
484                         }
485                         break;
486
487                 case 'c':
488                         if(mod & MOD_CTRL) {
489                                 noclip = !noclip;
490                                 show_message(noclip ? "no clip" : "clip");
491                         }
492                         break;
493
494                 case 'f':
495                         toggle_flight();
496                         break;
497
498                 case 'p':
499                         if(mod & MOD_CTRL) {
500                                 fb_srgb = !fb_srgb;
501                                 show_message("gamma correction for non-sRGB framebuffers: %s\n", fb_srgb ? "off" : "on");
502                         }
503                         break;
504
505                 case '=':
506                         walk_speed *= 1.25;
507                         show_message("walk speed: %g", walk_speed);
508                         break;
509
510                 case '-':
511                         walk_speed *= 0.75;
512                         show_message("walk speed: %g", walk_speed);
513                         break;
514
515                 case ']':
516                         mouse_speed *= 1.2;
517                         show_message("mouse speed: %g", mouse_speed);
518                         break;
519
520                 case '[':
521                         mouse_speed *= 0.8;
522                         show_message("mouse speed: %g", mouse_speed);
523                         break;
524
525                 case 'b':
526                         show_blobs = !show_blobs;
527                         show_message("blobs: %s\n", show_blobs ? "on" : "off");
528                         break;
529
530                 case ' ':
531                         goatvr_recenter();
532                         show_message("VR recenter\n");
533                         break;
534                 }
535         }
536
537         if(key < 256 && !(mod & (MOD_CTRL | MOD_ALT))) {
538                 keystate[key] = pressed;
539         }
540 }
541
542 void app_mouse_button(int bn, bool pressed, int x, int y)
543 {
544         prev_mx = x;
545         prev_my = y;
546         bnstate[bn] = pressed;
547 }
548
549 static inline void mouse_look(float dx, float dy)
550 {
551         float scrsz = (float)win_height;
552         avatar.body_rot += dx * 512.0 / scrsz;
553         avatar.head_alt += dy * 512.0 / scrsz;
554
555         if(avatar.head_alt < -90) avatar.head_alt = -90;
556         if(avatar.head_alt > 90) avatar.head_alt = 90;
557 }
558
559 static void mouse_zoom(float dx, float dy)
560 {
561         cam_dist += dy * 0.1;
562         if(cam_dist < 0.0) cam_dist = 0.0;
563 }
564
565 void app_mouse_motion(int x, int y)
566 {
567         int dx = x - prev_mx;
568         int dy = y - prev_my;
569         prev_mx = x;
570         prev_my = y;
571
572         if(!dx && !dy) return;
573
574         if(bnstate[0]) {
575                 mouse_look(dx, dy);
576         }
577         if(bnstate[2]) {
578                 mouse_zoom(dx, dy);
579         }
580 }
581
582 void app_mouse_delta(int dx, int dy)
583 {
584         if(bnstate[2]) {
585                 mouse_zoom(dx * mouse_speed, dy * mouse_speed);
586         } else {
587                 mouse_look(dx * mouse_speed, dy * mouse_speed);
588         }
589 }
590
591 void app_gamepad_axis(int axis, float val)
592 {
593         switch(axis) {
594         case 0:
595                 joy_move.x = val;
596                 break;
597         case 1:
598                 joy_move.y = val;
599                 break;
600
601         case 2:
602                 joy_look.x = val;
603                 break;
604         case 3:
605                 joy_look.y = val;
606                 break;
607         }
608 }
609
610 void app_gamepad_button(int bn, bool pressed)
611 {
612         gpad_bnstate[bn] = pressed;
613
614         if(pressed) {
615                 switch(bn) {
616                 case GPAD_LSTICK:
617                         toggle_flight();
618                         break;
619
620                 case GPAD_X:
621                         show_blobs = !show_blobs;
622                         show_message("blobs: %s\n", show_blobs ? "on" : "off");
623                         break;
624
625                 case GPAD_START:
626                         goatvr_recenter();
627                         show_message("VR recenter\n");
628                         break;
629
630                 default:
631                         break;
632                 }
633         }
634 }
635
636 static void toggle_flight()
637 {
638         static float prev_walk_speed = -1.0;
639         if(prev_walk_speed < 0.0) {
640                 noclip = true;
641                 prev_walk_speed = walk_speed;
642                 walk_speed = 1000.0;
643                 show_message("fly mode\n");
644         } else {
645                 noclip = false;
646                 walk_speed = prev_walk_speed;
647                 prev_walk_speed = -1.0;
648                 show_message("walk mode\n");
649         }
650 }
651
652 static void calc_framerate()
653 {
654         static int ncalc;
655         static int nframes;
656         static long prev_upd;
657
658         long elapsed = time_msec - prev_upd;
659         if(elapsed >= 1000) {
660                 framerate = (float)nframes / (float)(elapsed * 0.001);
661                 nframes = 1;
662                 prev_upd = time_msec;
663
664                 /*if(++ncalc >= 5) {
665                         printf("fps: %f\n", framerate);
666                         ncalc = 0;
667                 }*/
668         } else {
669                 ++nframes;
670         }
671 }