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