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