]> git.mxchange.org Git - flightgear.git/blob - src/GUI/gui.cxx
Activated gyro drift ... look out!
[flightgear.git] / src / GUI / gui.cxx
1 /**************************************************************************
2  * gui.cxx
3  *
4  * Written 1998 by Durk Talsma, started Juni, 1998.  For the flight gear
5  * project.
6  *
7  * Additional mouse supported added by David Megginson, 1999.
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License as
11  * published by the Free Software Foundation; either version 2 of the
12  * License, or (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22  *
23  * $Id$
24  **************************************************************************/
25
26
27 #ifdef HAVE_CONFIG_H
28 #  include <config.h>
29 #endif
30
31 #include <simgear/compiler.h>
32
33 #ifdef FG_MATH_EXCEPTION_CLASH
34 #  include <math.h>
35 #endif
36
37 #ifdef HAVE_WINDOWS_H
38 #  include <windows.h>
39 #endif
40
41 #include <GL/glut.h>
42 #include <simgear/xgl/xgl.h>
43
44 #if defined(FX) && defined(XMESA)
45 #  include <GL/xmesa.h>
46 #endif
47
48 #include STL_FSTREAM
49 #include STL_STRING
50
51 #include <stdlib.h>
52 #include <string.h>
53
54 #include <simgear/constants.h>
55 #include <simgear/debug/logstream.hxx>
56 #include <simgear/misc/fgpath.hxx>
57 #include <simgear/screen/screen-dump.hxx>
58
59 #include <Include/general.hxx>
60 #include <Aircraft/aircraft.hxx>
61 #include <Airports/simple.hxx>
62 #include <Autopilot/auto_gui.hxx>
63 #include <Autopilot/newauto.hxx>
64 #include <Cockpit/panel.hxx>
65 #include <Controls/controls.hxx>
66 #include <FDM/flight.hxx>
67 #include <Main/bfi.hxx>
68 #include <Main/fg_init.hxx>
69 #include <Main/globals.hxx>
70 #include <Main/options.hxx>
71 #include <Main/views.hxx>
72 #include <Main/save.hxx>
73 #ifdef FG_NETWORK_OLK
74 #include <NetworkOLK/network.h>
75 #endif
76
77 #if defined( WIN32 ) && !defined( __CYGWIN__ )
78 #  include <simgear/screen/win32-printer.h>
79 #  include <simgear/screen/GlBitmaps.h>
80 #endif
81
82 /*
83  * trackball.h
84  * A virtual trackball implementation
85  * Written by Gavin Bell for Silicon Graphics, November 1988.
86  */
87 /*
88  * Pass the x and y coordinates of the last and current positions of
89  * the mouse, scaled so they are from (-1.0 ... 1.0).
90  *
91  * The resulting rotation is returned as a quaternion rotation in the
92  * first paramater.
93  */
94 void
95 trackball(float q[4], float p1x, float p1y, float p2x, float p2y);
96
97 /*
98  * Given two quaternions, add them together to get a third quaternion.
99  * Adding quaternions to get a compound rotation is analagous to adding
100  * translations to get a compound translation.  When incrementally
101  * adding rotations, the first argument here should be the new
102
103   * rotation, the second and third the total rotation (which will be
104  * over-written with the resulting new total rotation).
105  */
106 void
107 add_quats(float *q1, float *q2, float *dest);
108
109 /*
110  * A useful function, builds a rotation matrix in Matrix based on
111  * given quaternion.
112  */
113 void
114 build_rotmatrix(float m[4][4], float q[4]);
115
116 /*
117  * This function computes a quaternion based on an axis (defined by
118  * the given vector) and an angle about which to rotate.  The angle is
119  * expressed in radians.  The result is put into the third argument.
120  */
121 void
122 axis_to_quat(float a[3], float phi, float q[4]);
123
124
125 #include "gui.h"
126
127 FG_USING_STD(string);
128
129 #ifndef FG_HAVE_NATIVE_SGI_COMPILERS
130 FG_USING_STD(cout);
131 #endif
132
133 #if defined(WIN32) || defined(__CYGWIN32__)
134 #define WIN32_CURSOR_TWEAKS
135 #elif (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 9)
136 #define X_CURSOR_TWEAKS
137 #endif
138
139 // hack, should come from an include someplace
140 extern void fgInitVisuals( void );
141 extern void fgReshape( int width, int height );
142 extern void fgRenderFrame( void );
143
144 puFont guiFnt = 0;
145 fntTexFont *guiFntHandle = 0;
146
147 static puMenuBar    *mainMenuBar = 0;
148 //static puButton     *hideMenuButton = 0;
149
150 static puDialogBox  *dialogBox = 0;
151 static puFrame      *dialogFrame = 0;
152 static puText       *dialogBoxMessage = 0;
153 static puOneShot    *dialogBoxOkButton = 0;
154
155
156 static puDialogBox  *YNdialogBox = 0;
157 static puFrame      *YNdialogFrame = 0;
158 static puText       *YNdialogBoxMessage = 0;
159 static puOneShot    *YNdialogBoxOkButton = 0;
160 static puOneShot    *YNdialogBoxNoButton = 0;
161
162 static char msg_OK[]     = "OK";
163 static char msg_NO[]     = "NO";
164 static char msg_YES[]    = "YES";
165 static char msg_CANCEL[] = "Cancel";
166 static char msg_RESET[]  = "Reset";
167
168 char *gui_msg_OK;     // "OK"
169 char *gui_msg_NO;     // "NO"
170 char *gui_msg_YES;    // "YES"
171 char *gui_msg_CANCEL; // "CANCEL"
172 char *gui_msg_RESET;  // "RESET"
173
174 static char global_dialog_string[256];
175
176 // from autopilot.cxx
177 // extern void NewAltitude( puObject *cb );
178 // extern void NewHeading( puObject *cb );
179 // extern void fgAPAdjust( puObject * );
180 // extern void NewTgtAirport( puObject *cb );
181 // bool fgAPTerrainFollowEnabled( void );
182 // bool fgAPAltitudeEnabled( void );
183 // bool fgAPHeadingEnabled( void );
184 // bool fgAPWayPointEnabled( void );
185 // bool fgAPAutoThrottleEnabled( void );
186
187 // from cockpit.cxx
188 extern void fgLatLonFormatToggle( puObject *);
189
190 /* --------------------------------------------------------------------
191 Mouse stuff
192 ---------------------------------------------------------------------*/
193
194 static int _mX = 0;
195 static int _mY = 0;
196 static int _savedX = 0;
197 static int _savedY = 0;
198 static int last_buttons = 0 ;
199 static int mouse_active = 0;
200 static int menu_on = 0;
201 static int mouse_joystick_control = 0;
202
203 //static time_t mouse_off_time;
204 //static int mouse_timed_out;
205
206 // to allow returning to previous view
207 // on second left click in MOUSE_VIEW mode
208 // This has file scope so that it can be reset
209 // if the little rodent is moved  NHV
210 static  int _mVtoggle;
211
212 // we break up the glutGetModifiers return mask
213 // once per loop and stash what we need in these
214 static int glut_active_shift;
215 static int glut_active_ctrl;
216 static int glut_active_alt;
217
218 static float lastquat[4];
219 static float curquat[4];
220 static float _quat0[4];
221 float quat_mat[4][4];
222
223 // uncomment this for view to exactly follow mouse in MOUSE_VIEW mode
224 // else smooth out the view panning to .01 radian per frame
225 // see view_offset smoothing mechanism in main.cxx
226 #define NO_SMOOTH_MOUSE_VIEW
227
228 // uncomment following to
229 #define RESET_VIEW_ON_LEAVING_MOUSE_VIEW
230
231 /* --------------------------------------------------------------------
232 Support for mouse as control yoke (david@megginson.com)
233
234 - right button toggles between pointer and yoke
235 - horizontal drag with no buttons moves ailerons
236 - vertical drag with no buttons moves elevators
237 - horizontal drag with left button moves brakes (left=on)
238 - vertical drag with left button moves throttle (up=more)
239 - horizontal drag with middle button moves rudder
240 - vertical drag with middle button moves trim
241
242 For the *_sensitivity variables, a lower number means more sensitive.
243
244 TODO: figure out how to keep pointer from leaving window in yoke mode.
245 TODO: add thresholds and null zones
246 TODO: sensitivity should be configurable at user option.
247 TODO: allow differential braking (this will be useful if FlightGear
248       ever supports tail-draggers like the DC-3)
249 ---------------------------------------------------------------------*/
250
251 typedef enum {
252     MOUSE_POINTER,
253     MOUSE_YOKE,
254     MOUSE_VIEW
255 } MouseMode;
256
257 MouseMode mouse_mode = MOUSE_POINTER;
258
259 static double aileron_sensitivity = 1.0/500.0;
260 static double elevator_sensitivity = 1.0/500.0;
261 static double brake_sensitivity = 1.0/250.0;
262 static double throttle_sensitivity = 1.0/250.0;
263 static double rudder_sensitivity = 1.0/500.0;
264 static double trim_sensitivity = 1.0/1000.0;
265
266 static inline void Quat0( void ) {
267     curquat[0] = _quat0[0];
268     curquat[1] = _quat0[1];
269     curquat[2] = _quat0[2];
270     curquat[3] = _quat0[3];
271 }
272
273 static inline int left_button( void ) {
274     return( last_buttons & (1 << GLUT_LEFT_BUTTON) );
275 }
276
277 static inline int middle_button( void ) {
278     return( last_buttons & (1 << GLUT_MIDDLE_BUTTON) );
279 }
280
281 static inline int right_button( void ) {
282     return( last_buttons & (1 << GLUT_RIGHT_BUTTON) );
283 }
284
285 static inline void TurnCursorOn( void )
286 {
287     mouse_active = ~0;
288 #if defined(WIN32_CURSOR_TWEAKS)
289     switch (mouse_mode) {
290         case MOUSE_POINTER:
291             glutSetCursor(GLUT_CURSOR_INHERIT);
292             break;
293         case MOUSE_YOKE:
294             glutSetCursor(GLUT_CURSOR_CROSSHAIR);
295             break;
296         case MOUSE_VIEW:
297             glutSetCursor(GLUT_CURSOR_LEFT_RIGHT);
298             break;
299     }
300 #endif
301 #if defined(X_CURSOR_TWEAKS)
302     glutWarpPointer( current_view.get_winWidth()/2, current_view.get_winHeight()/2);
303 #endif
304 }
305
306 static inline void TurnCursorOff( void )
307 {
308     mouse_active = 0;
309 #if defined(WIN32_CURSOR_TWEAKS)
310     glutSetCursor(GLUT_CURSOR_NONE);
311 #elif defined(X_CURSOR_TWEAKS)
312     glutWarpPointer( current_view.get_winWidth(), current_view.get_winHeight());
313 #endif
314 }
315
316 void maybeToggleMouse( void )
317 {
318 #if defined(WIN32_CURSOR_TWEAKS)
319     static int first_time = ~0;
320     static int mouse_changed = 0;
321
322     if ( first_time ) {
323         if(!mouse_active) {
324             mouse_changed = ~mouse_changed;
325             TurnCursorOn();
326         }
327     } else {
328         if( mouse_mode != MOUSE_POINTER )
329             return;
330         if( mouse_changed ) {
331             mouse_changed = ~mouse_changed;
332             if(mouse_active) {
333                 TurnCursorOff();
334             }
335         }
336     }
337     first_time = ~first_time;
338 #endif // #ifdef WIN32
339 }
340
341 // Call with FALSE to init and TRUE to restore
342 void BusyCursor( int restore )
343 {
344     static GLenum cursor = (GLenum) 0;
345     if( restore ) {
346         glutSetCursor(cursor);
347     } else {
348         cursor = (GLenum) glutGet( (GLenum) GLUT_WINDOW_CURSOR );
349 #if defined(WIN32_CURSOR_TWEAKS)
350         TurnCursorOn();
351 #endif
352         glutSetCursor( GLUT_CURSOR_WAIT );
353     }
354 }
355
356 int guiGetMouseButton(void)
357 {
358     return last_buttons;
359 }
360
361 void guiGetMouse(int *x, int *y)
362 {
363     *x = _mX;
364     *y = _mY;
365 };
366
367 void guiMotionFunc ( int x, int y )
368 {
369     int ww, wh, need_warp = 0;
370     float W, H;
371     double offset;
372
373     if (mouse_mode == MOUSE_POINTER) {
374         puMouse ( x, y ) ;
375         glutPostRedisplay () ;
376     } else {
377         if( x == _mX && y == _mY)
378             return;
379         
380         // reset left click MOUSE_VIEW toggle feature
381         _mVtoggle = 0;
382         
383         ww = current_view.get_winWidth();
384         wh = current_view.get_winHeight();
385         
386         switch (mouse_mode) {
387             case MOUSE_YOKE:
388                 if( !mouse_joystick_control ) {
389                     mouse_joystick_control = 1;
390                     current_options.set_control_mode( fgOPTIONS::FG_MOUSE );
391                 } else {
392                     if ( left_button() ) {
393                         offset = (_mX - x) * brake_sensitivity;
394                         controls.move_brake(FGControls::ALL_WHEELS, offset);
395                         offset = (_mY - y) * throttle_sensitivity;
396                         controls.move_throttle(FGControls::ALL_ENGINES, offset);
397                     } else if ( right_button() ) {
398                         if( ! current_autopilot->get_HeadingEnabled() ) {
399                             offset = (x - _mX) * rudder_sensitivity;
400                             controls.move_rudder(offset);
401                         }
402                         if( ! current_autopilot->get_AltitudeEnabled() ) {
403                             offset = (_mY - y) * trim_sensitivity;
404                             controls.move_elevator_trim(offset);
405                         }
406                     } else {
407                         if( ! current_autopilot->get_HeadingEnabled() ) {
408                             offset = (x - _mX) * aileron_sensitivity;
409                             controls.move_aileron(offset);
410                         }
411                         if( ! current_autopilot->get_AltitudeEnabled() ) {
412                             offset = (_mY - y) * elevator_sensitivity;
413                             controls.move_elevator(offset);
414                         }
415                     }
416                 }
417                 // Keep the mouse in the window.
418                 if (x < 5 || x > ww-5 || y < 5 || y > wh-5) {
419                     x = ww / 2;
420                     y = wh / 2;
421                     need_warp = 1;
422                 }
423                 break;
424                 
425             case MOUSE_VIEW:
426                 if( y <= 0 ) {
427 #define CONTRAINED_MOUSE_VIEW_Y
428 #ifdef CONTRAINED_MOUSE_VIEW_Y
429                     y = 1;
430 #else
431                     y = wh-2;
432 #endif // CONTRAINED_MOUSE_VIEW_Y
433                     need_warp = 1;
434                 } else if( y >= wh-1) {
435 #ifdef CONTRAINED_MOUSE_VIEW_Y
436                     y = wh-2;
437 #else
438                     y = 1;
439 #endif // CONTRAINED_MOUSE_VIEW_Y
440                     need_warp = 1;
441                 }
442                 // wrap MOUSE_VIEW mode cursor x position
443                 if ( x <= 0 ) {
444                     need_warp = 1;
445                     x = ww-2;
446                 } else if ( x >= ww-1 ) {
447                     need_warp = 1;
448                     x = 1;
449                 }
450                 // try to get FG_PI movement in each half of screen
451                 // do spherical pan
452                 W = ww;
453                 H = wh;
454                 if( middle_button() ) {
455                     trackball(lastquat,
456                               (2.0f * _mX - W) / W,
457                               0, //(H - 2.0f * y) / H,         // 3
458                               (2.0f * x - W) / W,
459                               0 //(H - 2.0f * _mY) / H       // 1
460                              );
461                     x = _mX;
462                     y = _mY;
463                     need_warp = 1;
464                 } else {
465                     trackball(lastquat,
466                               0, //(2.0f * _mX - W) / W,  // 0
467                               (H - 2.0f * y) / H,         // 3
468                               0, //(2.0f * x - W) / W,    // 2
469                               (H - 2.0f * _mY) / H        // 1 
470                              );
471                 }
472                 add_quats(lastquat, curquat, curquat);
473                 build_rotmatrix(quat_mat, curquat);
474                 
475                 // do horizontal pan
476                 // this could be done in above quat
477                 // but requires redoing view pipeline
478                 offset = current_view.get_goal_view_offset();
479                 offset += ((_mX - x) * FG_2PI / W );
480                 while (offset < 0.0) {
481                     offset += FG_2PI;
482                 }
483                 while (offset > FG_2PI) {
484                     offset -= FG_2PI;
485                 }
486                 current_view.set_goal_view_offset(offset);
487 #ifdef NO_SMOOTH_MOUSE_VIEW
488                 current_view.set_view_offset(offset);
489 #endif
490                 break;
491             
492             default:
493                 break;
494         }
495     }
496     if( need_warp)
497         glutWarpPointer(x, y);
498     
499     // Record the new mouse position.
500     _mX = x;
501     _mY = y;
502 }
503
504
505 void guiMouseFunc(int button, int updown, int x, int y)
506 {
507     int glutModifiers;
508
509     // private MOUSE_VIEW state variables
510     // to allow alternate left clicks in MOUSE_VIEW mode
511     // to toggle between current offsets and straight ahead
512     // uses _mVtoggle
513     static int _mVx, _mVy, _Vx, _Vy;
514     static float _quat[4];
515     static double _view_offset;
516     
517     // general purpose variables
518     double offset;
519             
520     glutModifiers = glutGetModifiers();
521     glut_active_shift = glutModifiers & GLUT_ACTIVE_SHIFT;
522     glut_active_ctrl  = glutModifiers & GLUT_ACTIVE_CTRL; 
523     glut_active_alt   = glutModifiers & GLUT_ACTIVE_ALT;
524     
525     // Was the left button pressed?
526     if (updown == GLUT_DOWN ) {
527         if( button == GLUT_LEFT_BUTTON)
528         {
529             switch (mouse_mode) {
530                 case MOUSE_POINTER:
531                     break;
532                 case MOUSE_YOKE:
533                     break;
534                 case MOUSE_VIEW:
535                     if(_mVtoggle) {
536                         // resume previous view offsets
537                         _mX = _mVx;
538                         _mY = _mVy;
539                         x = _Vx;
540                         y = _Vy;
541                         curquat[0] = _quat[0];
542                         curquat[1] = _quat[1];
543                         curquat[2] = _quat[2];
544                         curquat[3] = _quat[3];
545                         current_view.set_goal_view_offset(_view_offset);
546 #ifdef NO_SMOOTH_MOUSE_VIEW
547                         current_view.set_view_offset(_view_offset);
548 #endif
549                     } else {
550                         // center view
551                         _mVx = _mX;
552                         _mVy = _mY;
553                         _Vx = x;
554                         _Vy = y;
555                         _quat[0] = curquat[0];
556                         _quat[1] = curquat[1];
557                         _quat[2] = curquat[2];
558                         _quat[3] = curquat[3];
559                         x = current_view.get_winWidth()/2;
560                         y = current_view.get_winHeight()/2;
561                         Quat0();
562                         _view_offset = current_view.get_goal_view_offset();
563                         current_view.set_goal_view_offset(0.0);
564 #ifdef NO_SMOOTH_MOUSE_VIEW
565                         current_view.set_view_offset(0.0);
566 #endif
567                     }
568                     glutWarpPointer( x , y);
569                     build_rotmatrix(quat_mat, curquat);
570                     _mVtoggle = ~_mVtoggle;
571                     break;
572             }
573         }else if ( button == GLUT_RIGHT_BUTTON) {
574             switch (mouse_mode) {
575                 case MOUSE_POINTER:
576                     mouse_mode = MOUSE_YOKE;
577                     mouse_joystick_control = 0;
578                     _savedX = x;
579                     _savedY = y;
580                     // start with zero point in center of screen
581                     _mX = current_view.get_winWidth()/2;
582                     _mY = current_view.get_winHeight()/2;
583                     
584                     // try to have the MOUSE_YOKE position
585                     // reflect the current stick position
586                     offset = controls.get_aileron();
587                     x = _mX - (int)(offset * aileron_sensitivity);
588                     offset = controls.get_elevator();
589                     y = _mY - (int)(offset * elevator_sensitivity);
590                     
591                     glutSetCursor(GLUT_CURSOR_CROSSHAIR);
592                     FG_LOG( FG_INPUT, FG_INFO, "Mouse in yoke mode" );
593                     break;
594                     
595                 case MOUSE_YOKE:
596                     mouse_mode = MOUSE_VIEW;
597                     current_options.set_control_mode( fgOPTIONS::FG_JOYSTICK );
598                     x = current_view.get_winWidth()/2;
599                     y = current_view.get_winHeight()/2;
600                     _mVtoggle = 0;
601                     Quat0();
602                     build_rotmatrix(quat_mat, curquat);
603                     glutSetCursor(GLUT_CURSOR_LEFT_RIGHT);
604                     FG_LOG( FG_INPUT, FG_INFO, "Mouse in view mode" );
605                     break;
606                     
607                 case MOUSE_VIEW:
608                     mouse_mode = MOUSE_POINTER;
609                     x = _savedX;
610                     y = _savedY;
611 #ifdef RESET_VIEW_ON_LEAVING_MOUSE_VIEW
612                     Quat0();
613                     build_rotmatrix(quat_mat, curquat);
614                     current_view.set_goal_view_offset(0.0);
615 #ifdef NO_SMOOTH_MOUSE_VIEW
616                     current_view.set_view_offset(0.0);
617 #endif
618 #endif      // RESET_VIEW_ON_LEAVING_MOUSE_VIEW
619                     glutSetCursor(GLUT_CURSOR_INHERIT);
620                     
621                     if(!menu_on)
622                         TurnCursorOff();
623                     
624                     FG_LOG( FG_INPUT, FG_INFO, "Mouse in pointer mode" );
625                     break;
626             }     
627             glutWarpPointer( x, y );
628         } // END RIGHT BUTTON
629     } // END UPDOWN == GLUT_DOWN
630     
631     // Note which button is pressed.
632     if ( updown == GLUT_DOWN ) {
633         last_buttons |=  ( 1 << button ) ;
634     } else {
635         last_buttons &= ~( 1 << button ) ;
636     }
637     
638     // If we're in pointer mode, let PUI
639     // know what's going on.
640     if (mouse_mode == MOUSE_POINTER) {
641       if (!puMouse (button, updown, x,y)) {
642         current_panel->doMouseAction(button, updown, x, y);
643       }
644     }
645     
646     // Register the new position (if it
647     // hasn't been registered already).
648     _mX = x;
649     _mY = y;
650     
651     glutPostRedisplay ();
652 }
653
654 /* ================ General Purpose Functions ================ */
655
656 // Intercept the Escape Key
657 void ConfirmExitDialog(void)
658 {
659     FG_PUSH_PUI_DIALOG( YNdialogBox );
660 }
661
662 // General Purpose Message Box
663 void mkDialog (const char *txt)
664 {
665     strncpy(global_dialog_string, txt, 256);
666     dialogBoxMessage->setLabel(global_dialog_string);
667     FG_PUSH_PUI_DIALOG( dialogBox );
668 }
669
670 // Toggle the Menu and Mouse display state
671 void guiToggleMenu(void)
672 {
673     if( menu_on ) {
674         // printf("Hiding Menu\n");
675         mainMenuBar->hide  ();
676 #if defined(WIN32_CURSOR_TWEAKS)
677         if( mouse_mode == MOUSE_POINTER )
678             TurnCursorOff();
679 #endif // #ifdef WIN32_CURSOR_TWEAKS
680     } else {
681         // printf("Showing Menu\n");
682         mainMenuBar->reveal();
683 #ifdef WIN32
684         TurnCursorOn();
685 #endif // #ifdef WIN32
686     }
687     menu_on = ~menu_on;
688 }
689     
690 /* -----------------------------------------------------------------------
691 the Gui callback functions 
692 ____________________________________________________________________*/
693
694 static void saveFlight(puObject *cv)
695 {
696     BusyCursor(0);
697     ofstream output("fgfs.sav");
698     if (output.good() && fgSaveFlight(output)) {
699       output.close();
700       mkDialog("Saved flight to ./fgfs.sav");
701       FG_LOG(FG_INPUT, FG_INFO, "Saved flight to fgfs.sav");
702     } else {
703       mkDialog("Cannot save flight to ./fgfs.sav");
704       FG_LOG(FG_INPUT, FG_ALERT, "Cannot save flight to fgfs.sav");
705     }
706     BusyCursor(1);
707 }
708
709 static void loadFlight(puObject *cb)
710 {
711     BusyCursor(0);
712     ifstream input("fgfs.sav");
713     if (input.good() && fgLoadFlight(input)) {
714       input.close();
715       mkDialog("Loaded flight from fgfs.sav");
716       FG_LOG(FG_INPUT, FG_INFO, "Restored flight from ./fgfs.sav");
717     } else {
718       mkDialog("Failed to load flight from fgfs.sav");
719       FG_LOG(FG_INPUT, FG_ALERT, "Cannot load flight from ./fgfs.sav");
720     }
721     BusyCursor(1);
722 }
723
724 void reInit(puObject *cb)
725 {
726     BusyCursor(0);
727     Quat0();
728     build_rotmatrix(quat_mat, curquat);
729     fgReInitSubsystems();
730     BusyCursor(1);
731 }
732
733 static void toggleClouds(puObject *cb)
734 {
735     FGBFI::setClouds( !FGBFI::getClouds() );
736 }
737         
738 // This is the accessor function
739 void guiTogglePanel(puObject *cb)
740 {
741     current_options.toggle_panel();
742 }
743     
744 //void MenuHideMenuCb(puObject *cb)
745 void hideMenuCb (puObject *cb)
746 {
747     guiToggleMenu();
748 }
749
750 void goodBye(puObject *)
751 {
752     // FG_LOG( FG_INPUT, FG_ALERT,
753     //      "Program exiting normally at user request." );
754     cout << "Program exiting normally at user request." << endl;
755
756 #ifdef FG_NETWORK_OLK    
757     if ( current_options.get_network_olk() ) {
758         if ( net_is_registered == 0 ) fgd_send_com( "8", FGFS_host);
759     }
760 #endif
761
762     //  if(gps_bug)
763     //      fclose(gps_bug);
764
765     exit(-1);
766 }
767
768
769 void goAwayCb (puObject *me)
770 {
771     FG_POP_PUI_DIALOG( dialogBox );
772 }
773
774 void mkDialogInit (void)
775 {
776     //  printf("mkDialogInit\n");
777     int x = (current_options.get_xsize()/2 - 400/2);
778     int y = (current_options.get_ysize()/2 - 100/2);
779     dialogBox = new puDialogBox (x, y); // 150, 50
780     {
781         dialogFrame = new puFrame (0,0,400,100);
782         dialogBoxMessage  =  new puText         (10, 70);
783         dialogBoxMessage  -> setLabel           ("");
784         dialogBoxOkButton =  new puOneShot      (180, 10, 240, 50);
785         dialogBoxOkButton -> setLegend          (gui_msg_OK);
786         dialogBoxOkButton -> makeReturnDefault  (TRUE );
787         dialogBoxOkButton -> setCallback        (goAwayCb);
788     }
789     FG_FINALIZE_PUI_DIALOG( dialogBox );
790 }
791
792 void MayBeGoodBye(puObject *)
793 {
794     ConfirmExitDialog(); 
795 }
796
797 void goAwayYesNoCb(puObject *me)
798 {
799     FG_POP_PUI_DIALOG( YNdialogBox);
800 }
801
802 void ConfirmExitDialogInit(void)
803 {
804     char msg[] = "Really Quit";
805     char *s;
806
807     //  printf("ConfirmExitDialogInit\n");
808     int len = 200 - puGetStringWidth( puGetDefaultLabelFont(), msg )/2;
809
810     int x = (current_options.get_xsize()/2 - 400/2);
811     int y = (current_options.get_ysize()/2 - 100/2);
812         
813     YNdialogBox = new puDialogBox (x, y); // 150, 50
814     //  YNdialogBox = new puDialogBox (150, 50);
815     {
816         YNdialogFrame = new puFrame (0,0,400, 100);
817         
818         YNdialogBoxMessage  =  new puText         (len, 70);
819         YNdialogBoxMessage  -> setDefaultValue    (msg);
820         YNdialogBoxMessage  -> getDefaultValue    (&s);
821         YNdialogBoxMessage  -> setLabel           (s);
822         
823         YNdialogBoxOkButton =  new puOneShot      (100, 10, 160, 50);
824         YNdialogBoxOkButton -> setLegend          (gui_msg_OK);
825         YNdialogBoxOkButton -> makeReturnDefault  (TRUE );
826         YNdialogBoxOkButton -> setCallback        (goodBye);
827         
828         YNdialogBoxNoButton =  new puOneShot      (240, 10, 300, 50);
829         YNdialogBoxNoButton -> setLegend          (gui_msg_NO);
830         YNdialogBoxNoButton -> setCallback        (goAwayYesNoCb);
831     }
832     FG_FINALIZE_PUI_DIALOG( YNdialogBox );
833 }
834
835 void notCb (puObject *)
836 {
837     mkDialog ("This function isn't implemented yet");
838 }
839
840 void helpCb (puObject *)
841 {
842     string command;
843         
844 #if defined(FX) && !defined(WIN32)
845 #  if defined(XMESA_FX_FULLSCREEN) && defined(XMESA_FX_WINDOW)
846     if ( global_fullscreen ) {
847         global_fullscreen = false;
848         XMesaSetFXmode( XMESA_FX_WINDOW );
849     }
850 #  endif
851 #endif
852         
853 #if !defined(WIN32)
854     string url = "http://www.flightgear.org/Docs/InstallGuide/getstart.html";
855         
856     if ( system("xwininfo -name Netscape > /dev/null 2>&1") == 0 ) {
857         command = "netscape -remote \"openURL(" + url + ")\" &";
858     } else {
859         command = "netscape " + url + " &";
860     }
861 #else
862     command = "webrun.bat";
863 #endif
864         
865     system( command.c_str() );
866     //string text = "Help started in netscape window.";
867
868     //mkDialog (text.c_str());
869     mkDialog ("Help started in netscape window.");
870 }
871
872 #if defined( WIN32 ) && !defined( __CYGWIN__)
873
874 static void rotateView( double roll, double pitch, double yaw )
875 {
876         // rotate view
877 }
878
879 static GlBitmap *b1 = NULL;
880 extern FGInterface cur_view_fdm;
881 GLubyte *hiResScreenCapture( int multiplier )
882 {
883         float oldfov = current_options.get_fov();
884         float fov = oldfov / multiplier;
885         FGView *v = &current_view;
886         current_options.set_fov(fov);
887         v->force_update_fov_math();
888     fgInitVisuals();
889     int cur_width = current_view.get_winWidth( );
890     int cur_height = current_view.get_winHeight( );
891         if (b1) delete( b1 );
892         // New empty (mostly) bitmap
893         b1 = new GlBitmap( GL_RGB, 1, 1, (unsigned char *)"123" );
894         int x,y;
895         for ( y = 0; y < multiplier; y++ )
896         {
897                 for ( x = 0; x < multiplier; x++ )
898                 {
899                         fgReshape( cur_width, cur_height );
900                         // pan to tile
901                         rotateView( 0, (y*fov)-((multiplier-1)*fov/2), (x*fov)-((multiplier-1)*fov/2) );
902                         fgRenderFrame();
903                         // restore view
904                         GlBitmap b2;
905                         b1->copyBitmap( &b2, cur_width*x, cur_height*y );
906                 }
907         }
908         current_view.UpdateViewParams(cur_view_fdm);
909         current_options.set_fov(oldfov);
910         v->force_update_fov_math();
911         return b1->getBitmap();
912 }
913 #endif
914
915
916 #if defined( WIN32 ) && !defined( __CYGWIN__)
917 // win32 print screen function
918 void printScreen ( puObject *obj ) {
919     bool show_pu_cursor = false;
920     TurnCursorOff();
921     if ( !puCursorIsHidden() ) {
922         show_pu_cursor = true;
923         puHideCursor();
924     }
925     BusyCursor( 0 );
926     mainMenuBar->hide();
927
928     CGlPrinter p( CGlPrinter::PRINT_BITMAP );
929     int cur_width = current_view.get_winWidth( );
930     int cur_height = current_view.get_winHeight( );
931     p.Begin( "FlightGear", cur_width*3, cur_height*3 );
932         p.End( hiResScreenCapture(3) );
933
934     if( menu_on ) {
935         mainMenuBar->reveal();
936     }
937     BusyCursor(1);
938     if ( show_pu_cursor ) {
939         puShowCursor();
940     }
941     TurnCursorOn();
942 }
943 #endif // #ifdef WIN32
944
945
946 void dumpSnapShot ( puObject *obj ) {
947     fgDumpSnapShot();
948 }
949
950
951 // do a screen snap shot
952 void fgDumpSnapShot () {
953     bool show_pu_cursor = false;
954
955     int freeze = globals->get_freeze();
956     if(!freeze)
957         globals->set_freeze( true );
958
959     mainMenuBar->hide();
960     TurnCursorOff();
961     if ( !puCursorIsHidden() ) {
962         show_pu_cursor = true;
963         puHideCursor();
964     }
965
966     fgInitVisuals();
967     fgReshape( current_view.get_winWidth(), current_view.get_winHeight() );
968
969     // we need two render frames here to clear the menu and cursor
970     // ... not sure why but doing an extra fgFenderFrame() shoulnd't
971     // hurt anything
972     fgRenderFrame();
973     fgRenderFrame();
974
975     my_glDumpWindow( "fgfs-screen.ppm", 
976                      current_options.get_xsize(), 
977                      current_options.get_ysize() );
978     
979     mkDialog ("Snap shot saved to fgfs-screen.ppm");
980
981     if ( show_pu_cursor ) {
982         puShowCursor();
983     }
984
985     TurnCursorOn();
986     if( menu_on ) {
987         mainMenuBar->reveal();
988     }
989
990     if(!freeze)
991         globals->set_freeze( false );
992 }
993
994
995 /// The beginnings of teleportation :-)
996 //  Needs cleaning up but works
997 //  These statics should disapear when this is a class
998 static puDialogBox     *AptDialog = 0;
999 static puFrame         *AptDialogFrame = 0;
1000 static puText          *AptDialogMessage = 0;
1001 static puInput         *AptDialogInput = 0;
1002
1003 static char NewAirportId[16];
1004 static char NewAirportLabel[] = "Enter New Airport ID"; 
1005
1006 static puOneShot       *AptDialogOkButton = 0;
1007 static puOneShot       *AptDialogCancelButton = 0;
1008 static puOneShot       *AptDialogResetButton = 0;
1009
1010 void AptDialog_Cancel(puObject *)
1011 {
1012     FG_POP_PUI_DIALOG( AptDialog );
1013 }
1014
1015 void AptDialog_OK (puObject *)
1016 {
1017     FGPath path( current_options.get_fg_root() );
1018     path.append( "Airports" );
1019     path.append( "simple.mk4" );
1020     FGAirports airports( path.c_str() );
1021
1022     FGAirport a;
1023     
1024     int freeze = globals->get_freeze();
1025     if(!freeze)
1026         globals->set_freeze( true );
1027
1028     char *s;
1029     AptDialogInput->getValue(&s);
1030     string AptId(s);
1031
1032         cout << "AptDialog_OK " << AptId << " " << AptId.length() << endl;
1033     
1034     AptDialog_Cancel( NULL );
1035     
1036     if ( AptId.length() ) {
1037         // set initial position from airport id
1038         FG_LOG( FG_GENERAL, FG_INFO,
1039                 "Attempting to set starting position from airport code "
1040                 << AptId );
1041
1042         if ( airports.search( AptId, &a ) )
1043         {
1044             current_options.set_airport_id( AptId.c_str() );
1045             BusyCursor(0);
1046             fgReInitSubsystems();
1047             BusyCursor(1);
1048         } else {
1049             AptId  += " not in database.";
1050             mkDialog(AptId.c_str());
1051         }
1052     }
1053     if(!freeze)
1054         globals->set_freeze( false );
1055 }
1056
1057 void AptDialog_Reset(puObject *)
1058 {
1059     //  strncpy( NewAirportId, current_options.get_airport_id().c_str(), 16 );
1060     sprintf( NewAirportId, "%s", current_options.get_airport_id().c_str() );
1061     AptDialogInput->setValue ( NewAirportId );
1062     AptDialogInput->setCursor( 0 ) ;
1063 }
1064
1065 void NewAirport(puObject *cb)
1066 {
1067     //  strncpy( NewAirportId, current_options.get_airport_id().c_str(), 16 );
1068     sprintf( NewAirportId, "%s", current_options.get_airport_id().c_str() );
1069 //      cout << "NewAirport " << NewAirportId << endl;
1070     AptDialogInput->setValue( NewAirportId );
1071
1072     FG_PUSH_PUI_DIALOG( AptDialog );
1073 }
1074
1075 static void NewAirportInit(void)
1076 {
1077     sprintf( NewAirportId, "%s", current_options.get_airport_id().c_str() );
1078     int len = 150 - puGetStringWidth( puGetDefaultLabelFont(),
1079                                       NewAirportLabel ) / 2;
1080
1081     AptDialog = new puDialogBox (150, 50);
1082     {
1083         AptDialogFrame   = new puFrame           (0,0,350, 150);
1084         AptDialogMessage = new puText            (len, 110);
1085         AptDialogMessage ->    setLabel          (NewAirportLabel);
1086
1087         AptDialogInput   = new puInput           (50, 70, 300, 100);
1088         AptDialogInput   ->    setValue          (NewAirportId);
1089         AptDialogInput   ->    acceptInput();
1090
1091         AptDialogOkButton     =  new puOneShot   (50, 10, 110, 50);
1092         AptDialogOkButton     ->     setLegend   (gui_msg_OK);
1093         AptDialogOkButton     ->     setCallback (AptDialog_OK);
1094         AptDialogOkButton     ->     makeReturnDefault(TRUE);
1095
1096         AptDialogCancelButton =  new puOneShot   (140, 10, 210, 50);
1097         AptDialogCancelButton ->     setLegend   (gui_msg_CANCEL);
1098         AptDialogCancelButton ->     setCallback (AptDialog_Cancel);
1099
1100         AptDialogResetButton  =  new puOneShot   (240, 10, 300, 50);
1101         AptDialogResetButton  ->     setLegend   (gui_msg_RESET);
1102         AptDialogResetButton  ->     setCallback (AptDialog_Reset);
1103     }
1104         cout << "NewAirportInit " << NewAirportId << endl;
1105     FG_FINALIZE_PUI_DIALOG( AptDialog );
1106 }
1107
1108 #ifdef FG_NETWORK_OLK
1109
1110 /// The beginnings of networking :-)
1111 //  Needs cleaning up but works
1112 //  These statics should disapear when this is a class
1113 static puDialogBox     *NetIdDialog = 0;
1114 static puFrame         *NetIdDialogFrame = 0;
1115 static puText          *NetIdDialogMessage = 0;
1116 static puInput         *NetIdDialogInput = 0;
1117
1118 static char NewNetId[16];
1119 static char NewNetIdLabel[] = "Enter New Callsign"; 
1120 extern char *fgd_callsign;
1121
1122 static puOneShot       *NetIdDialogOkButton = 0;
1123 static puOneShot       *NetIdDialogCancelButton = 0;
1124
1125 void NetIdDialog_Cancel(puObject *)
1126 {
1127     FG_POP_PUI_DIALOG( NetIdDialog );
1128 }
1129
1130 void NetIdDialog_OK (puObject *)
1131 {
1132     string NetId;
1133     
1134     bool freeze = globals->get_freeze();
1135     if(!freeze)
1136         globals->set_freeze( true );
1137 /*  
1138    The following needs some cleanup because 
1139    "string options.NetId" and "char *net_callsign" 
1140 */
1141     NetIdDialogInput->getValue(&net_callsign);
1142     NetId = net_callsign;
1143     
1144     NetIdDialog_Cancel( NULL );
1145     current_options.set_net_id( NetId.c_str() );
1146     strcpy( fgd_callsign, net_callsign);
1147 //    strcpy( fgd_callsign, current_options.get_net_id().c_str());
1148 /* Entering a callsign indicates : user wants Net HUD Info */
1149     net_hud_display = 1;
1150
1151     if(!freeze)
1152         globals->set_freeze( false );
1153 }
1154
1155 void NewCallSign(puObject *cb)
1156 {
1157     sprintf( NewNetId, "%s", current_options.get_net_id().c_str() );
1158 //    sprintf( NewNetId, "%s", fgd_callsign );
1159     NetIdDialogInput->setValue( NewNetId );
1160
1161     FG_PUSH_PUI_DIALOG( NetIdDialog );
1162 }
1163
1164 static void NewNetIdInit(void)
1165 {
1166     sprintf( NewNetId, "%s", current_options.get_net_id().c_str() );
1167 //    sprintf( NewNetId, "%s", fgd_callsign );
1168     int len = 150 - puGetStringWidth( puGetDefaultLabelFont(),
1169                                       NewNetIdLabel ) / 2;
1170
1171     NetIdDialog = new puDialogBox (150, 50);
1172     {
1173         NetIdDialogFrame   = new puFrame           (0,0,350, 150);
1174         NetIdDialogMessage = new puText            (len, 110);
1175         NetIdDialogMessage ->    setLabel          (NewNetIdLabel);
1176
1177         NetIdDialogInput   = new puInput           (50, 70, 300, 100);
1178         NetIdDialogInput   ->    setValue          (NewNetId);
1179         NetIdDialogInput   ->    acceptInput();
1180
1181         NetIdDialogOkButton     =  new puOneShot   (50, 10, 110, 50);
1182         NetIdDialogOkButton     ->     setLegend   (gui_msg_OK);
1183         NetIdDialogOkButton     ->     setCallback (NetIdDialog_OK);
1184         NetIdDialogOkButton     ->     makeReturnDefault(TRUE);
1185
1186         NetIdDialogCancelButton =  new puOneShot   (240, 10, 300, 50);
1187         NetIdDialogCancelButton ->     setLegend   (gui_msg_CANCEL);
1188         NetIdDialogCancelButton ->     setCallback (NetIdDialog_Cancel);
1189
1190     }
1191     FG_FINALIZE_PUI_DIALOG( NetIdDialog );
1192 }
1193
1194 static void net_display_toggle( puObject *cb)
1195 {
1196         net_hud_display = (net_hud_display) ? 0 : 1;
1197         printf("Toggle net_hud_display : %d\n", net_hud_display);
1198 }
1199
1200 static void net_register( puObject *cb)
1201 {
1202         fgd_send_com( "1", FGFS_host );
1203         net_is_registered = 0;
1204         printf("Registering to deamon\n");
1205 }
1206
1207 static void net_unregister( puObject *cb)
1208 {
1209         fgd_send_com( "8", FGFS_host );
1210         net_is_registered = -1;
1211         printf("Unregistering from deamon\n");
1212 }
1213
1214
1215 /*************** Deamon communication **********/
1216
1217 //  These statics should disapear when this is a class
1218 static puDialogBox     *NetFGDDialog = 0;
1219 static puFrame         *NetFGDDialogFrame = 0;
1220 static puText          *NetFGDDialogMessage = 0;
1221 //static puInput         *NetFGDDialogInput = 0;
1222
1223 //static char NewNetId[16];
1224 static char NewNetFGDLabel[] = "Scan for deamon                        "; 
1225 static char NewFGDHost[64] = "olk.mcp.de"; 
1226 static int  NewFGDPortLo = 10000;
1227 static int  NewFGDPortHi = 10001;
1228  
1229 //extern char *fgd_callsign;
1230 extern u_short base_port, end_port;
1231 extern int fgd_ip, verbose, current_port;
1232 extern char *fgd_host;
1233
1234
1235 static puOneShot       *NetFGDDialogOkButton = 0;
1236 static puOneShot       *NetFGDDialogCancelButton = 0;
1237 static puOneShot       *NetFGDDialogScanButton = 0;
1238
1239 static puInput         *NetFGDHostDialogInput = 0;
1240 static puInput         *NetFGDPortLoDialogInput = 0;
1241 static puInput         *NetFGDPortHiDialogInput = 0;
1242
1243 void NetFGDDialog_Cancel(puObject *)
1244 {
1245     FG_POP_PUI_DIALOG( NetFGDDialog );
1246 }
1247
1248 void NetFGDDialog_OK (puObject *)
1249 {
1250     char *NetFGD;    
1251
1252     bool freeze = globals->get_freeze();
1253     if(!freeze)
1254         globals->set_freeze( true );
1255     NetFGDHostDialogInput->getValue( &NetFGD );
1256     strcpy( fgd_host, NetFGD);
1257     NetFGDPortLoDialogInput->getValue( (int *) &base_port );
1258     NetFGDPortHiDialogInput->getValue( (int *) &end_port );
1259     NetFGDDialog_Cancel( NULL );
1260     if(!freeze)
1261         globals->set_freeze( false );
1262 }
1263
1264 void NetFGDDialog_SCAN (puObject *)
1265 {
1266     char *NetFGD;
1267     int fgd_port;
1268     
1269     bool freeze = globals->get_freeze();
1270     if(!freeze)
1271         globals->set_freeze( true );
1272 //    printf("Vor getvalue %s\n");
1273     NetFGDHostDialogInput->getValue( &NetFGD );
1274 //    printf("Vor strcpy %s\n", (char *) NetFGD);
1275     strcpy( fgd_host, NetFGD);
1276     NetFGDPortLoDialogInput->getValue( (int *) &base_port );
1277     NetFGDPortHiDialogInput->getValue( (int *) &end_port );
1278     printf("FGD: %s  Port-Start: %d Port-End: %d\n", fgd_host, 
1279                  base_port, end_port);
1280     net_resolv_fgd(fgd_host);
1281     printf("Resolve : %d\n", net_r);
1282     if(!freeze)
1283         globals->set_freeze( false );
1284     if ( net_r == 0 ) {
1285       fgd_port = 10000;
1286       strcpy( fgd_name, "");
1287       for( current_port = base_port; ( current_port <= end_port); current_port++) {
1288           fgd_send_com("0" , FGFS_host);
1289           sprintf( NewNetFGDLabel , "Scanning for deamon Port: %d", current_port); 
1290           printf("FGD: searching %s\n", fgd_name);
1291           if ( strcmp( fgd_name, "") != 0 ) {
1292              sprintf( NewNetFGDLabel , "Found %s at Port: %d", 
1293                                               fgd_name, current_port);
1294              fgd_port = current_port;
1295              current_port = end_port+1;
1296           }
1297       }
1298       current_port = end_port = base_port = fgd_port;
1299     }
1300     NetFGDDialog_Cancel( NULL );
1301 }
1302
1303
1304 void net_fgd_scan(puObject *cb)
1305 {
1306     NewFGDPortLo = base_port;
1307     NewFGDPortHi = end_port;
1308     strcpy( NewFGDHost, fgd_host);
1309     NetFGDPortLoDialogInput->setValue( NewFGDPortLo );
1310     NetFGDPortHiDialogInput->setValue( NewFGDPortHi );
1311     NetFGDHostDialogInput->setValue( NewFGDHost );
1312
1313     FG_PUSH_PUI_DIALOG( NetFGDDialog );
1314 }
1315
1316
1317 static void NewNetFGDInit(void)
1318 {
1319 //    sprintf( NewNetId, "%s", current_options.get_net_id().c_str() );
1320 //    sprintf( NewNetId, "%s", fgd_callsign );
1321     int len = 170 - puGetStringWidth( puGetDefaultLabelFont(),
1322                                       NewNetFGDLabel ) / 2;
1323
1324     NetFGDDialog = new puDialogBox (310, 30);
1325     {
1326         NetFGDDialogFrame   = new puFrame           (0,0,320, 170);
1327         NetFGDDialogMessage = new puText            (len, 140);
1328         NetFGDDialogMessage ->    setLabel          (NewNetFGDLabel);
1329
1330         NetFGDPortLoDialogInput   = new puInput           (50, 70, 127, 100);
1331         NetFGDPortLoDialogInput   ->    setValue          (NewFGDPortLo);
1332         NetFGDPortLoDialogInput   ->    acceptInput();
1333
1334         NetFGDPortHiDialogInput   = new puInput           (199, 70, 275, 100);
1335         NetFGDPortHiDialogInput   ->    setValue          (NewFGDPortHi);
1336         NetFGDPortHiDialogInput   ->    acceptInput();
1337
1338         NetFGDHostDialogInput   = new puInput           (50, 100, 275, 130);
1339         NetFGDHostDialogInput   ->    setValue          (NewFGDHost);
1340         NetFGDHostDialogInput   ->    acceptInput();
1341
1342         NetFGDDialogScanButton     =  new puOneShot   (130, 10, 200, 50);
1343         NetFGDDialogScanButton     ->     setLegend   ("Scan");
1344         NetFGDDialogScanButton     ->     setCallback (NetFGDDialog_SCAN);
1345         NetFGDDialogScanButton     ->     makeReturnDefault(FALSE);
1346
1347         NetFGDDialogOkButton     =  new puOneShot   (50, 10, 120, 50);
1348         NetFGDDialogOkButton     ->     setLegend   (gui_msg_OK);
1349         NetFGDDialogOkButton     ->     setCallback (NetFGDDialog_OK);
1350         NetFGDDialogOkButton     ->     makeReturnDefault(TRUE);
1351
1352         NetFGDDialogCancelButton =  new puOneShot   (210, 10, 280, 50);
1353         NetFGDDialogCancelButton ->     setLegend   (gui_msg_CANCEL);
1354         NetFGDDialogCancelButton ->     setCallback (NetFGDDialog_Cancel);
1355
1356     }
1357     FG_FINALIZE_PUI_DIALOG( NetFGDDialog );
1358 }
1359
1360 /*
1361 static void net_display_toggle( puObject *cb)
1362 {
1363         net_hud_display = (net_hud_display) ? 0 : 1;
1364         printf("Toggle net_hud_display : %d\n", net_hud_display);
1365 }
1366
1367 */
1368
1369 #endif
1370
1371 /***************  End Networking  **************/
1372
1373
1374
1375 /* -----------------------------------------------------------------------
1376 The menu stuff 
1377 ---------------------------------------------------------------------*/
1378 char *fileSubmenu               [] = {
1379     "Exit", /* "Close", "---------", */
1380 #if defined( WIN32 ) && !defined( __CYGWIN__)
1381     "Print",
1382 #endif
1383     "Snap Shot",
1384     "---------", 
1385     "Reset", 
1386     "Load flight",
1387     "Save flight",
1388     NULL
1389 };
1390 puCallback fileSubmenuCb        [] = {
1391     MayBeGoodBye, /* hideMenuCb, NULL, */
1392 #if defined( WIN32 ) && !defined( __CYGWIN__)
1393     printScreen, 
1394 #endif
1395     /* NULL, notCb, */
1396     dumpSnapShot,
1397     NULL,
1398     reInit, 
1399     loadFlight,
1400     saveFlight,
1401     NULL
1402 };
1403
1404 /*
1405 char *editSubmenu               [] = {
1406     "Edit text", NULL
1407 };
1408 puCallback editSubmenuCb        [] = {
1409     notCb, NULL
1410 };
1411 */
1412
1413 extern void fgHUDalphaAdjust( puObject * );
1414 char *viewSubmenu               [] = {
1415     "HUD Alpha",
1416     /* "Cockpit View > ", "View >","------------", */
1417     "Toggle Panel...", NULL
1418 };
1419 puCallback viewSubmenuCb        [] = {
1420     fgHUDalphaAdjust,
1421     /* notCb, notCb, NULL, */
1422     guiTogglePanel, NULL
1423 };
1424
1425 char *aircraftSubmenu           [] = {
1426     "Autopilot", "Heading", "Altitude", "Navigation", "Airport", 
1427     /* "Communication", */ NULL
1428 };
1429 puCallback aircraftSubmenuCb    [] = {
1430     fgAPAdjust, NewHeading, NewAltitude, fgLatLonFormatToggle, NewTgtAirport, 
1431     /* notCb, */ NULL
1432 };
1433
1434 char *environmentSubmenu        [] = {
1435     "Toggle Clouds",
1436     "Goto Airport", /* "Terrain", "Weather", */ NULL
1437 };
1438 puCallback environmentSubmenuCb [] = {
1439     toggleClouds,
1440     NewAirport, /* notCb, notCb, */ NULL
1441 };
1442
1443 /*
1444 char *optionsSubmenu            [] = {
1445     "Preferences", "Realism & Reliablity...", NULL
1446 };
1447 puCallback optionsSubmenuCb     [] = {
1448     notCb, notCb, NULL
1449 };
1450 */
1451
1452 #ifdef FG_NETWORK_OLK
1453 char *networkSubmenu            [] = {
1454     "Unregister from FGD ", /* "Send MSG to All", "Send MSG", "Show Pilots", */
1455     "Register to FGD",
1456     "Scan for Deamons", "Enter Callsign", /* "Display Netinfos", */
1457     "Toggle Display", NULL
1458 };
1459 puCallback networkSubmenuCb     [] = {
1460     /* notCb, notCb, notCb, notCb, */ 
1461     net_unregister, 
1462     net_register, 
1463     net_fgd_scan, NewCallSign, 
1464     net_display_toggle, NULL
1465 };
1466 #endif
1467
1468 char *helpSubmenu               [] = {
1469     /* "About...", */ "Help", NULL
1470 };
1471 puCallback helpSubmenuCb        [] = {
1472     /* notCb, */ helpCb, NULL
1473 };
1474
1475
1476 /* -------------------------------------------------------------------------
1477 init the gui
1478 _____________________________________________________________________*/
1479
1480
1481 void guiInit()
1482 {
1483     char *mesa_win_state;
1484
1485     // Initialize PUI
1486     puInit();
1487     puSetDefaultStyle         ( PUSTYLE_SMALL_BEVELLED ); //PUSTYLE_DEFAULT
1488     puSetDefaultColourScheme  (0.8, 0.8, 0.8, 0.4);
1489
1490     // Initialize our GLOBAL GUI STRINGS
1491     gui_msg_OK     = msg_OK;     // "OK"
1492     gui_msg_NO     = msg_NO;     // "NO"
1493     gui_msg_YES    = msg_YES;    // "YES"
1494     gui_msg_CANCEL = msg_CANCEL; // "CANCEL"
1495     gui_msg_RESET  = msg_RESET;  // "RESET"
1496
1497     // Next check home directory
1498     FGPath fntpath;
1499     char* envp = ::getenv( "FG_FONTS" );
1500     if ( envp != NULL ) {
1501         fntpath.set( envp );
1502     } else {
1503         fntpath.set( current_options.get_fg_root() );
1504         fntpath.append( "Fonts" );
1505     }
1506
1507     // Install our fast fonts
1508     fntpath.append( "typewriter.txf" );
1509     guiFntHandle = new fntTexFont ;
1510     guiFntHandle -> load ( (char *)fntpath.c_str() ) ;
1511     puFont GuiFont ( guiFntHandle, 15 ) ;
1512     puSetDefaultFonts( GuiFont, GuiFont ) ;
1513     guiFnt = puGetDefaultLabelFont();
1514   
1515     if ( current_options.get_mouse_pointer() == 0 ) {
1516         // no preference specified for mouse pointer, attempt to autodetect...
1517         // Determine if we need to render the cursor, or if the windowing
1518         // system will do it.  First test if we are rendering with glide.
1519         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1520             // Test for the MESA_GLX_FX env variable
1521             if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
1522                 // test if we are fullscreen mesa/glide
1523                 if ( (mesa_win_state[0] == 'f') ||
1524                      (mesa_win_state[0] == 'F') ) {
1525                     puShowCursor ();
1526                 }
1527             }
1528         }
1529         mouse_active = ~mouse_active;
1530     } else if ( current_options.get_mouse_pointer() == 1 ) {
1531         // don't show pointer
1532     } else if ( current_options.get_mouse_pointer() == 2 ) {
1533         // force showing pointer
1534         puShowCursor();
1535         mouse_active = ~mouse_active;
1536     }
1537         
1538     // MOUSE_VIEW mode stuff
1539     trackball(_quat0, 0.0, 0.0, 0.0, 0.0);  
1540     Quat0();
1541     build_rotmatrix(quat_mat, curquat);
1542
1543     // Set up our Dialog Boxes
1544     ConfirmExitDialogInit();
1545     NewAirportInit();
1546 #ifdef FG_NETWORK_OLK
1547     NewNetIdInit();
1548     NewNetFGDInit();
1549 #endif
1550     mkDialogInit();
1551     
1552     // Make the menu bar
1553     mainMenuBar = new puMenuBar ();
1554     mainMenuBar -> add_submenu ("File", fileSubmenu, fileSubmenuCb);
1555     // mainMenuBar -> add_submenu ("Edit", editSubmenu, editSubmenuCb);
1556     mainMenuBar -> add_submenu ("View", viewSubmenu, viewSubmenuCb);
1557     mainMenuBar -> add_submenu ("Aircraft", aircraftSubmenu, aircraftSubmenuCb);
1558     mainMenuBar -> add_submenu ("Environment", environmentSubmenu, environmentSubmenuCb);
1559     // mainMenuBar -> add_submenu ("Options", optionsSubmenu, optionsSubmenuCb);
1560 #ifdef FG_NETWORK_OLK
1561     mainMenuBar -> add_submenu ("Network", networkSubmenu, networkSubmenuCb);
1562 #endif
1563     mainMenuBar -> add_submenu ("Help", helpSubmenu, helpSubmenuCb);
1564     mainMenuBar-> close ();
1565     // Set up menu bar toggle
1566     menu_on = ~0;
1567 }
1568
1569
1570
1571 /*
1572  * Trackball code:
1573  *
1574  * Implementation of a virtual trackball.
1575  * Implemented by Gavin Bell, lots of ideas from Thant Tessman and
1576  *   the August '88 issue of Siggraph's "Computer Graphics," pp. 121-129.
1577  *
1578  * Vector manip code:
1579  *
1580  * Original code from:
1581  * David M. Ciemiewicz, Mark Grossman, Henry Moreton, and Paul Haeberli
1582  *
1583  * Much mucking with by:
1584  * Gavin Bell
1585  */
1586 #if defined(_WIN32) && !defined( __CYGWIN32__ )
1587 #pragma warning (disable:4244)          /* disable bogus conversion warnings */
1588 #endif
1589 #include <math.h>
1590 #include <stdio.h>
1591 //#include "trackball.h"
1592
1593 /*
1594  * This size should really be based on the distance from the center of
1595  * rotation to the point on the object underneath the mouse.  That
1596  * point would then track the mouse as closely as possible.  This is a
1597  * simple example, though, so that is left as an Exercise for the
1598  * Programmer.
1599  */
1600 #define TRACKBALLSIZE  (0.8f)
1601 #define SQRT(x) sqrt(x)
1602
1603 /*
1604  * Local function prototypes (not defined in trackball.h)
1605  */
1606 static float tb_project_to_sphere(float, float, float);
1607 static void normalize_quat(float [4]);
1608
1609 static void
1610 vzero(float *v)
1611 {
1612     v[0] = 0.0;
1613     v[1] = 0.0;
1614     v[2] = 0.0;
1615 }
1616
1617 static void
1618 vset(float *v, float x, float y, float z)
1619 {
1620     v[0] = x;
1621     v[1] = y;
1622     v[2] = z;
1623 }
1624
1625 static void
1626 vsub(const float *src1, const float *src2, float *dst)
1627 {
1628     dst[0] = src1[0] - src2[0];
1629     dst[1] = src1[1] - src2[1];
1630     dst[2] = src1[2] - src2[2];
1631 }
1632
1633 static void
1634 vcopy(const float *v1, float *v2)
1635 {
1636     register int i;
1637     for (i = 0 ; i < 3 ; i++)
1638         v2[i] = v1[i];
1639 }
1640
1641 static void
1642 vcross(const float *v1, const float *v2, float *cross)
1643 {
1644     float temp[3];
1645
1646     temp[0] = (v1[1] * v2[2]) - (v1[2] * v2[1]);
1647     temp[1] = (v1[2] * v2[0]) - (v1[0] * v2[2]);
1648     temp[2] = (v1[0] * v2[1]) - (v1[1] * v2[0]);
1649     vcopy(temp, cross);
1650 }
1651
1652 static float
1653 vlength(const float *v)
1654 {
1655     float tmp = v[0] * v[0] + v[1] * v[1] + v[2] * v[2];
1656     return SQRT(tmp);
1657 }
1658
1659 static void
1660 vscale(float *v, float div)
1661 {
1662     v[0] *= div;
1663     v[1] *= div;
1664     v[2] *= div;
1665 }
1666
1667 static void
1668 vnormal(float *v)
1669 {
1670     vscale(v,1.0/vlength(v));
1671 }
1672
1673 static float
1674 vdot(const float *v1, const float *v2)
1675 {
1676     return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2];
1677 }
1678
1679 static void
1680 vadd(const float *src1, const float *src2, float *dst)
1681 {
1682     dst[0] = src1[0] + src2[0];
1683     dst[1] = src1[1] + src2[1];
1684     dst[2] = src1[2] + src2[2];
1685 }
1686
1687 /*
1688  *  Given an axis and angle, compute quaternion.
1689  */
1690 void
1691 axis_to_quat(float a[3], float phi, float q[4])
1692 {
1693     double sinphi2, cosphi2;
1694     double phi2 = phi/2.0;
1695     sinphi2 = sin(phi2);
1696     cosphi2 = cos(phi2);
1697     vnormal(a);
1698     vcopy(a,q);
1699     vscale(q,sinphi2);
1700     q[3] = cosphi2;
1701 }
1702
1703 /*
1704  * Project an x,y pair onto a sphere of radius r OR a hyperbolic sheet
1705  * if we are away from the center of the sphere.
1706  */
1707 static float
1708 tb_project_to_sphere(float r, float x, float y)
1709 {
1710     float d, t, z, tmp;
1711
1712     tmp = x*x + y*y;
1713     d = SQRT(tmp);
1714     if (d < r * 0.70710678118654752440) {    /* Inside sphere */
1715         tmp = r*r - d*d;
1716         z = SQRT(tmp);
1717     } else {           /* On hyperbola */
1718         t = r / 1.41421356237309504880;
1719         z = t*t / d;
1720     }
1721     return z;
1722 }
1723
1724 /*
1725  * Quaternions always obey:  a^2 + b^2 + c^2 + d^2 = 1.0
1726  * If they don't add up to 1.0, dividing by their magnitued will
1727  * renormalize them.
1728  *
1729  * Note: See the following for more information on quaternions:
1730  *
1731  * - Shoemake, K., Animating rotation with quaternion curves, Computer
1732  *   Graphics 19, No 3 (Proc. SIGGRAPH'85), 245-254, 1985.
1733  * - Pletinckx, D., Quaternion calculus as a basic tool in computer
1734  *   graphics, The Visual Computer 5, 2-13, 1989.
1735  */
1736 static void
1737 normalize_quat(float q[4])
1738 {
1739     int i;
1740     float mag, tmp;
1741
1742     tmp = q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + q[3]*q[3];
1743     mag = 1.0 / SQRT(tmp);
1744     for (i = 0; i < 4; i++)
1745         q[i] *= mag;
1746 }
1747
1748 /*
1749  * Ok, simulate a track-ball.  Project the points onto the virtual
1750  * trackball, then figure out the axis of rotation, which is the cross
1751  * product of P1 P2 and O P1 (O is the center of the ball, 0,0,0)
1752  * Note:  This is a deformed trackball-- is a trackball in the center,
1753  * but is deformed into a hyperbolic sheet of rotation away from the
1754  * center.  This particular function was chosen after trying out
1755  * several variations.
1756  *
1757  * It is assumed that the arguments to this routine are in the range
1758  * (-1.0 ... 1.0)
1759  */
1760 void
1761 trackball(float q[4], float p1x, float p1y, float p2x, float p2y)
1762 {
1763     float a[3]; /* Axis of rotation */
1764     float phi;  /* how much to rotate about axis */
1765     float p1[3], p2[3], d[3];
1766     float t;
1767
1768     if (p1x == p2x && p1y == p2y) {
1769         /* Zero rotation */
1770         vzero(q);
1771         q[3] = 1.0;
1772         return;
1773     }
1774
1775     /*
1776      * First, figure out z-coordinates for projection of P1 and P2 to
1777      * deformed sphere
1778      */
1779     vset(p1,p1x,p1y,tb_project_to_sphere(TRACKBALLSIZE,p1x,p1y));
1780     vset(p2,p2x,p2y,tb_project_to_sphere(TRACKBALLSIZE,p2x,p2y));
1781
1782     /*
1783      *  Now, we want the cross product of P1 and P2
1784      */
1785     vcross(p2,p1,a);
1786
1787     /*
1788      *  Figure out how much to rotate around that axis.
1789      */
1790     vsub(p1,p2,d);
1791     t = vlength(d) / (2.0*TRACKBALLSIZE);
1792
1793     /*
1794      * Avoid problems with out-of-control values...
1795      */
1796     if (t > 1.0) t = 1.0;
1797     if (t < -1.0) t = -1.0;
1798     phi = 2.0 * asin(t);
1799
1800     axis_to_quat(a,phi,q);
1801 }
1802
1803 /*
1804  * Given two rotations, e1 and e2, expressed as quaternion rotations,
1805  * figure out the equivalent single rotation and stuff it into dest.
1806  *
1807  * This routine also normalizes the result every RENORMCOUNT times it is
1808  * called, to keep error from creeping in.
1809  *
1810  * NOTE: This routine is written so that q1 or q2 may be the same
1811  * as dest (or each other).
1812  */
1813
1814 #define RENORMCOUNT 97
1815
1816 void
1817 add_quats(float q1[4], float q2[4], float dest[4])
1818 {
1819     static int count=0;
1820     float t1[4], t2[4], t3[4];
1821     float tf[4];
1822
1823 #if 0
1824 printf("q1 = %f %f %f %f\n", q1[0], q1[1], q1[2], q1[3]);
1825 printf("q2 = %f %f %f %f\n", q2[0], q2[1], q2[2], q2[3]);
1826 #endif
1827
1828     vcopy(q1,t1);
1829     vscale(t1,q2[3]);
1830
1831     vcopy(q2,t2);
1832     vscale(t2,q1[3]);
1833
1834     vcross(q2,q1,t3);
1835     vadd(t1,t2,tf);
1836     vadd(t3,tf,tf);
1837     tf[3] = q1[3] * q2[3] - vdot(q1,q2);
1838
1839 #if 0
1840 printf("tf = %f %f %f %f\n", tf[0], tf[1], tf[2], tf[3]);
1841 #endif
1842
1843     dest[0] = tf[0];
1844     dest[1] = tf[1];
1845     dest[2] = tf[2];
1846     dest[3] = tf[3];
1847
1848     if (++count > RENORMCOUNT) {
1849         count = 0;
1850         normalize_quat(dest);
1851     }
1852 }
1853
1854 /*
1855  * Build a rotation matrix, given a quaternion rotation.
1856  *
1857  */
1858 void
1859 build_rotmatrix(float m[4][4], float q[4])
1860 {
1861 //#define TRANSPOSED_QUAT
1862 #ifndef TRANSPOSED_QUAT
1863     m[0][0] = 1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2]);
1864     m[0][1] = 2.0 * (q[0] * q[1] - q[2] * q[3]);
1865     m[0][2] = 2.0 * (q[2] * q[0] + q[1] * q[3]);
1866     m[0][3] = 0.0;
1867
1868     m[1][0] = 2.0 * (q[0] * q[1] + q[2] * q[3]);
1869     m[1][1]= 1.0 - 2.0 * (q[2] * q[2] + q[0] * q[0]);
1870     m[1][2] = 2.0 * (q[1] * q[2] - q[0] * q[3]);
1871     m[1][3] = 0.0;
1872
1873     m[2][0] = 2.0 * (q[2] * q[0] - q[1] * q[3]);
1874     m[2][1] = 2.0 * (q[1] * q[2] + q[0] * q[3]);
1875     m[2][2] = 1.0 - 2.0 * (q[1] * q[1] + q[0] * q[0]);
1876     
1877     m[2][3] = 0.0;
1878     m[3][0] = 0.0;
1879     m[3][1] = 0.0;
1880     m[3][2] = 0.0;
1881     m[3][3] = 1.0;
1882 #else //  TRANSPOSED_QUAT
1883     m[0][0] = 1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2]);
1884     m[0][1] = 2.0 * (q[0] * q[1] + q[2] * q[3]);
1885     m[0][2] = 2.0 * (q[2] * q[0] - q[1] * q[3]);
1886     m[0][3] = 0.0;
1887
1888     m[1][0] = 2.0 * (q[0] * q[1] - q[2] * q[3]);
1889     m[1][1] = 1.0 - 2.0 * (q[2] * q[2] + q[0] * q[0]);
1890     m[1][2] = 2.0 * (q[1] * q[2] + q[0] * q[3]);
1891     m[1][3] = 0.0;
1892
1893     m[2][0] = 2.0 * (q[2] * q[0] + q[1] * q[3]);
1894     m[2][1] = 2.0 * (q[1] * q[2] - q[0] * q[3]);
1895     m[2][2] = 1.0 - 2.0 * (q[1] * q[1] + q[0] * q[0]);
1896     m[2][3] = 0.0;
1897     
1898     m[3][0] = 0.0;
1899     m[3][1] = 0.0;
1900     m[3][2] = 0.0;
1901     m[3][3] = 1.0;
1902 #endif // 0
1903 }
1904