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