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