]> git.mxchange.org Git - simgear.git/blob - simgear/scene/model/SGPickAnimation.cxx
Foundations of hover support in pick-callbacks.
[simgear.git] / simgear / scene / model / SGPickAnimation.cxx
1 /* -*-c++-*-
2  *
3  * Copyright (C) 2013 James Turner
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
18  * MA 02110-1301, USA.
19  *
20  */
21      
22      
23 #include <simgear/scene/model/SGPickAnimation.hxx>
24
25 #include <osg/Geode>
26 #include <osg/PolygonOffset>
27 #include <osg/PolygonMode>
28 #include <osg/Material>
29 #include <osgGA/GUIEventAdapter>
30      
31 #include <simgear/scene/util/SGPickCallback.hxx>
32 #include <simgear/scene/material/EffectGeode.hxx>
33 #include <simgear/scene/util/SGSceneUserData.hxx>
34 #include <simgear/structure/SGBinding.hxx>
35 #include <simgear/scene/util/StateAttributeFactory.hxx>
36 #include <simgear/scene/model/SGRotateTransform.hxx>
37
38 using namespace simgear;
39
40 using OpenThreads::Mutex;
41 using OpenThreads::ScopedLock;
42
43 static void readOptionalBindingList(const SGPropertyNode* aNode, SGPropertyNode* modelRoot,
44     const std::string& aName, SGBindingList& aBindings)
45 {
46     const SGPropertyNode* n = aNode->getChild(aName);
47     if (n)
48         aBindings = readBindingList(n->getChildren("binding"), modelRoot);
49     
50 }
51
52  class SGPickAnimation::PickCallback : public SGPickCallback {
53  public:
54    PickCallback(const SGPropertyNode* configNode,
55                 SGPropertyNode* modelRoot) :
56      _repeatable(configNode->getBoolValue("repeatable", false)),
57      _repeatInterval(configNode->getDoubleValue("interval-sec", 0.1))
58    {
59      std::vector<SGPropertyNode_ptr> bindings;
60
61      bindings = configNode->getChildren("button");
62      for (unsigned int i = 0; i < bindings.size(); ++i) {
63        _buttons.insert( bindings[i]->getIntValue() );
64      }
65
66      _bindingsDown = readBindingList(configNode->getChildren("binding"), modelRoot);
67      readOptionalBindingList(configNode, modelRoot, "mod-up", _bindingsUp);
68      readOptionalBindingList(configNode, modelRoot, "hovered", _hover);
69    }
70    
71    virtual bool buttonPressed(int button, const osgGA::GUIEventAdapter* ea, const Info&)
72    {
73        if (_buttons.find(button) == _buttons.end()) {
74            return false;
75        }
76        
77      fireBindingList(_bindingsDown);
78      _repeatTime = -_repeatInterval;    // anti-bobble: delay start of repeat
79      return true;
80    }
81    virtual void buttonReleased(void)
82    {
83        fireBindingList(_bindingsUp);
84    }
85    virtual void update(double dt)
86    {
87      if (!_repeatable)
88        return;
89
90      _repeatTime += dt;
91      while (_repeatInterval < _repeatTime) {
92        _repeatTime -= _repeatInterval;
93          fireBindingList(_bindingsDown);
94      }
95    }
96    
97    virtual bool hover(const osg::Vec2d& windowPos, const Info& info)
98    {
99        if (_hover.empty()) {
100            return false;
101        }
102        
103        // FIXME - make x,y available to the binding 
104        fireBindingList(_hover);
105        return true;
106    }
107  private:
108    SGBindingList _bindingsDown;
109    SGBindingList _bindingsUp;
110    SGBindingList _hover;
111    std::set<int> _buttons;
112    bool _repeatable;
113    double _repeatInterval;
114    double _repeatTime;
115  };
116
117  class VncVisitor : public osg::NodeVisitor {
118   public:
119    VncVisitor(double x, double y, int mask) :
120      osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
121      _texX(x), _texY(y), _mask(mask), _done(false)
122    {
123      SG_LOG(SG_INPUT, SG_DEBUG, "VncVisitor constructor "
124        << x << "," << y << " mask " << mask);
125    }
126
127    virtual void apply(osg::Node &node)
128    {
129      // Some nodes have state sets attached
130      touchStateSet(node.getStateSet());
131      if (!_done)
132        traverse(node);
133      if (_done) return;
134      // See whether we are a geode worth exploring
135      osg::Geode *g = dynamic_cast<osg::Geode*>(&node);
136      if (!g) return;
137      // Go find all its drawables
138      int i = g->getNumDrawables();
139      while (--i >= 0) {
140        osg::Drawable *d = g->getDrawable(i);
141        if (d) touchDrawable(*d);
142      }
143      // Out of optimism, do the same for EffectGeode
144      simgear::EffectGeode *eg = dynamic_cast<simgear::EffectGeode*>(&node);
145      if (!eg) return;
146      for (simgear::EffectGeode::DrawablesIterator di = eg->drawablesBegin();
147           di != eg->drawablesEnd(); di++) {
148        touchDrawable(**di);
149      }
150      // Now see whether the EffectGeode has an Effect
151      simgear::Effect *e = eg->getEffect();
152      if (e) {
153        touchStateSet(e->getDefaultStateSet());
154      }
155    }
156
157    inline void touchDrawable(osg::Drawable &d)
158    {
159      osg::StateSet *ss = d.getStateSet();
160      touchStateSet(ss);
161    }
162
163    void touchStateSet(osg::StateSet *ss)
164    {
165      if (!ss) return;
166      osg::StateAttribute *sa = ss->getTextureAttribute(0,
167        osg::StateAttribute::TEXTURE);
168      if (!sa) return;
169      osg::Texture *t = sa->asTexture();
170      if (!t) return;
171      osg::Image *img = t->getImage(0);
172      if (!img) return;
173      if (!_done) {
174        int pixX = _texX * img->s();
175        int pixY = _texY * img->t();
176        _done = img->sendPointerEvent(pixX, pixY, _mask);
177        SG_LOG(SG_INPUT, SG_DEBUG, "VncVisitor image said " << _done
178          << " to coord " << pixX << "," << pixY);
179      }
180    }
181
182    inline bool wasSuccessful()
183    {
184      return _done;
185    }
186
187   private:
188    double _texX, _texY;
189    int _mask;
190    bool _done;
191  };
192
193
194  class SGPickAnimation::VncCallback : public SGPickCallback {
195  public:
196    VncCallback(const SGPropertyNode* configNode,
197                 SGPropertyNode* modelRoot,
198                 osg::Group *node)
199        : _node(node)
200    {
201      SG_LOG(SG_INPUT, SG_DEBUG, "Configuring VNC callback");
202      const char *cornernames[3] = {"top-left", "top-right", "bottom-left"};
203      SGVec3d *cornercoords[3] = {&_topLeft, &_toRight, &_toDown};
204      for (int c =0; c < 3; c++) {
205        const SGPropertyNode* cornerNode = configNode->getChild(cornernames[c]);
206        *cornercoords[c] = SGVec3d(
207          cornerNode->getDoubleValue("x"),
208          cornerNode->getDoubleValue("y"),
209          cornerNode->getDoubleValue("z"));
210      }
211      _toRight -= _topLeft;
212      _toDown -= _topLeft;
213      _squaredRight = dot(_toRight, _toRight);
214      _squaredDown = dot(_toDown, _toDown);
215    }
216
217    virtual bool buttonPressed(int button, const osgGA::GUIEventAdapter* ea, const Info& info)
218    {
219      SGVec3d loc(info.local);
220      SG_LOG(SG_INPUT, SG_DEBUG, "VNC pressed " << button << ": " << loc);
221      loc -= _topLeft;
222      _x = dot(loc, _toRight) / _squaredRight;
223      _y = dot(loc, _toDown) / _squaredDown;
224      if (_x<0) _x = 0; else if (_x > 1) _x = 1;
225      if (_y<0) _y = 0; else if (_y > 1) _y = 1;
226      VncVisitor vv(_x, _y, 1 << button);
227      _node->accept(vv);
228      return vv.wasSuccessful();
229
230    }
231    virtual void buttonReleased(void)
232    {
233      SG_LOG(SG_INPUT, SG_DEBUG, "VNC release");
234      VncVisitor vv(_x, _y, 0);
235      _node->accept(vv);
236    }
237    virtual void update(double dt)
238    {
239    }
240  private:
241    double _x, _y;
242    osg::ref_ptr<osg::Group> _node;
243    SGVec3d _topLeft, _toRight, _toDown;
244    double _squaredRight, _squaredDown;
245  };
246
247  SGPickAnimation::SGPickAnimation(const SGPropertyNode* configNode,
248                                   SGPropertyNode* modelRoot) :
249    SGAnimation(configNode, modelRoot)
250  {
251  }
252
253  namespace
254  {
255  OpenThreads::Mutex colorModeUniformMutex;
256  osg::ref_ptr<osg::Uniform> colorModeUniform;
257  }
258
259
260 void 
261 SGPickAnimation::innerSetupPickGroup(osg::Group* commonGroup, osg::Group& parent)
262 {
263     // Contains the normal geometry that is interactive
264     osg::ref_ptr<osg::Group> normalGroup = new osg::Group;
265     normalGroup->setName("pick normal group");
266     normalGroup->addChild(commonGroup);
267     
268     // Used to render the geometry with just yellow edges
269     osg::Group* highlightGroup = new osg::Group;
270     highlightGroup->setName("pick highlight group");
271     highlightGroup->setNodeMask(simgear::PICK_BIT);
272     highlightGroup->addChild(commonGroup);
273     
274     // prepare a state set that paints the edges of this object yellow
275     // The material and texture attributes are set with
276     // OVERRIDE|PROTECTED in case there is a material animation on a
277     // higher node in the scene graph, which would have its material
278     // attribute set with OVERRIDE.
279     osg::StateSet* stateSet = highlightGroup->getOrCreateStateSet();
280     osg::Texture2D* white = StateAttributeFactory::instance()->getWhiteTexture();
281     stateSet->setTextureAttributeAndModes(0, white,
282                                           (osg::StateAttribute::ON
283                                            | osg::StateAttribute::OVERRIDE
284                                            | osg::StateAttribute::PROTECTED));
285     osg::PolygonOffset* polygonOffset = new osg::PolygonOffset;
286     polygonOffset->setFactor(-1);
287     polygonOffset->setUnits(-1);
288     stateSet->setAttribute(polygonOffset, osg::StateAttribute::OVERRIDE);
289     stateSet->setMode(GL_POLYGON_OFFSET_LINE,
290                       osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
291     osg::PolygonMode* polygonMode = new osg::PolygonMode;
292     polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
293                          osg::PolygonMode::LINE);
294     stateSet->setAttribute(polygonMode, osg::StateAttribute::OVERRIDE);
295     osg::Material* material = new osg::Material;
296     material->setColorMode(osg::Material::OFF);
297     material->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4f(0, 0, 0, 1));
298     // XXX Alpha < 1.0 in the diffuse material value is a signal to the
299     // default shader to take the alpha value from the material value
300     // and not the glColor. In many cases the pick animation geometry is
301     // transparent, so the outline would not be visible without this hack.
302     material->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4f(0, 0, 0, .95));
303     material->setEmission(osg::Material::FRONT_AND_BACK, osg::Vec4f(1, 1, 0, 1));
304     material->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4f(0, 0, 0, 0));
305     stateSet->setAttribute(
306                            material, osg::StateAttribute::OVERRIDE | osg::StateAttribute::PROTECTED);
307     // The default shader has a colorMode uniform that mimics the
308     // behavior of Material color mode.
309     osg::Uniform* cmUniform = 0;
310     {
311         ScopedLock<Mutex> lock(colorModeUniformMutex);
312         if (!colorModeUniform.valid()) {
313             colorModeUniform = new osg::Uniform(osg::Uniform::INT, "colorMode");
314             colorModeUniform->set(0); // MODE_OFF
315             colorModeUniform->setDataVariance(osg::Object::STATIC);
316         }
317         cmUniform = colorModeUniform.get();
318     }
319     stateSet->addUniform(cmUniform,
320                          osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON);
321     
322     // Only add normal geometry if configured
323     if (getConfig()->getBoolValue("visible", true))
324         parent.addChild(normalGroup.get());
325     parent.addChild(highlightGroup);
326 }
327
328  osg::Group*
329  SGPickAnimation::createAnimationGroup(osg::Group& parent)
330  {
331      osg::Group* commonGroup = new osg::Group;
332      innerSetupPickGroup(commonGroup, parent);
333      SGSceneUserData* ud = SGSceneUserData::getOrCreateSceneUserData(commonGroup);
334
335    // add actions that become macro and command invocations
336    std::vector<SGPropertyNode_ptr> actions;
337    actions = getConfig()->getChildren("action");
338    for (unsigned int i = 0; i < actions.size(); ++i)
339      ud->addPickCallback(new PickCallback(actions[i], getModelRoot()));
340    // Look for the VNC sessions that want raw mouse input
341    actions = getConfig()->getChildren("vncaction");
342    for (unsigned int i = 0; i < actions.size(); ++i)
343      ud->addPickCallback(new VncCallback(actions[i], getModelRoot(),
344        &parent));
345
346    return commonGroup;
347 }
348
349 ///////////////////////////////////////////////////////////////////////////
350
351 // insert count copies of binding list A, into the output list.
352 // effectively makes the output list fire binding A multiple times
353 // in sequence
354 static void repeatBindings(const SGBindingList& a, SGBindingList& out, int count)
355 {
356     out.clear();
357     for (int i=0; i<count; ++i) {
358         out.insert(out.end(), a.begin(), a.end());
359     }
360 }
361
362 static bool static_knobMouseWheelAlternateDirection = false;
363
364 class SGKnobAnimation::KnobPickCallback : public SGPickCallback {
365 public:
366     KnobPickCallback(const SGPropertyNode* configNode,
367                  SGPropertyNode* modelRoot) :
368         _direction(DIRECTION_NONE),
369         _repeatInterval(configNode->getDoubleValue("interval-sec", 0.1)),
370         _stickyShifted(false)
371     {
372         readOptionalBindingList(configNode, modelRoot, "action", _action);
373         readOptionalBindingList(configNode, modelRoot, "cw", _bindingsCW);
374         readOptionalBindingList(configNode, modelRoot, "ccw", _bindingsCCW);
375         
376         readOptionalBindingList(configNode, modelRoot, "release", _releaseAction);
377         readOptionalBindingList(configNode, modelRoot, "hovered", _hover);
378         
379         if (configNode->hasChild("shift-action") || configNode->hasChild("shift-cw") ||
380             configNode->hasChild("shift-ccw"))
381         {
382         // explicit shifted behaviour - just do exactly what was provided
383             readOptionalBindingList(configNode, modelRoot, "shift-action", _shiftedAction);
384             readOptionalBindingList(configNode, modelRoot, "shift-cw", _shiftedCW);
385             readOptionalBindingList(configNode, modelRoot, "shift-ccw", _shiftedCCW);
386         } else {
387             // default shifted behaviour - repeat normal bindings N times.
388             int shiftRepeat = configNode->getIntValue("shift-repeat", 10);
389             repeatBindings(_action, _shiftedAction, shiftRepeat);
390             repeatBindings(_bindingsCW, _shiftedCW, shiftRepeat);
391             repeatBindings(_bindingsCCW, _shiftedCCW, shiftRepeat);
392         } // of default shifted behaviour
393     }
394     
395     virtual bool buttonPressed(int button, const osgGA::GUIEventAdapter* ea, const Info&)
396     {
397         _stickyShifted = ea->getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_SHIFT;
398         
399         // the 'be nice to Mac / laptop' users option; alt-clicking spins the
400         // opposite direction. Should make this configurable
401         if ((button == 0) && (ea->getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_ALT)) {
402             button = 1;
403         }
404         
405         int increaseMouseWheel = static_knobMouseWheelAlternateDirection ? 3 : 4;
406         int decreaseMouseWheel = static_knobMouseWheelAlternateDirection ? 4 : 3;
407             
408         _direction = DIRECTION_NONE;
409         if ((button == 0) || (button == increaseMouseWheel)) {
410             _direction = DIRECTION_CLOCKWISE;
411         } else if ((button == 1) || (button == decreaseMouseWheel)) {
412             _direction = DIRECTION_ANTICLOCKWISE;
413         } else {
414             return false;
415         }
416         
417         _repeatTime = -_repeatInterval;    // anti-bobble: delay start of repeat
418         fire(_stickyShifted);
419         return true;
420     }
421     
422     virtual void buttonReleased(void)
423     {
424         fireBindingList(_releaseAction);
425     }
426     
427     virtual void update(double dt)
428     {
429         _repeatTime += dt;
430         while (_repeatInterval < _repeatTime) {
431             _repeatTime -= _repeatInterval;
432             fire(_stickyShifted);
433         } // of repeat iteration
434     }
435
436     virtual bool hover(const osg::Vec2d& windowPos, const Info& info)
437     {
438         if (_hover.empty()) {
439             return false;
440         }
441        
442         // FIXME - make x,y available to the binding 
443         fireBindingList(_hover);
444         return true;
445     }
446 private:
447     void fire(bool isShifted)
448     {
449         const SGBindingList& act(isShifted ? _shiftedAction : _action);
450         const SGBindingList& cw(isShifted ? _shiftedCW : _bindingsCW);
451         const SGBindingList& ccw(isShifted ? _shiftedCCW : _bindingsCCW);
452         
453         switch (_direction) {
454             case DIRECTION_CLOCKWISE:
455                 fireBindingListWithOffset(act,  1, 1);
456                 fireBindingList(cw);
457                 break;
458             case DIRECTION_ANTICLOCKWISE:
459                 fireBindingListWithOffset(act, -1, 1);
460                 fireBindingList(ccw);
461                 break;
462             default: break;
463         }
464     }
465     
466     SGBindingList _action, _shiftedAction;
467     SGBindingList _releaseAction;
468     SGBindingList _bindingsCW, _shiftedCW,
469         _bindingsCCW, _shiftedCCW;
470     SGBindingList _hover;
471     
472     enum Direction
473     {
474         DIRECTION_NONE,
475         DIRECTION_CLOCKWISE,
476         DIRECTION_ANTICLOCKWISE
477     };
478     
479     Direction _direction;
480     double _repeatInterval;
481     double _repeatTime;
482     
483     // FIXME - would be better to pass the current modifier state
484     // into update(), but for now let's make it sticky
485     bool _stickyShifted;
486 };
487
488 class SGKnobAnimation::UpdateCallback : public osg::NodeCallback {
489 public:
490     UpdateCallback(SGExpressiond const* animationValue) :
491         _animationValue(animationValue)
492     {
493         setName("SGKnobAnimation::UpdateCallback");
494     }
495     virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
496     {
497         SGRotateTransform* transform = static_cast<SGRotateTransform*>(node);
498         transform->setAngleDeg(_animationValue->getValue());
499         traverse(node, nv);
500     }
501     
502 private:
503     SGSharedPtr<SGExpressiond const> _animationValue;
504 };
505
506
507 SGKnobAnimation::SGKnobAnimation(const SGPropertyNode* configNode,
508                                  SGPropertyNode* modelRoot) :
509     SGPickAnimation(configNode, modelRoot)
510 {
511     SGSharedPtr<SGExpressiond> value = read_value(configNode, modelRoot, "-deg",
512                                                   -SGLimitsd::max(), SGLimitsd::max());
513     _animationValue = value->simplify();
514     
515     
516     readRotationCenterAndAxis(configNode, _center, _axis);
517 }
518
519
520 osg::Group*
521 SGKnobAnimation::createAnimationGroup(osg::Group& parent)
522 {
523     SGRotateTransform* transform = new SGRotateTransform();
524     innerSetupPickGroup(transform, parent);
525     
526     UpdateCallback* uc = new UpdateCallback(_animationValue);
527     transform->setUpdateCallback(uc);
528     transform->setCenter(_center);
529     transform->setAxis(_axis);
530         
531     SGSceneUserData* ud = SGSceneUserData::getOrCreateSceneUserData(transform);
532     ud->setPickCallback(new KnobPickCallback(getConfig(), getModelRoot()));
533     
534     return transform;
535 }
536
537 void SGKnobAnimation::setAlternateMouseWheelDirection(bool aToggle)
538 {
539     static_knobMouseWheelAlternateDirection = aToggle;
540 }
541