fixed mirror rendering for goatvr backends which don't use an fbo
[laserbrain_demo] / src / app.cc
1 #include <stdio.h>
2 #include <limits.h>
3 #include <assert.h>
4 #include <goatvr.h>
5 #include "app.h"
6 #include "opengl.h"
7 #include "sdr.h"
8 #include "texture.h"
9 #include "mesh.h"
10 #include "meshgen.h"
11 #include "scene.h"
12 #include "metascene.h"
13 #include "datamap.h"
14 #include "ui.h"
15 #include "opt.h"
16 #include "post.h"
17 #include "renderer.h"
18 #include "avatar.h"
19 #include "vrinput.h"
20 #include "exman.h"
21 #include "blob_exhibit.h"
22 #include "dbg_gui.h"
23 #include "geomdraw.h"
24 #include "ui_exhibit.h"
25
26 #define NEAR_CLIP       5.0
27 #define FAR_CLIP        10000.0
28
29 static void draw_scene();
30 static void toggle_flight();
31 static void calc_framerate();
32 static Ray calc_pick_ray(int x, int y);
33
34 long time_msec;
35 int win_width, win_height;
36 int vp_width, vp_height;
37 float win_aspect;
38 bool fb_srgb;
39 bool opt_gear_wireframe;
40
41 TextureSet texman;
42 SceneSet sceneman;
43
44 int fpexcept_enabled;
45
46 unsigned int dbg_key_pending;
47
48 static Avatar avatar;
49
50 static float cam_dist = 0.0;
51 static float floor_y;   // last floor height
52 static float user_eye_height = 165;
53
54 static float walk_speed = 300.0f;
55 static float mouse_speed = 0.5f;
56 static bool show_walk_mesh, noclip = false;
57
58 static bool have_headtracking, have_handtracking, should_swap;
59
60 static int prev_mx, prev_my;
61 static bool bnstate[8];
62 static bool keystate[256];
63 static bool gpad_bnstate[64];
64 static Vec2 joy_move, joy_look;
65 static float joy_deadzone = 0.01;
66
67 static float framerate;
68
69 static Mat4 view_matrix, mouse_view_matrix, proj_matrix;
70 static MetaScene *mscn;
71 static unsigned int sdr_post_gamma;
72
73 static long prev_msec;
74
75 static ExhibitManager *exman;
76 static bool show_blobs;
77
78 ExSelection exsel_active, exsel_hover;
79 ExSelection exsel_grab_left, exsel_grab_right;
80 #define exsel_grab_mouse exsel_grab_right
81 static ExhibitSlot exslot_left, exslot_right;
82 #define exslot_mouse exslot_right
83
84 static Renderer *rend;
85
86 static Ray last_pick_ray;
87
88 static bool post_scene_init_pending = true;
89
90
91 bool app_init(int argc, char **argv)
92 {
93         set_log_file("demo.log");
94
95         char *env = getenv("FPEXCEPT");
96         if(env && atoi(env)) {
97                 info_log("enabling floating point exceptions\n");
98                 fpexcept_enabled = 1;
99                 enable_fpexcept();
100         }
101
102         if(init_opengl() == -1) {
103                 return false;
104         }
105
106         if(!init_options(argc, argv, "demo.conf")) {
107                 return false;
108         }
109         app_resize(opt.width, opt.height);
110         app_fullscreen(opt.fullscreen);
111
112         if(opt.vr) {
113                 if(goatvr_init() == -1) {
114                         return false;
115                 }
116                 goatvr_set_origin_mode(GOATVR_HEAD);
117                 goatvr_set_units_scale(100.0f);
118
119                 goatvr_startvr();
120                 should_swap = goatvr_should_swap() != 0;
121                 user_eye_height = goatvr_get_eye_height();
122                 have_headtracking = goatvr_have_headtracking();
123                 have_handtracking = goatvr_have_handtracking();
124
125                 goatvr_recenter();
126         }
127
128         if(fb_srgb) {
129                 int srgb_capable;
130                 glGetIntegerv(GL_FRAMEBUFFER_SRGB_CAPABLE_EXT, &srgb_capable);
131                 printf("Framebuffer %s sRGB-capable\n", srgb_capable ? "is" : "is not");
132                 if(srgb_capable) {
133                         glEnable(GL_FRAMEBUFFER_SRGB);
134                 } else {
135                         fb_srgb = 0;
136                 }
137         }
138
139         glEnable(GL_MULTISAMPLE);
140         glEnable(GL_DEPTH_TEST);
141         glEnable(GL_CULL_FACE);
142         glEnable(GL_NORMALIZE);
143
144         if(!init_debug_gui()) {
145                 return false;
146         }
147
148         Mesh::use_custom_sdr_attr = false;
149
150         float ambient[] = {0.0, 0.0, 0.0, 0.0};
151         glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);
152
153         init_audio();
154
155         if(!init_vrhands()) {
156                 return false;
157         }
158
159         mscn = new MetaScene;
160         if(!mscn->load(opt.scenefile ? opt.scenefile : "data/museum.scene")) {
161                 return false;
162         }
163
164         avatar.pos = mscn->start_pos;
165         Vec3 dir = rotate(Vec3(0, 0, 1), mscn->start_rot);
166         dir.y = 0;
167         avatar.body_rot = rad_to_deg(acos(dot(dir, Vec3(0, 0, 1))));
168
169         exman = new ExhibitManager;
170         // exhibits are loaded in post_scene_init, because they need access to the scene graph
171
172         if(!exui_init()) {
173                 error_log("failed to initialize exhibit ui system\n");
174                 return false;
175         }
176         exui_setnode(&exslot_left.node);
177
178         if(!fb_srgb) {
179                 sdr_post_gamma = create_program_load("sdr/post_gamma.v.glsl", "sdr/post_gamma.p.glsl");
180         }
181
182         rend = new Renderer;
183         if(!rend->init()) {
184                 return false;
185         }
186         if(opt.reflect) {
187                 rend->ropt |= RENDER_MIRRORS;
188         } else {
189                 rend->ropt &= ~RENDER_MIRRORS;
190         }
191         rend->set_scene(mscn);
192
193         glUseProgram(0);
194
195         if(opt.vr || opt.fullscreen) {
196                 app_grab_mouse(true);
197         }
198
199         if(mscn->music && opt.music) {
200                 mscn->music->play(AUDIO_PLAYMODE_LOOP);
201         }
202         return true;
203 }
204
205 // post_scene_init is called after the scene has completed loading
206 static void post_scene_init()
207 {
208         mscn->update(0);        // update once to calculate node matrices
209
210         int num_mir = mscn->calc_mirror_planes();
211         info_log("found %d mirror planes\n", num_mir);
212
213         exman->load(mscn, "data/exhibits");
214 }
215
216 void app_cleanup()
217 {
218         if(mscn->music) {
219                 mscn->music->stop();
220         }
221         destroy_audio();
222
223         app_grab_mouse(false);
224         if(opt.vr) {
225                 goatvr_shutdown();
226         }
227         destroy_vrhands();
228
229         delete rend;
230
231         exui_shutdown();
232
233         /* this must be destroyed before the scene graph to detach exhibit nodes
234          * before the scene tries to delete them recursively
235          */
236         delete exman;
237
238         texman.clear();
239         sceneman.clear();
240
241         cleanup_debug_gui();
242 }
243
244 static bool constrain_walk_mesh(const Vec3 &v, Vec3 *newv)
245 {
246         Mesh *wm = mscn->walk_mesh;
247         if(!wm) {
248                 *newv = v;
249                 return true;
250         }
251
252         Ray downray = Ray(v, Vec3(0, -1, 0));
253         HitPoint hit;
254         if(mscn->walk_mesh->intersect(downray, &hit)) {
255                 *newv = hit.pos;
256                 newv->y += user_eye_height;
257                 return true;
258         }
259         return false;
260 }
261
262 static void update(float dt)
263 {
264         texman.update();
265         sceneman.update();
266
267         if(post_scene_init_pending && !sceneman.pending()) {
268                 post_scene_init_pending = false;
269                 post_scene_init();
270         }
271
272         mscn->update(dt);
273         exman->update(dt);
274         exui_update(dt);
275
276         float speed = walk_speed * dt;
277         Vec3 dir;
278
279         // joystick
280         float jdeadsq = joy_deadzone * joy_deadzone;
281         float jmove_lensq = length_sq(joy_move);
282         float jlook_lensq = length_sq(joy_look);
283
284         if(jmove_lensq > jdeadsq) {
285                 float len = sqrt(jmove_lensq);
286                 jmove_lensq -= jdeadsq;
287
288                 float mag = len * len;
289                 dir.x += mag * joy_move.x / len * 2.0 * speed;
290                 dir.z += mag * joy_move.y / len * 2.0 * speed;
291         }
292         if(jlook_lensq > jdeadsq) {
293                 float len = sqrt(jlook_lensq);
294                 jlook_lensq -= jdeadsq;
295
296                 float mag = len * len;
297                 avatar.body_rot += mag * joy_look.x / len * 200.0 * dt;
298                 avatar.head_alt += mag * joy_look.y / len * 100.0 * dt;
299                 if(avatar.head_alt < -90.0f) avatar.head_alt = -90.0f;
300                 if(avatar.head_alt > 90.0f) avatar.head_alt = 90.0f;
301         }
302
303         // keyboard move
304         if(keystate[(int)'w']) {
305                 dir.z -= speed;
306         }
307         if(keystate[(int)'s']) {
308                 dir.z += speed;
309         }
310         if(keystate[(int)'d']) {
311                 dir.x += speed;
312         }
313         if(keystate[(int)'a']) {
314                 dir.x -= speed;
315         }
316         if(keystate[(int)'q'] || gpad_bnstate[GPAD_UP]) {
317                 avatar.pos.y += speed;
318         }
319         if(keystate[(int)'z'] || gpad_bnstate[GPAD_DOWN]) {
320                 avatar.pos.y -= speed;
321         }
322
323         float theta = M_PI * avatar.body_rot / 180.0f;
324         Vec3 newpos;
325         newpos.x = avatar.pos.x + cos(theta) * dir.x - sin(theta) * dir.z;
326         newpos.y = avatar.pos.y;
327         newpos.z = avatar.pos.z + sin(theta) * dir.x + cos(theta) * dir.z;
328
329         if(noclip) {
330                 avatar.pos = newpos;
331         } else {
332                 if(!constrain_walk_mesh(newpos, &avatar.pos)) {
333                         float dtheta = M_PI / 32.0;
334                         float theta = dtheta;
335                         Vec2 dir2d = newpos.xz() - avatar.pos.xz();
336
337                         for(int i=0; i<16; i++) {
338                                 Vec2 dvec = rotate(dir2d, theta);
339                                 Vec3 pos = avatar.pos + Vec3(dvec.x, 0, dvec.y);
340                                 if(constrain_walk_mesh(pos, &avatar.pos)) {
341                                         break;
342                                 }
343                                 dvec = rotate(dir2d, -theta);
344                                 pos = avatar.pos + Vec3(dvec.x, 0, dvec.y);
345                                 if(constrain_walk_mesh(pos, &avatar.pos)) {
346                                         break;
347                                 }
348                                 theta += dtheta;
349                         }
350                 }
351                 floor_y = avatar.pos.y - user_eye_height;
352         }
353
354         // TODO move to the avatar system
355         // calculate mouselook view matrix
356         mouse_view_matrix = Mat4::identity;
357         mouse_view_matrix.pre_translate(0, 0, -cam_dist);
358         if(!have_headtracking) {
359                 mouse_view_matrix.pre_rotate_x(deg_to_rad(avatar.head_alt));
360         }
361         mouse_view_matrix.pre_rotate_y(deg_to_rad(avatar.body_rot));
362         mouse_view_matrix.pre_translate(-avatar.pos.x, -avatar.pos.y, -avatar.pos.z);
363
364
365         // update hand-tracking
366         if(have_handtracking) {
367                 update_vrhands(&avatar);
368
369                 if(vrhand[0].valid) {
370                         exslot_left.node.set_position(vrhand[0].pos);
371                         exslot_left.node.set_rotation(vrhand[0].rot);
372
373                         // right hand takes precedence for hover
374                         if(!exsel_grab_left && !exsel_hover) {
375                                 exsel_hover = exman->select(Sphere(vrhand[0].pos, 5));
376                         }
377                 }
378                 if(vrhand[1].valid) {
379                         exslot_right.node.set_position(vrhand[1].pos);
380                         exslot_right.node.set_rotation(vrhand[1].rot);
381
382                         if(!exsel_grab_right) {
383                                 exsel_hover = exman->select(Sphere(vrhand[1].pos, 5));
384                         }
385                 }
386
387         } else {
388                 // check if an exhibit is hovered-over by mouse (only if we don't have one grabbed)
389                 if(!exsel_grab_mouse) {
390                         Ray ray = calc_pick_ray(prev_mx, prev_my);
391                         exsel_hover = exman->select(ray);
392                 }
393
394                 // TODO do this properly
395                 // set the position of the left hand at a suitable position for the exhibit UI
396                 dir = rotate(Vec3(-0.46, -0.1, -1), Vec3(0, 1, 0), deg_to_rad(-avatar.body_rot));
397                 exslot_left.node.set_position(avatar.pos + dir * 30); // magic: distance in front
398         }
399
400         if(!exslot_right.empty()) exslot_right.node.update(dt);
401         // always update the left slot, because it's the anchor point of the exhibit ui
402         exslot_left.node.update(dt);
403 }
404
405 void app_display()
406 {
407         float dt = (float)(time_msec - prev_msec) / 1000.0f;
408         prev_msec = time_msec;
409
410         if(debug_gui) {
411                 ImGui::GetIOPtr()->DeltaTime = dt;
412                 ImGui::NewFrame();
413
414                 //ImGui::ShowTestWindow();
415         }
416
417         glClearColor(1, 1, 1, 1);
418
419         if(opt.vr) {
420                 // VR mode
421                 goatvr_draw_start();
422                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
423
424                 update(dt);
425
426                 for(int i=0; i<2; i++) {
427                         // for each eye
428                         goatvr_draw_eye(i);
429                         if(goatvr_get_fb_texture()) {
430                                 vp_width = goatvr_get_fb_eye_width(i);
431                                 vp_height = goatvr_get_fb_eye_height(i);
432                         } else {
433                                 vp_width = win_width / 2;
434                         }
435
436                         proj_matrix = goatvr_projection_matrix(i, NEAR_CLIP, FAR_CLIP);
437                         glMatrixMode(GL_PROJECTION);
438                         glLoadMatrixf(proj_matrix[0]);
439
440                         view_matrix = mouse_view_matrix * Mat4(goatvr_view_matrix(i));
441                         glMatrixMode(GL_MODELVIEW);
442                         glLoadMatrixf(view_matrix[0]);
443
444                         draw_scene();
445                         if(have_handtracking) {
446                                 draw_vrhands();
447                         }
448
449                         if(debug_gui) {
450                                 ImGui::Render();
451                         }
452                 }
453                 goatvr_draw_done();
454
455                 vp_width = win_width;
456                 vp_height = win_height;
457
458                 if(should_swap) {
459                         app_swap_buffers();
460                 }
461
462         } else {
463                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
464
465                 update(dt);
466
467                 proj_matrix.perspective(deg_to_rad(50.0), win_aspect, NEAR_CLIP, FAR_CLIP);
468                 glMatrixMode(GL_PROJECTION);
469                 glLoadMatrixf(proj_matrix[0]);
470
471                 view_matrix = mouse_view_matrix;
472                 glMatrixMode(GL_MODELVIEW);
473                 glLoadMatrixf(view_matrix[0]);
474
475                 draw_scene();
476
477                 if(!fb_srgb && sdr_post_gamma) {
478                         slow_post(sdr_post_gamma);
479                         glUseProgram(0);
480                 }
481
482                 if(debug_gui) {
483                         ImGui::Render();
484                 }
485                 app_swap_buffers();
486         }
487         assert(glGetError() == GL_NO_ERROR);
488
489         calc_framerate();
490 }
491
492
493 static void draw_scene()
494 {
495         rend->draw();
496         exman->draw();
497
498         if(have_handtracking) {
499                 Mat4 head_xform = inverse(mouse_view_matrix);//goatvr_head_matrix();
500                 Mat4 head_dir_xform = head_xform.upper3x3();
501
502                 glUseProgram(0);
503                 glPushAttrib(GL_ENABLE_BIT);
504                 glDisable(GL_LIGHTING);
505                 glBegin(GL_LINES);
506                 for(int i=0; i<2; i++) {
507                         if(vrhand[i].valid) {
508                                 glColor3f(i, 1 - i, i);
509                         } else {
510                                 glColor3f(0.5, 0.5, 0.5);
511                         }
512                         Vec3 v = head_xform * vrhand[i].pos;
513                         Vec3 dir = head_dir_xform * rotate(Vec3(0, 0, -1), vrhand[i].rot) * 20.0f;
514                         Vec3 up = head_dir_xform * rotate(Vec3(0, 1, 0), vrhand[i].rot) * 10.0f;
515                         Vec3 right = head_dir_xform * rotate(Vec3(1, 0, 0), vrhand[i].rot) * 10.0f;
516
517                         glVertex3f(v.x, v.y, v.z);
518                         glVertex3f(v.x + dir.x, v.y + dir.y, v.z + dir.z);
519                         glVertex3f(v.x - right.x, v.y - right.y, v.z - right.z);
520                         glVertex3f(v.x + right.x, v.y + right.y, v.z + right.z);
521                         glVertex3f(v.x - up.x, v.y - up.y, v.z - up.z);
522                         glVertex3f(v.x + up.x, v.y + up.y, v.z + up.z);
523                 }
524                 glEnd();
525                 glPopAttrib();
526         }
527
528         if(debug_gui && dbg_sel_node) {
529                 AABox bvol = dbg_sel_node->get_bounds();
530                 draw_geom_object(&bvol);
531         }
532
533         if(show_walk_mesh && mscn->walk_mesh) {
534                 glPushAttrib(GL_ENABLE_BIT);
535                 glEnable(GL_BLEND);
536                 glBlendFunc(GL_ONE, GL_ONE);
537                 glEnable(GL_POLYGON_OFFSET_FILL);
538
539                 glUseProgram(0);
540
541                 glPolygonOffset(-1, 1);
542                 glDepthMask(0);
543
544                 glColor3f(0.3, 0.08, 0.01);
545                 mscn->walk_mesh->draw();
546
547                 glDepthMask(1);
548
549                 glPopAttrib();
550         }
551
552         exui_draw();
553
554         print_text(Vec2(9 * win_width / 10, 20), Vec3(1, 1, 0), "fps: %.1f", framerate);
555         draw_ui();
556 }
557
558
559 void app_reshape(int x, int y)
560 {
561         glViewport(0, 0, x, y);
562         goatvr_set_fb_size(x, y, 1.0f);
563         debug_gui_reshape(x, y);
564
565         vp_width = x;
566         vp_height = y;
567 }
568
569 void app_keyboard(int key, bool pressed)
570 {
571         unsigned int mod = app_get_modifiers();
572
573         if(debug_gui && !(pressed && (key == '`' || key == 27))) {
574                 debug_gui_key(key, pressed, mod);
575                 return; // ignore all keystrokes when GUI is visible
576         }
577
578         if(pressed) {
579                 switch(key) {
580                 case 27:
581                         app_quit();
582                         break;
583
584                 case '\n':
585                 case '\r':
586                         if(mod & MOD_ALT) {
587                                 app_toggle_fullscreen();
588                         }
589                         break;
590
591                 case '`':
592                         debug_gui = !debug_gui;
593                         show_message("debug gui %s", debug_gui ? "enabled" : "disabled");
594                         break;
595
596                 case 'm':
597                         app_toggle_grab_mouse();
598                         show_message("mouse %s", app_is_mouse_grabbed() ? "grabbed" : "released");
599                         break;
600
601                 case 'w':
602                         if(mod & MOD_CTRL) {
603                                 show_walk_mesh = !show_walk_mesh;
604                                 show_message("walk mesh: %s", show_walk_mesh ? "on" : "off");
605                         }
606                         break;
607
608                 case 'c':
609                         if(mod & MOD_CTRL) {
610                                 noclip = !noclip;
611                                 show_message(noclip ? "no clip" : "clip");
612                         }
613                         break;
614
615                 case 'f':
616                         toggle_flight();
617                         break;
618
619                 case 'p':
620                         if(mod & MOD_CTRL) {
621                                 fb_srgb = !fb_srgb;
622                                 show_message("gamma correction for non-sRGB framebuffers: %s\n", fb_srgb ? "off" : "on");
623                         }
624                         break;
625
626                 case '=':
627                         walk_speed *= 1.25;
628                         show_message("walk speed: %g", walk_speed);
629                         break;
630
631                 case '-':
632                         walk_speed *= 0.75;
633                         show_message("walk speed: %g", walk_speed);
634                         break;
635
636                 case ']':
637                         mouse_speed *= 1.2;
638                         show_message("mouse speed: %g", mouse_speed);
639                         break;
640
641                 case '[':
642                         mouse_speed *= 0.8;
643                         show_message("mouse speed: %g", mouse_speed);
644                         break;
645
646                 case 'b':
647                         show_blobs = !show_blobs;
648                         show_message("blobs: %s\n", show_blobs ? "on" : "off");
649                         break;
650
651                 case ' ':
652                         goatvr_recenter();
653                         show_message("VR recenter\n");
654                         break;
655
656                 case KEY_UP:
657                         exui_scroll(-1);
658                         break;
659
660                 case KEY_DOWN:
661                         exui_scroll(1);
662                         break;
663
664                 case KEY_LEFT:
665                         exui_change_tab(-1);
666                         break;
667
668                 case KEY_RIGHT:
669                         exui_change_tab(1);
670                         break;
671
672                 case KEY_F5:
673                 case KEY_F6:
674                 case KEY_F7:
675                 case KEY_F8:
676                         dbg_key_pending |= 1 << (key - KEY_F5);
677                         break;
678                 }
679         }
680
681         if(key < 256 && !(mod & (MOD_CTRL | MOD_ALT))) {
682                 keystate[key] = pressed;
683         }
684 }
685
686 void app_mouse_button(int bn, bool pressed, int x, int y)
687 {
688         static int press_x, press_y;
689
690         if(debug_gui) {
691                 debug_gui_mbutton(bn, pressed, x, y);
692                 return; // ignore mouse events while GUI is visible
693         }
694
695         prev_mx = x;
696         prev_my = y;
697         bnstate[bn] = pressed;
698
699         if(bn == 0) {
700                 ExSelection sel;
701                 Ray ray = calc_pick_ray(x, y);
702                 sel = exman->select(ray);
703
704                 if(pressed) {
705                         if(sel && (app_get_modifiers() & MOD_CTRL)) {
706                                 exsel_grab_mouse = sel;
707                                 Vec3 pos = sel.ex->node->get_position();
708                                 debug_log("grabbing... (%g %g %g)\n", pos.x, pos.y, pos.z);
709                                 exslot_mouse.node.set_position(pos);
710                                 exslot_mouse.node.set_rotation(sel.ex->node->get_rotation());
711                                 exslot_mouse.attach_exhibit(sel.ex, EXSLOT_ATTACH_TRANSIENT);
712                                 if(exsel_active) {
713                                         exsel_active = ExSelection::null;       // cancel active on grab
714                                 }
715                         }
716                         press_x = x;
717                         press_y = y;
718
719                 } else {
720                         if(exsel_grab_mouse) {
721                                 // cancel grab on mouse release
722                                 Exhibit *ex = exsel_grab_mouse.ex;
723                                 Vec3 pos = exslot_mouse.node.get_position();
724
725                                 debug_log("releasing at %g %g %g ...\n", pos.x, pos.y, pos.z);
726
727                                 exslot_mouse.detach_exhibit();
728
729                                 ExhibitSlot *slot = exman->nearest_empty_slot(pos, 100);
730                                 if(!slot) {
731                                         debug_log("no empty slot nearby\n");
732                                         if(ex->prev_slot && ex->prev_slot->empty()) {
733                                                 slot = ex->prev_slot;
734                                                 debug_log("using previous slot");
735                                         }
736                                 }
737
738                                 if(slot) {
739                                         slot->attach_exhibit(ex);
740                                 } else {
741                                         // nowhere to put it, so stash it for later
742                                         exslot_mouse.detach_exhibit();
743                                         exman->stash_exhibit(ex);
744                                         debug_log("no slots available, stashing\n");
745                                 }
746
747                                 exsel_grab_mouse = ExSelection::null;
748                         }
749
750                         if(abs(press_x - x) < 5 && abs(press_y - y) < 5) {
751                                 exsel_active = sel;     // select or deselect active exhibit
752                                 if(sel) {
753                                         debug_log("selecting...\n");
754                                 } else {
755                                         debug_log("deselecting...\n");
756                                 }
757                         }
758
759                         press_x = press_y = INT_MIN;
760                 }
761         }
762 }
763
764 static inline void mouse_look(float dx, float dy)
765 {
766         float scrsz = (float)win_height;
767         avatar.body_rot += dx * 512.0 / scrsz;
768         avatar.head_alt += dy * 512.0 / scrsz;
769
770         if(avatar.head_alt < -90) avatar.head_alt = -90;
771         if(avatar.head_alt > 90) avatar.head_alt = 90;
772 }
773
774 static void mouse_zoom(float dx, float dy)
775 {
776         cam_dist += dy * 0.1;
777         if(cam_dist < 0.0) cam_dist = 0.0;
778 }
779
780 void app_mouse_motion(int x, int y)
781 {
782         if(debug_gui) {
783                 debug_gui_mmotion(x, y);
784                 return; // ignore mouse events while GUI is visible
785         }
786
787         int dx = x - prev_mx;
788         int dy = y - prev_my;
789         prev_mx = x;
790         prev_my = y;
791
792         if(!dx && !dy) return;
793
794         if(exsel_grab_mouse) {
795                 Vec3 pos = exslot_mouse.node.get_node_position();
796                 Vec3 dir = transpose(view_matrix.upper3x3()) * Vec3(dx * 1.0, dy * -1.0, 0);
797
798                 exslot_mouse.node.set_position(pos + dir);
799         }
800
801         if(bnstate[2]) {
802                 mouse_look(dx, dy);
803         }
804 }
805
806 void app_mouse_delta(int dx, int dy)
807 {
808         if(bnstate[2]) {
809                 mouse_zoom(dx * mouse_speed, dy * mouse_speed);
810         } else {
811                 mouse_look(dx * mouse_speed, dy * mouse_speed);
812         }
813 }
814
815 void app_mouse_wheel(int dir)
816 {
817         if(debug_gui) {
818                 debug_gui_wheel(dir);
819         }
820 }
821
822 void app_gamepad_axis(int axis, float val)
823 {
824         switch(axis) {
825         case 0:
826                 joy_move.x = val;
827                 break;
828         case 1:
829                 joy_move.y = val;
830                 break;
831
832         case 2:
833                 joy_look.x = val;
834                 break;
835         case 3:
836                 joy_look.y = val;
837                 break;
838         }
839 }
840
841 void app_gamepad_button(int bn, bool pressed)
842 {
843         gpad_bnstate[bn] = pressed;
844
845         if(pressed) {
846                 switch(bn) {
847                 case GPAD_LSTICK:
848                         toggle_flight();
849                         break;
850
851                 case GPAD_X:
852                         show_blobs = !show_blobs;
853                         show_message("blobs: %s\n", show_blobs ? "on" : "off");
854                         break;
855
856                 case GPAD_START:
857                         goatvr_recenter();
858                         show_message("VR recenter\n");
859                         break;
860
861                 default:
862                         break;
863                 }
864         }
865 }
866
867 static void toggle_flight()
868 {
869         static float prev_walk_speed = -1.0;
870         if(prev_walk_speed < 0.0) {
871                 noclip = true;
872                 prev_walk_speed = walk_speed;
873                 walk_speed = 1000.0;
874                 show_message("fly mode\n");
875         } else {
876                 noclip = false;
877                 walk_speed = prev_walk_speed;
878                 prev_walk_speed = -1.0;
879                 show_message("walk mode\n");
880         }
881 }
882
883 static void calc_framerate()
884 {
885         //static int ncalc;
886         static int nframes;
887         static long prev_upd;
888
889         long elapsed = time_msec - prev_upd;
890         if(elapsed >= 1000) {
891                 framerate = (float)nframes / (float)(elapsed * 0.001);
892                 nframes = 1;
893                 prev_upd = time_msec;
894
895                 /*if(++ncalc >= 5) {
896                         printf("fps: %f\n", framerate);
897                         ncalc = 0;
898                 }*/
899         } else {
900                 ++nframes;
901         }
902 }
903
904 static Ray calc_pick_ray(int x, int y)
905 {
906         float nx = (float)x / (float)win_width;
907         float ny = (float)(win_height - y) / (float)win_height;
908
909         last_pick_ray = mouse_pick_ray(nx, ny, view_matrix, proj_matrix);
910         return last_pick_ray;
911 }