]> git.mxchange.org Git - flightgear.git/blob - src/Input/input.cxx
09ef2c21d0bbafc740253fa7ac12609f67b2cbc8
[flightgear.git] / src / Input / input.cxx
1 // input.cxx -- handle user input from various sources.
2 //
3 // Written by David Megginson, started May 2001.
4 //
5 // Copyright (C) 2001 David Megginson, david@megginson.com
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23 #ifdef HAVE_CONFIG_H
24 #  include <config.h>
25 #endif
26
27 #ifdef HAVE_WINDOWS_H
28 #  include <windows.h>
29 #endif
30
31 #include <simgear/compiler.h>
32
33 #include <math.h>
34 #include <ctype.h>
35 #include <sstream>
36
37 #include STL_FSTREAM
38 #include STL_STRING
39 #include <vector>
40
41 #include <simgear/compiler.h>
42
43 #include <simgear/constants.h>
44 #include <simgear/debug/logstream.hxx>
45 #include <simgear/math/SGMath.hxx>
46 #include <simgear/props/props.hxx>
47 #include <simgear/scene/util/SGSceneUserData.hxx>
48
49 #include <Aircraft/aircraft.hxx>
50 #include <Autopilot/xmlauto.hxx>
51 #include <Cockpit/hud.hxx>
52 #include <Cockpit/panel.hxx>
53 #include <Cockpit/panel_io.hxx>
54 #include <GUI/gui.h>
55 #include <Model/panelnode.hxx>
56 #include <Scripting/NasalSys.hxx>
57
58 #include <Main/globals.hxx>
59 #include <Main/fg_props.hxx>
60
61 #include "input.hxx"
62
63 #include <Scenery/scenery.hxx>
64 #include <Main/renderer.hxx>
65
66 SG_USING_STD(ifstream);
67 SG_USING_STD(ostringstream);
68 SG_USING_STD(string);
69 SG_USING_STD(vector);
70
71 void mouseClickHandler(int button, int updown, int x, int y, bool mainWindow, const osgGA::GUIEventAdapter*);
72 void mouseMotionHandler(int x, int y);
73 void keyHandler(int key, int keymod, int mousex, int mousey);
74
75 \f
76 ////////////////////////////////////////////////////////////////////////
77 // Local variables.
78 ////////////////////////////////////////////////////////////////////////
79
80 static FGInput * default_input = 0;
81
82 \f
83 ////////////////////////////////////////////////////////////////////////
84 // Local functions.
85 ////////////////////////////////////////////////////////////////////////
86
87 static bool
88 getModShift ()
89 {
90   return bool(fgGetKeyModifiers() & KEYMOD_SHIFT);
91 }
92
93 static bool
94 getModCtrl ()
95 {
96   return bool(fgGetKeyModifiers() & KEYMOD_CTRL);
97 }
98
99 static bool
100 getModAlt ()
101 {
102   return bool(fgGetKeyModifiers() & KEYMOD_ALT);
103 }
104
105 static bool
106 getModMeta ()
107 {
108   return bool(fgGetKeyModifiers() & KEYMOD_META);
109 }
110
111 static bool
112 getModSuper ()
113 {
114   return bool(fgGetKeyModifiers() & KEYMOD_SUPER);
115 }
116
117 \f
118 ////////////////////////////////////////////////////////////////////////
119 // Implementation of FGInput.
120 ////////////////////////////////////////////////////////////////////////
121
122
123 FGInput::FGInput () :
124     _key_event(fgGetNode("/devices/status/keyboard/event", true))
125 {
126     if (default_input == 0)
127         default_input = this;
128 }
129
130 FGInput::~FGInput ()
131 {
132     if (default_input == this)
133         default_input = 0;
134 }
135
136 void
137 FGInput::init ()
138 {
139   _init_joystick();
140   _init_mouse();
141
142   fgRegisterKeyHandler(keyHandler);
143   fgRegisterMouseClickHandler(mouseClickHandler);
144   fgRegisterMouseMotionHandler(mouseMotionHandler);
145 }
146
147 void
148 FGInput::reinit ()
149 {
150     init();
151 }
152
153 void
154 FGInput::postinit ()
155 {
156   _postinit_joystick();
157   _postinit_keyboard();
158 }
159
160 void
161 FGInput::bind ()
162 {
163   fgTie("/devices/status/keyboard/shift", getModShift);
164   fgTie("/devices/status/keyboard/ctrl", getModCtrl);
165   fgTie("/devices/status/keyboard/alt", getModAlt);
166   fgTie("/devices/status/keyboard/meta", getModMeta);
167   fgTie("/devices/status/keyboard/super", getModSuper);
168
169   _key_event->tie("key", SGRawValuePointer<int>(&_key_code));
170   _key_event->tie("pressed", SGRawValuePointer<bool>(&_key_pressed));
171   _key_event->tie("modifier", SGRawValuePointer<int>(&_key_modifiers));
172   _key_event->tie("modifier/shift", SGRawValuePointer<bool>(&_key_shift));
173   _key_event->tie("modifier/ctrl", SGRawValuePointer<bool>(&_key_ctrl));
174   _key_event->tie("modifier/alt", SGRawValuePointer<bool>(&_key_alt));
175   _key_event->tie("modifier/meta", SGRawValuePointer<bool>(&_key_meta));
176   _key_event->tie("modifier/super", SGRawValuePointer<bool>(&_key_super));
177 }
178
179 void
180 FGInput::unbind ()
181 {
182   fgUntie("/devices/status/keyboard/shift");
183   fgUntie("/devices/status/keyboard/ctrl");
184   fgUntie("/devices/status/keyboard/alt");
185   fgUntie("/devices/status/keyboard/meta");
186   fgUntie("/devices/status/keyboard/super");
187
188   _key_event->untie("key");
189   _key_event->untie("pressed");
190   _key_event->untie("modifier");
191   _key_event->untie("modifier/shift");
192   _key_event->untie("modifier/ctrl");
193   _key_event->untie("modifier/alt");
194   _key_event->untie("modifier/meta");
195   _key_event->untie("modifier/super");
196 }
197
198 void 
199 FGInput::update (double dt)
200 {
201   _update_keyboard();
202   _update_joystick(dt);
203   _update_mouse(dt);
204 }
205
206 void
207 FGInput::suspend ()
208 {
209     // NO-OP
210 }
211
212 void
213 FGInput::resume ()
214 {
215     // NO-OP
216 }
217
218 bool
219 FGInput::is_suspended () const
220 {
221     return false;
222 }
223
224 void
225 FGInput::makeDefault (bool status)
226 {
227     if (status)
228         default_input = this;
229     else if (default_input == this)
230         default_input = 0;
231 }
232
233 void
234 FGInput::doKey (int k, int modifiers, int x, int y)
235 {
236                                 // Sanity check.
237   if (k < 0 || k >= MAX_KEYS) {
238     SG_LOG(SG_INPUT, SG_WARN, "Key value " << k << " out of range");
239     return;
240   }
241
242   _key_code = k;
243   _key_modifiers = modifiers & ~KEYMOD_RELEASED;
244   _key_pressed = !bool(modifiers & KEYMOD_RELEASED);
245   _key_shift = bool(modifiers & KEYMOD_SHIFT);
246   _key_ctrl = bool(modifiers & KEYMOD_CTRL);
247   _key_alt = bool(modifiers & KEYMOD_ALT);
248   _key_meta = bool(modifiers & KEYMOD_META);
249   _key_super = bool(modifiers & KEYMOD_SUPER);
250   _key_event->fireValueChanged();
251   if (!_key_code)
252     return;
253
254   k = _key_code;
255   modifiers = _key_modifiers | (_key_pressed ? KEYMOD_NONE : KEYMOD_RELEASED);
256   button &b = _key_bindings[k];
257
258                                 // Key pressed.
259   if (!(modifiers & KEYMOD_RELEASED)) {
260     SG_LOG( SG_INPUT, SG_DEBUG, "User pressed key " << k
261             << " with modifiers " << modifiers );
262     if (!b.last_state || b.is_repeatable) {
263       const binding_list_t &bindings = _find_key_bindings(k, modifiers);
264
265       for (unsigned int i = 0; i < bindings.size(); i++)
266         bindings[i]->fire();
267       b.last_state = 1;
268     }
269   }
270                                 // Key released.
271   else {
272     SG_LOG(SG_INPUT, SG_DEBUG, "User released key " << k
273            << " with modifiers " << modifiers);
274     if (b.last_state) {
275       const binding_list_t &bindings = _find_key_bindings(k, modifiers);
276       for (unsigned int i = 0; i < bindings.size(); i++)
277         bindings[i]->fire();
278       b.last_state = 0;
279     }
280   }
281 }
282
283 void
284 FGInput::doMouseClick (int b, int updown, int x, int y, bool mainWindow, const osgGA::GUIEventAdapter* ea)
285 {
286   int modifiers = fgGetKeyModifiers();
287
288   mouse &m = _mouse_bindings[0];
289   mouse_mode &mode = m.modes[m.current_mode];
290
291                                 // Let the property manager know.
292   if (b >= 0 && b < MAX_MOUSE_BUTTONS)
293     m.mouse_button_nodes[b]->setBoolValue(updown == MOUSE_BUTTON_DOWN);
294
295                                 // Pass on to PUI and the panel if
296                                 // requested, and return if one of
297                                 // them consumes the event.
298
299   if (updown != MOUSE_BUTTON_DOWN) {
300     // Execute the mouse up event in any case, may be we should
301     // stop processing here?
302     while (!_activePickCallbacks[b].empty()) {
303       _activePickCallbacks[b].front()->buttonReleased();
304       _activePickCallbacks[b].pop_front();
305     }
306   }
307
308   if (mode.pass_through) {
309     // The pu stuff seems to need that. May be it does opengl picking ...
310     fgMakeCurrent();
311     if (0 <= x && 0 <= y && puMouse(b, updown, x, y))
312       return;
313     else if (0 <= x && 0 <= y && (globals->get_current_panel() != 0) &&
314              globals->get_current_panel()->getVisibility() &&
315              globals->get_current_panel()->doMouseAction(b, updown, x, y))
316       return;
317     else if (0 <= x && 0 <= y && fgHandle3DPanelMouseEvent(b, updown, x, y))
318       return;
319     else {
320       // pui didn't want the click event so compute a
321       // scenegraph intersection point corresponding to the mouse click
322       if (updown == MOUSE_BUTTON_DOWN) {
323
324         // Get the list of hit callbacks. Take the first callback that
325         // accepts the mouse button press and ignore the rest of them
326         // That is they get sorted by distance and by scenegraph depth.
327         // The nearest one is the first one and the deepest
328         // (the most specialized one in the scenegraph) is the first.
329         std::vector<SGSceneryPick> pickList;
330         if (FGRenderer::pick(x, y, pickList, ea)) {
331           std::vector<SGSceneryPick>::const_iterator i;
332           for (i = pickList.begin(); i != pickList.end(); ++i) {
333             if (i->callback->buttonPressed(b, i->info)) {
334               _activePickCallbacks[b].push_back(i->callback);
335               return;
336             }
337           }
338         }
339       }
340     }
341   }
342
343   // OK, PUI and the panel didn't want the click
344   if (b >= MAX_MOUSE_BUTTONS) {
345     SG_LOG(SG_INPUT, SG_ALERT, "Mouse button " << b
346            << " where only " << MAX_MOUSE_BUTTONS << " expected");
347     return;
348   }
349
350   _update_button(m.modes[m.current_mode].buttons[b], modifiers, 0 != updown, x, y);
351 }
352
353 void
354 FGInput::doMouseMotion (int x, int y)
355 {
356   // Don't call fgGetKeyModifiers() here, until we are using a
357   // toolkit that supports getting the mods from outside a key
358   // callback.  Glut doesn't.
359   int modifiers = KEYMOD_NONE;
360
361   int xsize = fgGetInt("/sim/startup/xsize", 800);
362   int ysize = fgGetInt("/sim/startup/ysize", 600);
363
364   mouse &m = _mouse_bindings[0];
365
366   if (m.current_mode < 0 || m.current_mode >= m.nModes) {
367       m.x = x;
368       m.y = y;
369       return;
370   }
371   mouse_mode &mode = m.modes[m.current_mode];
372
373                                 // Pass on to PUI if requested, and return
374                                 // if PUI consumed the event.
375   if (mode.pass_through && puMouse(x, y)) {
376       m.x = x;
377       m.y = y;
378       return;
379   }
380
381                                 // OK, PUI didn't want the event,
382                                 // so we can play with it.
383   if (x != m.x) {
384     int delta = x - m.x;
385     for (unsigned int i = 0; i < mode.x_bindings[modifiers].size(); i++)
386       mode.x_bindings[modifiers][i]->fire(double(delta), double(xsize));
387   }
388   if (y != m.y) {
389     int delta = y - m.y;
390     for (unsigned int i = 0; i < mode.y_bindings[modifiers].size(); i++)
391       mode.y_bindings[modifiers][i]->fire(double(delta), double(ysize));
392   }
393
394                                 // Constrain the mouse if requested
395   if (mode.constrained) {
396     bool need_warp = false;
397     if (x <= (xsize * .25) || x >= (xsize * .75)) {
398       x = int(xsize * .5);
399       need_warp = true;
400     }
401
402     if (y <= (ysize * .25) || y >= (ysize * .75)) {
403       y = int(ysize * .5);
404       need_warp = true;
405     }
406
407     if (need_warp)
408       fgWarpMouse(x, y);
409   }
410
411   if (m.x != x)
412       fgSetInt("/devices/status/mice/mouse/x", m.x = x);
413
414   if (m.y != y)
415       fgSetInt("/devices/status/mice/mouse/y", m.y = y);
416 }
417
418
419 void
420 FGInput::_scan_joystick_dir(SGPath *path, SGPropertyNode* node, int *index)
421 {
422   ulDir *dir = ulOpenDir(path->c_str());
423   if (dir) {
424     ulDirEnt* dent;
425     while ((dent = ulReadDir(dir)) != 0) {
426       if (dent->d_name[0] == '.')
427         continue;
428
429       SGPath p(path->str());
430       p.append(dent->d_name);
431       _scan_joystick_dir(&p, node, index);
432     }
433     ulCloseDir(dir);
434
435   } else if (path->extension() == "xml") {
436     SG_LOG(SG_INPUT, SG_DEBUG, "Reading joystick file " << path->str());
437     SGPropertyNode *n = node->getChild("js-named", (*index)++, true);
438     readProperties(path->str(), n);
439     n->setStringValue("source", path->c_str());
440   }
441 }
442
443
444 void
445 FGInput::_init_joystick ()
446 {
447   jsInit();
448                                 // TODO: zero the old bindings first.
449   SG_LOG(SG_INPUT, SG_DEBUG, "Initializing joystick bindings");
450   SGPropertyNode * js_nodes = fgGetNode("/input/joysticks", true);
451
452   // read all joystick xml files into /input/joysticks/js_named[1000++]
453   SGPath path(globals->get_fg_root());
454   path.append("Input/Joysticks");
455   int js_named_index = 1000;
456   _scan_joystick_dir(&path, js_nodes, &js_named_index);
457
458   // build name->node map with each <name> (reverse order)
459   map<string, SGPropertyNode_ptr> jsmap;
460   vector<SGPropertyNode_ptr> js_named = js_nodes->getChildren("js-named");
461
462   for (int k = (int)js_named.size() - 1; k >= 0; k--) {
463     SGPropertyNode *n = js_named[k];
464     vector<SGPropertyNode_ptr> names = n->getChildren("name");
465     if (names.size() && (n->getChildren("axis").size() || n->getChildren("button").size()))
466       for (unsigned int j = 0; j < names.size(); j++)
467         jsmap[names[j]->getStringValue()] = n;
468   }
469
470   // set up js[] nodes
471   for (int i = 0; i < MAX_JOYSTICKS; i++) {
472     jsJoystick * js = new jsJoystick(i);
473     _joystick_bindings[i].js = js;
474
475     if (js->notWorking()) {
476       SG_LOG(SG_INPUT, SG_DEBUG, "Joystick " << i << " not found");
477       continue;
478     }
479
480     const char * name = js->getName();
481     SGPropertyNode_ptr js_node = js_nodes->getChild("js", i);
482
483     if (js_node) {
484       SG_LOG(SG_INPUT, SG_INFO, "Using existing bindings for joystick " << i);
485
486     } else {
487       SG_LOG(SG_INPUT, SG_INFO, "Looking for bindings for joystick \"" << name << '"');
488       SGPropertyNode_ptr named;
489
490       if ((named = jsmap[name])) {
491         string source = named->getStringValue("source", "user defined");
492         SG_LOG(SG_INPUT, SG_INFO, "... found joystick: " << source);
493
494       } else if ((named = jsmap["default"])) {
495         string source = named->getStringValue("source", "user defined");
496         SG_LOG(SG_INPUT, SG_INFO, "No config found for joystick \"" << name
497             << "\"\nUsing default: \"" << source << '"');
498
499       } else {
500         throw sg_throwable(string("No joystick configuration file with "
501             "<name>default</name> entry found!"));
502       }
503
504       js_node = js_nodes->getChild("js", i, true);
505       copyProperties(named, js_node);
506       js_node->setStringValue("id", name);
507     }
508   }
509
510   // get rid of unused config nodes
511   js_nodes->removeChildren("js-named", false);
512 }
513
514
515 void
516 FGInput::_postinit_keyboard()
517 {
518   SG_LOG(SG_INPUT, SG_DEBUG, "Initializing key bindings");
519   _module = "__kbd";
520   SGPropertyNode * key_nodes = fgGetNode("/input/keyboard");
521   if (key_nodes == 0) {
522     SG_LOG(SG_INPUT, SG_WARN, "No key bindings (/input/keyboard)!!");
523     key_nodes = fgGetNode("/input/keyboard", true);
524   }
525
526   FGNasalSys *nasalsys = (FGNasalSys *)globals->get_subsystem("nasal");
527   vector<SGPropertyNode_ptr> nasal = key_nodes->getChildren("nasal");
528   for (unsigned int j = 0; j < nasal.size(); j++) {
529     nasal[j]->setStringValue("module", _module.c_str());
530     nasalsys->handleCommand(nasal[j]);
531   }
532
533   vector<SGPropertyNode_ptr> keys = key_nodes->getChildren("key");
534   for (unsigned int i = 0; i < keys.size(); i++) {
535     int index = keys[i]->getIndex();
536     SG_LOG(SG_INPUT, SG_DEBUG, "Binding key " << index);
537
538     _key_bindings[index].bindings->clear();
539     _key_bindings[index].is_repeatable = keys[i]->getBoolValue("repeatable");
540     _key_bindings[index].last_state = 0;
541     _read_bindings(keys[i], _key_bindings[index].bindings, KEYMOD_NONE);
542   }
543 }
544
545
546 void
547 FGInput::_postinit_joystick()
548 {
549   FGNasalSys *nasalsys = (FGNasalSys *)globals->get_subsystem("nasal");
550   SGPropertyNode *js_nodes = fgGetNode("/input/joysticks");
551
552   for (int i = 0; i < MAX_JOYSTICKS; i++) {
553     SGPropertyNode_ptr js_node = js_nodes->getChild("js", i);
554     jsJoystick *js = _joystick_bindings[i].js;
555     if (!js_node || js->notWorking())
556       continue;
557
558 #ifdef WIN32
559     JOYCAPS jsCaps ;
560     joyGetDevCaps( i, &jsCaps, sizeof(jsCaps) );
561     unsigned int nbuttons = jsCaps.wNumButtons;
562     if (nbuttons > MAX_JOYSTICK_BUTTONS) nbuttons = MAX_JOYSTICK_BUTTONS;
563 #else
564     unsigned int nbuttons = MAX_JOYSTICK_BUTTONS;
565 #endif
566
567     int naxes = js->getNumAxes();
568     if (naxes > MAX_JOYSTICK_AXES) naxes = MAX_JOYSTICK_AXES;
569     _joystick_bindings[i].naxes = naxes;
570     _joystick_bindings[i].nbuttons = nbuttons;
571
572     SG_LOG(SG_INPUT, SG_DEBUG, "Initializing joystick " << i);
573
574                                 // Set up range arrays
575     float minRange[MAX_JOYSTICK_AXES];
576     float maxRange[MAX_JOYSTICK_AXES];
577     float center[MAX_JOYSTICK_AXES];
578
579                                 // Initialize with default values
580     js->getMinRange(minRange);
581     js->getMaxRange(maxRange);
582     js->getCenter(center);
583
584                                 // Allocate axes and buttons
585     _joystick_bindings[i].axes = new axis[naxes];
586     _joystick_bindings[i].buttons = new button[nbuttons];
587
588     //
589     // Initialize nasal groups.
590     //
591     ostringstream str;
592     str << "__js" << i;
593     _module = str.str();
594     nasalsys->createModule(_module.c_str(), _module.c_str(), "", 0);
595
596     vector<SGPropertyNode_ptr> nasal = js_node->getChildren("nasal");
597     unsigned int j;
598     for (j = 0; j < nasal.size(); j++) {
599       nasal[j]->setStringValue("module", _module.c_str());
600       nasalsys->handleCommand(nasal[j]);
601     }
602
603     //
604     // Initialize the axes.
605     //
606     vector<SGPropertyNode_ptr> axes = js_node->getChildren("axis");
607     size_t nb_axes = axes.size();
608     for (j = 0; j < nb_axes; j++ ) {
609       const SGPropertyNode * axis_node = axes[j];
610       const SGPropertyNode * num_node = axis_node->getChild("number");
611       int n_axis = axis_node->getIndex();
612       if (num_node != 0) {
613           n_axis = num_node->getIntValue(TGT_PLATFORM, -1);
614
615           // Silently ignore platforms that are not specified within the
616           // <number></number> section
617           if (n_axis < 0)
618              continue;
619       }
620
621       if (n_axis >= naxes) {
622           SG_LOG(SG_INPUT, SG_DEBUG, "Dropping bindings for axis " << n_axis);
623           continue;
624       }
625       axis &a = _joystick_bindings[i].axes[n_axis];
626
627       js->setDeadBand(n_axis, axis_node->getDoubleValue("dead-band", 0.0));
628
629       a.tolerance = axis_node->getDoubleValue("tolerance", 0.002);
630       minRange[n_axis] = axis_node->getDoubleValue("min-range", minRange[n_axis]);
631       maxRange[n_axis] = axis_node->getDoubleValue("max-range", maxRange[n_axis]);
632       center[n_axis] = axis_node->getDoubleValue("center", center[n_axis]);
633
634       _read_bindings(axis_node, a.bindings, KEYMOD_NONE);
635
636       // Initialize the virtual axis buttons.
637       _init_button(axis_node->getChild("low"), a.low, "low");
638       a.low_threshold = axis_node->getDoubleValue("low-threshold", -0.9);
639
640       _init_button(axis_node->getChild("high"), a.high, "high");
641       a.high_threshold = axis_node->getDoubleValue("high-threshold", 0.9);
642       a.interval_sec = axis_node->getDoubleValue("interval-sec",0.0);
643       a.last_dt = 0.0;
644     }
645
646     //
647     // Initialize the buttons.
648     //
649     vector<SGPropertyNode_ptr> buttons = js_node->getChildren("button");
650     char buf[32];
651     for (j = 0; j < buttons.size() && j < nbuttons; j++) {
652       const SGPropertyNode * button_node = buttons[j];
653       const SGPropertyNode * num_node = button_node->getChild("number");
654       size_t n_but = button_node->getIndex();
655       if (num_node != 0) {
656           n_but = num_node->getIntValue(TGT_PLATFORM,n_but);
657       }
658
659       if (n_but >= nbuttons) {
660           SG_LOG(SG_INPUT, SG_DEBUG, "Dropping bindings for button " << n_but);
661           continue;
662       }
663
664       sprintf(buf, "%d", n_but);
665       SG_LOG(SG_INPUT, SG_DEBUG, "Initializing button " << n_but);
666       _init_button(button_node,
667                    _joystick_bindings[i].buttons[n_but],
668                    buf);
669
670       // get interval-sec property
671       button &b = _joystick_bindings[i].buttons[n_but];
672       if (button_node != 0) {
673         b.interval_sec = button_node->getDoubleValue("interval-sec",0.0);
674         b.last_dt = 0.0;
675       }
676     }
677
678     js->setMinRange(minRange);
679     js->setMaxRange(maxRange);
680     js->setCenter(center);
681   }
682 }
683
684
685 // 
686 // Map of all known cursor names
687 // This used to contain all the Glut cursors, but those are
688 // not defined by other toolkits.  It now supports only the cursor
689 // images we actually use, in the interest of portability.  Someday,
690 // it would be cool to write an OpenGL cursor renderer, with the
691 // cursors defined as textures referenced in the property tree.  This
692 // list could then be eliminated. -Andy
693 //
694 static struct {
695   const char * name;
696   int cursor;
697 } mouse_cursor_map[] = {
698   { "none", MOUSE_CURSOR_NONE },
699   { "inherit", MOUSE_CURSOR_POINTER },
700   { "wait", MOUSE_CURSOR_WAIT },
701   { "crosshair", MOUSE_CURSOR_CROSSHAIR },
702   { "left-right", MOUSE_CURSOR_LEFTRIGHT },
703   { 0, 0 }
704 };
705
706 void
707 FGInput::_init_mouse ()
708 {
709   SG_LOG(SG_INPUT, SG_DEBUG, "Initializing mouse bindings");
710   _module = "";
711
712   SGPropertyNode * mouse_nodes = fgGetNode("/input/mice");
713   if (mouse_nodes == 0) {
714     SG_LOG(SG_INPUT, SG_WARN, "No mouse bindings (/input/mice)!!");
715     mouse_nodes = fgGetNode("/input/mice", true);
716   }
717
718   int j;
719   for (int i = 0; i < MAX_MICE; i++) {
720     SGPropertyNode * mouse_node = mouse_nodes->getChild("mouse", i, true);
721     mouse &m = _mouse_bindings[i];
722
723                                 // Grab node pointers
724     char buf[64];
725     sprintf(buf, "/devices/status/mice/mouse[%d]/mode", i);
726     m.mode_node = fgGetNode(buf);
727     if (m.mode_node == NULL) {
728       m.mode_node = fgGetNode(buf, true);
729       m.mode_node->setIntValue(0);
730     }
731     for (j = 0; j < MAX_MOUSE_BUTTONS; j++) {
732       sprintf(buf, "/devices/status/mice/mouse[%d]/button[%d]", i, j);
733       m.mouse_button_nodes[j] = fgGetNode(buf, true);
734       m.mouse_button_nodes[j]->setBoolValue(false);
735     }
736
737                                 // Read all the modes
738     m.nModes = mouse_node->getIntValue("mode-count", 1);
739     m.modes = new mouse_mode[m.nModes];
740
741     for (int j = 0; j < m.nModes; j++) {
742       int k;
743
744                                 // Read the mouse cursor for this mode
745       SGPropertyNode * mode_node = mouse_node->getChild("mode", j, true);
746       const char * cursor_name =
747         mode_node->getStringValue("cursor", "inherit");
748       m.modes[j].cursor = MOUSE_CURSOR_POINTER;
749       for (k = 0; mouse_cursor_map[k].name != 0; k++) {
750         if (!strcmp(mouse_cursor_map[k].name, cursor_name)) {
751           m.modes[j].cursor = mouse_cursor_map[k].cursor;
752           break;
753         }
754       }
755
756                                 // Read other properties for this mode
757       m.modes[j].constrained = mode_node->getBoolValue("constrained", false);
758       m.modes[j].pass_through = mode_node->getBoolValue("pass-through", false);
759
760                                 // Read the button bindings for this mode
761       m.modes[j].buttons = new button[MAX_MOUSE_BUTTONS];
762       char buf[32];
763       for (k = 0; k < MAX_MOUSE_BUTTONS; k++) {
764         sprintf(buf, "mouse button %d", k);
765         SG_LOG(SG_INPUT, SG_DEBUG, "Initializing mouse button " << k);
766         _init_button(mode_node->getChild("button", k),
767                      m.modes[j].buttons[k],
768                      buf);
769       }
770
771                                 // Read the axis bindings for this mode
772       _read_bindings(mode_node->getChild("x-axis", 0, true),
773                      m.modes[j].x_bindings,
774                      KEYMOD_NONE);
775       _read_bindings(mode_node->getChild("y-axis", 0, true),
776                      m.modes[j].y_bindings,
777                      KEYMOD_NONE);
778     }
779   }
780 }
781
782
783 void
784 FGInput::_init_button (const SGPropertyNode * node,
785                        button &b,
786                        const string name)
787 {       
788   if (node == 0) {
789     SG_LOG(SG_INPUT, SG_DEBUG, "No bindings for button " << name);
790   } else {
791     b.is_repeatable = node->getBoolValue("repeatable", b.is_repeatable);
792     
793                 // Get the bindings for the button
794     _read_bindings(node, b.bindings, KEYMOD_NONE);
795   }
796 }
797
798
799 void
800 FGInput::_update_keyboard ()
801 {
802   // no-op
803 }
804
805
806 void
807 FGInput::_update_joystick (double dt)
808 {
809   int modifiers = KEYMOD_NONE;  // FIXME: any way to get the real ones?
810   int buttons;
811   // float js_val, diff;
812   float axis_values[MAX_JOYSTICK_AXES];
813
814   int i;
815   int j;
816
817   for ( i = 0; i < MAX_JOYSTICKS; i++) {
818
819     jsJoystick * js = _joystick_bindings[i].js;
820     if (js == 0 || js->notWorking())
821       continue;
822
823     js->read(&buttons, axis_values);
824
825                                 // Fire bindings for the axes.
826     for ( j = 0; j < _joystick_bindings[i].naxes; j++) {
827       axis &a = _joystick_bindings[i].axes[j];
828       
829                                 // Do nothing if the axis position
830                                 // is unchanged; only a change in
831                                 // position fires the bindings.
832       if (fabs(axis_values[j] - a.last_value) > a.tolerance) {
833 //      SG_LOG(SG_INPUT, SG_DEBUG, "Axis " << j << " has moved");
834         a.last_value = axis_values[j];
835 //      SG_LOG(SG_INPUT, SG_DEBUG, "There are "
836 //             << a.bindings[modifiers].size() << " bindings");
837         for (unsigned int k = 0; k < a.bindings[modifiers].size(); k++)
838           a.bindings[modifiers][k]->fire(axis_values[j]);
839       }
840      
841                                 // do we have to emulate axis buttons?
842       a.last_dt += dt;
843       if(a.last_dt >= a.interval_sec) {
844         if (a.low.bindings[modifiers].size())
845           _update_button(_joystick_bindings[i].axes[j].low,
846                          modifiers,
847                          axis_values[j] < a.low_threshold,
848                          -1, -1);
849       
850         if (a.high.bindings[modifiers].size())
851           _update_button(_joystick_bindings[i].axes[j].high,
852                          modifiers,
853                          axis_values[j] > a.high_threshold,
854                          -1, -1);
855          a.last_dt -= a.interval_sec;
856       }
857     }
858
859                                 // Fire bindings for the buttons.
860     for (j = 0; j < _joystick_bindings[i].nbuttons; j++) {
861       button &b = _joystick_bindings[i].buttons[j];
862       b.last_dt += dt;
863       if(b.last_dt >= b.interval_sec) {
864         _update_button(_joystick_bindings[i].buttons[j],
865                        modifiers,
866                        (buttons & (1 << j)) > 0,
867                        -1, -1);
868         b.last_dt -= b.interval_sec;
869       }
870     }
871   }
872 }
873
874 void
875 FGInput::_update_mouse ( double dt )
876 {
877   mouse &m = _mouse_bindings[0];
878   int mode =  m.mode_node->getIntValue();
879   if (mode != m.current_mode) {
880     m.current_mode = mode;
881     m.timeout = fgGetDouble( "/sim/mouse/cursor-timeout-sec", 10.0 );
882     if (mode >= 0 && mode < m.nModes) {
883       fgSetMouseCursor(m.modes[mode].cursor);
884       m.x = fgGetInt("/sim/startup/xsize", 800) / 2;
885       m.y = fgGetInt("/sim/startup/ysize", 600) / 2;
886       fgWarpMouse(m.x, m.y);
887     } else {
888       SG_LOG(SG_INPUT, SG_DEBUG, "Mouse mode " << mode << " out of range");
889       fgSetMouseCursor(MOUSE_CURSOR_POINTER);
890     }
891   }
892
893   if ( fgGetBool( "/sim/mouse/hide-cursor", true ) ) {
894       if ( m.x != m.save_x || m.y != m.save_y ) {
895           m.timeout = fgGetDouble( "/sim/mouse/cursor-timeout-sec", 10.0 );
896           fgSetMouseCursor(m.modes[mode].cursor);
897       } else {
898           m.timeout -= dt;
899           if ( m.timeout <= 0.0 ) {
900               fgSetMouseCursor(MOUSE_CURSOR_NONE);
901               m.timeout = 0.0;
902           }
903       }
904       m.save_x = m.x;
905       m.save_y = m.y;
906   }
907
908   // handle repeatable mouse press events
909   std::map<int, std::list<SGSharedPtr<SGPickCallback> > >::iterator mi;
910   for (mi = _activePickCallbacks.begin();
911        mi != _activePickCallbacks.end(); ++mi) {
912     std::list<SGSharedPtr<SGPickCallback> >::iterator li;
913     for (li = mi->second.begin(); li != mi->second.end(); ++li) {
914       (*li)->update(dt);
915     }
916   }
917 }
918
919 void
920 FGInput::_update_button (button &b, int modifiers, bool pressed,
921                          int x, int y)
922 {
923   if (pressed) {
924                                 // The press event may be repeated.
925     if (!b.last_state || b.is_repeatable) {
926       SG_LOG( SG_INPUT, SG_DEBUG, "Button has been pressed" );
927       for (unsigned int k = 0; k < b.bindings[modifiers].size(); k++) {
928         b.bindings[modifiers][k]->fire(x, y);
929       }
930     }
931   } else {
932                                 // The release event is never repeated.
933     if (b.last_state) {
934       SG_LOG( SG_INPUT, SG_DEBUG, "Button has been released" );
935       for (unsigned int k = 0; k < b.bindings[modifiers|KEYMOD_RELEASED].size(); k++)
936         b.bindings[modifiers|KEYMOD_RELEASED][k]->fire(x, y);
937     }
938   }
939           
940   b.last_state = pressed;
941 }  
942
943
944 void
945 FGInput::_read_bindings (const SGPropertyNode * node, 
946                          binding_list_t * binding_list,
947                          int modifiers)
948 {
949   SG_LOG(SG_INPUT, SG_DEBUG, "Reading all bindings");
950   vector<SGPropertyNode_ptr> bindings = node->getChildren("binding");
951   for (unsigned int i = 0; i < bindings.size(); i++) {
952     const char *cmd = bindings[i]->getStringValue("command");
953     SG_LOG(SG_INPUT, SG_DEBUG, "Reading binding " << cmd);
954
955     if (!strcmp(cmd, "nasal") && !_module.empty())
956       bindings[i]->setStringValue("module", _module.c_str());
957     binding_list[modifiers].push_back(new SGBinding(bindings[i], globals->get_props()));
958   }
959
960                                 // Read nested bindings for modifiers
961   if (node->getChild("mod-up") != 0)
962     _read_bindings(node->getChild("mod-up"), binding_list,
963                    modifiers|KEYMOD_RELEASED);
964
965   if (node->getChild("mod-shift") != 0)
966     _read_bindings(node->getChild("mod-shift"), binding_list,
967                    modifiers|KEYMOD_SHIFT);
968
969   if (node->getChild("mod-ctrl") != 0)
970     _read_bindings(node->getChild("mod-ctrl"), binding_list,
971                    modifiers|KEYMOD_CTRL);
972
973   if (node->getChild("mod-alt") != 0)
974     _read_bindings(node->getChild("mod-alt"), binding_list,
975                    modifiers|KEYMOD_ALT);
976
977   if (node->getChild("mod-meta") != 0)
978     _read_bindings(node->getChild("mod-meta"), binding_list,
979                    modifiers|KEYMOD_META);
980
981   if (node->getChild("mod-super") != 0)
982     _read_bindings(node->getChild("mod-super"), binding_list,
983                    modifiers|KEYMOD_SUPER);
984 }
985
986
987 const FGInput::binding_list_t&
988 FGInput::_find_key_bindings (unsigned int k, int modifiers)
989 {
990   unsigned char kc = (unsigned char)k;
991   button &b = _key_bindings[k];
992
993                                 // Try it straight, first.
994   if (b.bindings[modifiers].size() > 0)
995     return b.bindings[modifiers];
996
997                                 // Alt-Gr is CTRL+ALT
998   else if (modifiers&(KEYMOD_CTRL|KEYMOD_ALT))
999     return _find_key_bindings(k, modifiers&~(KEYMOD_CTRL|KEYMOD_ALT));
1000
1001                                 // Try removing the control modifier
1002                                 // for control keys.
1003   else if ((modifiers&KEYMOD_CTRL) && iscntrl(kc))
1004     return _find_key_bindings(k, modifiers&~KEYMOD_CTRL);
1005
1006                                 // Try removing shift modifier 
1007                                 // for upper case or any punctuation
1008                                 // (since different keyboards will
1009                                 // shift different punctuation types)
1010   else if ((modifiers&KEYMOD_SHIFT) && (isupper(kc) || ispunct(kc)))
1011     return _find_key_bindings(k, modifiers&~KEYMOD_SHIFT);
1012
1013                                 // Try removing alt modifier for
1014                                 // high-bit characters.
1015   else if ((modifiers&KEYMOD_ALT) && k >= 128 && k < 256)
1016     return _find_key_bindings(k, modifiers&~KEYMOD_ALT);
1017
1018                                 // Give up and return the empty vector.
1019   else
1020     return b.bindings[modifiers];
1021 }
1022
1023
1024 \f
1025 ////////////////////////////////////////////////////////////////////////
1026 // Implementation of FGInput::button.
1027 ////////////////////////////////////////////////////////////////////////
1028
1029 FGInput::button::button ()
1030   : is_repeatable(false),
1031     interval_sec(0),
1032     last_dt(0),
1033     last_state(0)
1034 {
1035 }
1036
1037 FGInput::button::~button ()
1038 {
1039                                 // FIXME: memory leak
1040 //   for (int i = 0; i < KEYMOD_MAX; i++)
1041 //     for (int j = 0; i < bindings[i].size(); j++)
1042 //       delete bindings[i][j];
1043 }
1044
1045
1046 \f
1047 ////////////////////////////////////////////////////////////////////////
1048 // Implementation of FGInput::axis.
1049 ////////////////////////////////////////////////////////////////////////
1050
1051 FGInput::axis::axis ()
1052   : last_value(9999999),
1053     tolerance(0.002),
1054     low_threshold(-0.9),
1055     high_threshold(0.9),
1056     interval_sec(0),
1057     last_dt(0)
1058 {
1059 }
1060
1061 FGInput::axis::~axis ()
1062 {
1063 //   for (int i = 0; i < KEYMOD_MAX; i++)
1064 //     for (int j = 0; i < bindings[i].size(); j++)
1065 //       delete bindings[i][j];
1066 }
1067
1068
1069 \f
1070 ////////////////////////////////////////////////////////////////////////
1071 // Implementation of FGInput::joystick.
1072 ////////////////////////////////////////////////////////////////////////
1073
1074 FGInput::joystick::joystick ()
1075   : jsnum(0),
1076     js(0),
1077     naxes(0),
1078     nbuttons(0),
1079     axes(0),
1080     buttons(0)
1081 {
1082 }
1083
1084 FGInput::joystick::~joystick ()
1085 {
1086 //   delete js;
1087   delete[] axes;
1088   delete[] buttons;
1089 }
1090
1091
1092 \f
1093 ////////////////////////////////////////////////////////////////////////
1094 // Implementation of FGInput::mouse_mode
1095 ////////////////////////////////////////////////////////////////////////
1096
1097 FGInput::mouse_mode::mouse_mode ()
1098   : cursor(MOUSE_CURSOR_POINTER),
1099     constrained(false),
1100     pass_through(false),
1101     buttons(0)
1102 {
1103 }
1104
1105 FGInput::mouse_mode::~mouse_mode ()
1106 {
1107                                 // FIXME: memory leak
1108 //   for (int i = 0; i < KEYMOD_MAX; i++) {
1109 //     int j;
1110 //     for (j = 0; i < x_bindings[i].size(); j++)
1111 //       delete bindings[i][j];
1112 //     for (j = 0; j < y_bindings[i].size(); j++)
1113 //       delete bindings[i][j];
1114 //   }
1115   delete [] buttons;
1116 }
1117
1118
1119 \f
1120 ////////////////////////////////////////////////////////////////////////
1121 // Implementation of FGInput::mouse
1122 ////////////////////////////////////////////////////////////////////////
1123
1124 FGInput::mouse::mouse ()
1125   : x(-1),
1126     y(-1),
1127     save_x(-1),
1128     save_y(-1),
1129     nModes(1),
1130     current_mode(0),
1131     modes(0)
1132 {
1133 }
1134
1135 FGInput::mouse::~mouse ()
1136 {
1137   delete [] modes;
1138 }
1139
1140 ////////////////////////////////////////////////////////////////////////
1141 // Implementation of OS callbacks.
1142 ////////////////////////////////////////////////////////////////////////
1143
1144 void keyHandler(int key, int keymod, int mousex, int mousey)
1145 {
1146     if((keymod & KEYMOD_RELEASED) == 0)
1147         if(puKeyboard(key, PU_DOWN))
1148             return;
1149
1150     if(default_input)
1151         default_input->doKey(key, keymod, mousex, mousey);
1152 }
1153
1154 void mouseClickHandler(int button, int updown, int x, int y, bool mainWindow, const osgGA::GUIEventAdapter* ea)
1155 {
1156     if(default_input)
1157       default_input->doMouseClick(button, updown, x, y, mainWindow, ea);
1158 }
1159
1160 void mouseMotionHandler(int x, int y)
1161 {
1162     if (default_input != 0)
1163         default_input->doMouseMotion(x, y);
1164 }