]> git.mxchange.org Git - simgear.git/blob - simgear/structure/SGExpression.hxx
Boolean uniforms are now updatable by properties
[simgear.git] / simgear / structure / SGExpression.hxx
1 /* -*-c++-*-
2  *
3  * Copyright (C) 2006-2007 Mathias Froehlich 
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 #ifndef _SG_EXPRESSION_HXX
23 #define _SG_EXPRESSION_HXX 1
24
25 #include <string>
26 #include <vector>
27
28 #include <simgear/props/condition.hxx>
29 #include <simgear/props/props.hxx>
30 #include <simgear/math/interpolater.hxx>
31 #include <simgear/math/SGMath.hxx>
32 #include <simgear/scene/model/persparam.hxx>
33 #include <simgear/structure/exception.hxx>
34 #include <simgear/structure/Singleton.hxx>
35
36 /// Expression tree implementation.
37
38 namespace simgear
39 {
40   namespace expression
41   {
42     enum Type {
43       BOOL = 0,
44       INT,
45       FLOAT,
46       DOUBLE
47     };
48     template<typename T> struct TypeTraits;
49     template<> struct TypeTraits<bool> {
50       static const Type typeTag = BOOL;
51     };
52     template<> struct TypeTraits<int> {
53       static const Type typeTag = INT;
54     };
55     template<> struct TypeTraits<float> {
56       static const Type typeTag = FLOAT;
57     };
58     template<> struct TypeTraits<double> {
59       static const Type typeTag = DOUBLE;
60     };
61
62     struct Value
63     {
64       Type typeTag;
65       union {
66         bool boolVal;
67         int intVal;
68         float floatVal;
69         double doubleVal;
70       } val;
71
72       Value() : typeTag(DOUBLE)
73       {
74         val.doubleVal = 0.0;
75       }
76
77       Value(bool val_) : typeTag(BOOL)
78       {
79         val.boolVal = val_;
80       }
81
82       Value(int val_) : typeTag(INT)
83       {
84         val.intVal = val_;
85       }
86
87       Value(float val_) : typeTag(FLOAT)
88       {
89         val.floatVal = val_;
90       }
91
92       Value(double val_) : typeTag(DOUBLE)
93       {
94         val.doubleVal = val_;
95       }
96
97     };
98
99     class Binding;
100   }
101
102   class Expression : public SGReferenced
103   {
104   public:
105     virtual ~Expression() {}
106     virtual expression::Type getType() const = 0;
107   };
108
109   const expression::Value eval(const Expression* exp,
110                                const expression::Binding* binding = 0);
111
112 }
113
114 template<typename T>
115 class SGExpression : public simgear::Expression {
116 public:
117   virtual ~SGExpression() {}
118   typedef T result_type;
119   typedef T operand_type;
120   virtual void eval(T&, const simgear::expression::Binding*) const = 0;
121
122   T getValue(const simgear::expression::Binding* binding = 0) const
123   { T value; eval(value, binding); return value; }
124
125   double getDoubleValue(const simgear::expression::Binding* binding = 0) const
126   { T value; eval(value, binding); return value; }
127
128   virtual bool isConst() const { return false; }
129   virtual SGExpression* simplify();
130   virtual simgear::expression::Type getType() const
131   {
132     return simgear::expression::TypeTraits<T>::typeTag;
133   }
134   virtual simgear::expression::Type getOperandType() const
135   {
136     return simgear::expression::TypeTraits<T>::typeTag;
137   }
138 };
139
140 /// Constant value expression
141 template<typename T>
142 class SGConstExpression : public SGExpression<T> {
143 public:
144   SGConstExpression(const T& value = T()) : _value(value)
145   { }
146   void setValue(const T& value)
147   { _value = value; }
148   const T& getValue(const simgear::expression::Binding* binding = 0) const
149   { return _value; }
150   virtual void eval(T& value, const simgear::expression::Binding*) const
151   { value = _value; }
152   virtual bool isConst() const { return true; }
153 private:
154   T _value;
155 };
156
157 template<typename T>
158 SGExpression<T>*
159 SGExpression<T>::simplify()
160 {
161   if (isConst())
162     return new SGConstExpression<T>(getValue());
163   return this;
164 }
165
166 template<typename T>
167 class SGUnaryExpression : public SGExpression<T> {
168 public:
169   const SGExpression<T>* getOperand() const
170   { return _expression; }
171   SGExpression<T>* getOperand()
172   { return _expression; }
173   void setOperand(SGExpression<T>* expression)
174   {
175     if (!expression)
176       expression = new SGConstExpression<T>(T());
177     _expression = expression;
178   }
179   virtual bool isConst() const
180   { return getOperand()->isConst(); }
181   virtual SGExpression<T>* simplify()
182   {
183     _expression = _expression->simplify();
184     return SGExpression<T>::simplify();
185   }
186
187 protected:
188   SGUnaryExpression(SGExpression<T>* expression = 0)
189   { setOperand(expression); }
190
191 private:
192   SGSharedPtr<SGExpression<T> > _expression;
193 };
194
195 template<typename T>
196 class SGBinaryExpression : public SGExpression<T> {
197 public:
198   const SGExpression<T>* getOperand(unsigned i) const
199   { return _expressions[i]; }
200   SGExpression<T>* getOperand(unsigned i)
201   { return _expressions[i]; }
202   void setOperand(unsigned i, SGExpression<T>* expression)
203   {
204     if (!expression)
205       expression = new SGConstExpression<T>(T());
206     if (2 <= i)
207       i = 0;
208     _expressions[i] = expression;
209   }
210
211   virtual bool isConst() const
212   { return getOperand(0)->isConst() && getOperand(1)->isConst(); }
213   virtual SGExpression<T>* simplify()
214   {
215     _expressions[0] = _expressions[0]->simplify();
216     _expressions[1] = _expressions[1]->simplify();
217     return SGExpression<T>::simplify();
218   }
219
220 protected:
221   SGBinaryExpression(SGExpression<T>* expr0, SGExpression<T>* expr1)
222   { setOperand(0, expr0); setOperand(1, expr1); }
223   
224 private:
225   SGSharedPtr<SGExpression<T> > _expressions[2];
226 };
227
228 template<typename T>
229 class SGNaryExpression : public SGExpression<T> {
230 public:
231   unsigned getNumOperands() const
232   { return _expressions.size(); }
233   const SGExpression<T>* getOperand(unsigned i) const
234   { return _expressions[i]; }
235   SGExpression<T>* getOperand(unsigned i)
236   { return _expressions[i]; }
237   unsigned addOperand(SGExpression<T>* expression)
238   {
239     if (!expression)
240       return ~unsigned(0);
241     _expressions.push_back(expression);
242     return _expressions.size() - 1;
243   }
244
245   template<typename Iter>
246   void addOperands(Iter begin, Iter end)
247   {
248     for (Iter iter = begin; iter != end; ++iter)
249       {
250         addOperand(static_cast< ::SGExpression<T>*>(*iter));
251       }
252   }
253
254   virtual bool isConst() const
255   {
256     for (unsigned i = 0; i < _expressions.size(); ++i)
257       if (!_expressions[i]->isConst())
258         return false;
259     return true;
260   }
261   virtual SGExpression<T>* simplify()
262   {
263     for (unsigned i = 0; i < _expressions.size(); ++i)
264       _expressions[i] = _expressions[i]->simplify();
265     return SGExpression<T>::simplify();
266   }
267
268 protected:
269   SGNaryExpression()
270   { }
271   SGNaryExpression(SGExpression<T>* expr0, SGExpression<T>* expr1)
272   { addOperand(expr0); addOperand(expr1); }
273   
274 private:
275   std::vector<SGSharedPtr<SGExpression<T> > > _expressions;
276 };
277
278
279
280
281 template<typename T>
282 class SGPropertyExpression : public SGExpression<T> {
283 public:
284   SGPropertyExpression(const SGPropertyNode* prop) : _prop(prop)
285   { }
286   void setPropertyNode(const SGPropertyNode* prop)
287   { _prop = prop; }
288   virtual void eval(T& value, const simgear::expression::Binding*) const
289   { doEval(value); }
290 private:
291   void doEval(float& value) const
292   { if (_prop) value = _prop->getFloatValue(); }
293   void doEval(double& value) const
294   { if (_prop) value = _prop->getDoubleValue(); }
295   void doEval(int& value) const
296   { if (_prop) value = _prop->getIntValue(); }
297   void doEval(long& value) const
298   { if (_prop) value = _prop->getLongValue(); }
299   void doEval(bool& value) const
300   { if (_prop) value = _prop->getBoolValue(); }
301   SGSharedPtr<const SGPropertyNode> _prop;
302 };
303
304 template<typename T>
305 class SGAbsExpression : public SGUnaryExpression<T> {
306 public:
307   SGAbsExpression(SGExpression<T>* expr = 0)
308     : SGUnaryExpression<T>(expr)
309   { }
310
311   virtual void eval(T& value, const simgear::expression::Binding* b) const
312   { value = getOperand()->getValue(b); if (value <= 0) value = -value; }
313
314   using SGUnaryExpression<T>::getOperand;
315 };
316
317 template<typename T>
318 class SGACosExpression : public SGUnaryExpression<T> {
319 public:
320   SGACosExpression(SGExpression<T>* expr = 0)
321     : SGUnaryExpression<T>(expr)
322   { }
323
324   virtual void eval(T& value, const simgear::expression::Binding* b) const
325   { value = acos((double)SGMisc<T>::clip(getOperand()->getValue(b), -1, 1)); }
326
327   using SGUnaryExpression<T>::getOperand;
328 };
329
330 template<typename T>
331 class SGASinExpression : public SGUnaryExpression<T> {
332 public:
333   SGASinExpression(SGExpression<T>* expr = 0)
334     : SGUnaryExpression<T>(expr)
335   { }
336
337   virtual void eval(T& value, const simgear::expression::Binding* b) const
338   { value = asin((double)SGMisc<T>::clip(getOperand()->getValue(b), -1, 1)); }
339
340   using SGUnaryExpression<T>::getOperand;
341 };
342
343 template<typename T>
344 class SGATanExpression : public SGUnaryExpression<T> {
345 public:
346   SGATanExpression(SGExpression<T>* expr = 0)
347     : SGUnaryExpression<T>(expr)
348   { }
349
350   virtual void eval(T& value, const simgear::expression::Binding* b) const
351   { value = atan(getOperand()->getDoubleValue(b)); }
352
353   using SGUnaryExpression<T>::getOperand;
354 };
355
356 template<typename T>
357 class SGCeilExpression : public SGUnaryExpression<T> {
358 public:
359   SGCeilExpression(SGExpression<T>* expr = 0)
360     : SGUnaryExpression<T>(expr)
361   { }
362
363   virtual void eval(T& value, const simgear::expression::Binding* b) const
364   { value = ceil(getOperand()->getDoubleValue(b)); }
365
366   using SGUnaryExpression<T>::getOperand;
367 };
368
369 template<typename T>
370 class SGCosExpression : public SGUnaryExpression<T> {
371 public:
372   SGCosExpression(SGExpression<T>* expr = 0)
373     : SGUnaryExpression<T>(expr)
374   { }
375
376   virtual void eval(T& value, const simgear::expression::Binding* b) const
377   { value = cos(getOperand()->getDoubleValue(b)); }
378
379   using SGUnaryExpression<T>::getOperand;
380 };
381
382 template<typename T>
383 class SGCoshExpression : public SGUnaryExpression<T> {
384 public:
385   SGCoshExpression(SGExpression<T>* expr = 0)
386     : SGUnaryExpression<T>(expr)
387   { }
388
389   virtual void eval(T& value, const simgear::expression::Binding* b) const
390   { value = cosh(getOperand()->getDoubleValue(b)); }
391
392   using SGUnaryExpression<T>::getOperand;
393 };
394
395 template<typename T>
396 class SGExpExpression : public SGUnaryExpression<T> {
397 public:
398   SGExpExpression(SGExpression<T>* expr = 0)
399     : SGUnaryExpression<T>(expr)
400   { }
401
402   virtual void eval(T& value, const simgear::expression::Binding* b) const
403   { value = exp(getOperand()->getDoubleValue(b)); }
404
405   using SGUnaryExpression<T>::getOperand;
406 };
407
408 template<typename T>
409 class SGFloorExpression : public SGUnaryExpression<T> {
410 public:
411   SGFloorExpression(SGExpression<T>* expr = 0)
412     : SGUnaryExpression<T>(expr)
413   { }
414
415   virtual void eval(T& value, const simgear::expression::Binding* b) const
416   { value = floor(getOperand()->getDoubleValue(b)); }
417
418   using SGUnaryExpression<T>::getOperand;
419 };
420
421 template<typename T>
422 class SGLogExpression : public SGUnaryExpression<T> {
423 public:
424   SGLogExpression(SGExpression<T>* expr = 0)
425     : SGUnaryExpression<T>(expr)
426   { }
427
428   virtual void eval(T& value, const simgear::expression::Binding* b) const
429   { value = log(getOperand()->getDoubleValue(b)); }
430
431   using SGUnaryExpression<T>::getOperand;
432 };
433
434 template<typename T>
435 class SGLog10Expression : public SGUnaryExpression<T> {
436 public:
437   SGLog10Expression(SGExpression<T>* expr = 0)
438     : SGUnaryExpression<T>(expr)
439   { }
440
441   virtual void eval(T& value, const simgear::expression::Binding* b) const
442   { value = log10(getOperand()->getDoubleValue(b)); }
443
444   using SGUnaryExpression<T>::getOperand;
445 };
446
447 template<typename T>
448 class SGSinExpression : public SGUnaryExpression<T> {
449 public:
450   SGSinExpression(SGExpression<T>* expr = 0)
451     : SGUnaryExpression<T>(expr)
452   { }
453
454   virtual void eval(T& value, const simgear::expression::Binding* b) const
455   { value = sin(getOperand()->getDoubleValue(b)); }
456
457   using SGUnaryExpression<T>::getOperand;
458 };
459
460 template<typename T>
461 class SGSinhExpression : public SGUnaryExpression<T> {
462 public:
463   SGSinhExpression(SGExpression<T>* expr = 0)
464     : SGUnaryExpression<T>(expr)
465   { }
466
467   virtual void eval(T& value, const simgear::expression::Binding* b) const
468   { value = sinh(getOperand()->getDoubleValue(b)); }
469
470   using SGUnaryExpression<T>::getOperand;
471 };
472
473 template<typename T>
474 class SGSqrExpression : public SGUnaryExpression<T> {
475 public:
476   SGSqrExpression(SGExpression<T>* expr = 0)
477     : SGUnaryExpression<T>(expr)
478   { }
479
480   virtual void eval(T& value, const simgear::expression::Binding* b) const
481   { value = getOperand()->getValue(b); value = value*value; }
482
483   using SGUnaryExpression<T>::getOperand;
484 };
485
486 template<typename T>
487 class SGSqrtExpression : public SGUnaryExpression<T> {
488 public:
489   SGSqrtExpression(SGExpression<T>* expr = 0)
490     : SGUnaryExpression<T>(expr)
491   { }
492
493   virtual void eval(T& value, const simgear::expression::Binding* b) const
494   { value = sqrt(getOperand()->getDoubleValue(b)); }
495
496   using SGUnaryExpression<T>::getOperand;
497 };
498
499 template<typename T>
500 class SGTanExpression : public SGUnaryExpression<T> {
501 public:
502   SGTanExpression(SGExpression<T>* expr = 0)
503     : SGUnaryExpression<T>(expr)
504   { }
505
506   virtual void eval(T& value, const simgear::expression::Binding* b) const
507   { value = tan(getOperand()->getDoubleValue(b)); }
508
509   using SGUnaryExpression<T>::getOperand;
510 };
511
512 template<typename T>
513 class SGTanhExpression : public SGUnaryExpression<T> {
514 public:
515   SGTanhExpression(SGExpression<T>* expr = 0)
516     : SGUnaryExpression<T>(expr)
517   { }
518
519   virtual void eval(T& value, const simgear::expression::Binding* b) const
520   { value = tanh(getOperand()->getDoubleValue(b)); }
521
522   using SGUnaryExpression<T>::getOperand;
523 };
524
525 template<typename T>
526 class SGScaleExpression : public SGUnaryExpression<T> {
527 public:
528   SGScaleExpression(SGExpression<T>* expr = 0, const T& scale = T(1))
529     : SGUnaryExpression<T>(expr), _scale(scale)
530   { }
531   void setScale(const T& scale)
532   { _scale = scale; }
533   const T& getScale() const
534   { return _scale; }
535
536   virtual void eval(T& value, const simgear::expression::Binding* b) const
537   { value = _scale * getOperand()->getValue(b); }
538
539   virtual SGExpression<T>* simplify()
540   {
541     if (_scale == 1)
542       return getOperand()->simplify();
543     return SGUnaryExpression<T>::simplify();
544   }
545
546   using SGUnaryExpression<T>::getOperand;
547 private:
548   T _scale;
549 };
550
551 template<typename T>
552 class SGBiasExpression : public SGUnaryExpression<T> {
553 public:
554   SGBiasExpression(SGExpression<T>* expr = 0, const T& bias = T(0))
555     : SGUnaryExpression<T>(expr), _bias(bias)
556   { }
557
558   void setBias(const T& bias)
559   { _bias = bias; }
560   const T& getBias() const
561   { return _bias; }
562
563   virtual void eval(T& value, const simgear::expression::Binding* b) const
564   { value = _bias + getOperand()->getValue(b); }
565
566   virtual SGExpression<T>* simplify()
567   {
568     if (_bias == 0)
569       return getOperand()->simplify();
570     return SGUnaryExpression<T>::simplify();
571   }
572
573   using SGUnaryExpression<T>::getOperand;
574 private:
575   T _bias;
576 };
577
578 template<typename T>
579 class SGInterpTableExpression : public SGUnaryExpression<T> {
580 public:
581   SGInterpTableExpression(SGExpression<T>* expr,
582                           const SGInterpTable* interpTable) :
583     SGUnaryExpression<T>(expr),
584     _interpTable(interpTable)
585   { }
586
587   virtual void eval(T& value, const simgear::expression::Binding* b) const
588   {
589     if (_interpTable)
590       value = _interpTable->interpolate(getOperand()->getValue(b));
591   }
592
593   using SGUnaryExpression<T>::getOperand;
594 private:
595   SGSharedPtr<SGInterpTable const> _interpTable;
596 };
597
598 template<typename T>
599 class SGClipExpression : public SGUnaryExpression<T> {
600 public:
601   SGClipExpression(SGExpression<T>* expr)
602     : SGUnaryExpression<T>(expr),
603       _clipMin(SGMisc<T>::min(-SGLimits<T>::max(), SGLimits<T>::min())),
604       _clipMax(SGLimits<T>::max())
605   { }
606   SGClipExpression(SGExpression<T>* expr,
607                    const T& clipMin, const T& clipMax)
608     : SGUnaryExpression<T>(expr),
609       _clipMin(clipMin),
610       _clipMax(clipMax)
611   { }
612
613   void setClipMin(const T& clipMin)
614   { _clipMin = clipMin; }
615   const T& getClipMin() const
616   { return _clipMin; }
617
618   void setClipMax(const T& clipMax)
619   { _clipMax = clipMax; }
620   const T& getClipMax() const
621   { return _clipMax; }
622
623   virtual void eval(T& value, const simgear::expression::Binding* b) const
624   {
625     value = SGMisc<T>::clip(getOperand()->getValue(b), _clipMin, _clipMax);
626   }
627
628   virtual SGExpression<T>* simplify()
629   {
630     if (_clipMin <= SGMisc<T>::min(-SGLimits<T>::max(), SGLimits<T>::min()) &&
631         _clipMax >= SGLimits<T>::max())
632       return getOperand()->simplify();
633     return SGUnaryExpression<T>::simplify();
634   }
635
636   using SGUnaryExpression<T>::getOperand;
637 private:
638   T _clipMin;
639   T _clipMax;
640 };
641
642 template<typename T>
643 class SGStepExpression : public SGUnaryExpression<T> {
644 public:
645   SGStepExpression(SGExpression<T>* expr = 0,
646                    const T& step = T(1), const T& scroll = T(0))
647     : SGUnaryExpression<T>(expr), _step(step), _scroll(scroll)
648   { }
649
650   void setStep(const T& step)
651   { _step = step; }
652   const T& getStep() const
653   { return _step; }
654
655   void setScroll(const T& scroll)
656   { _scroll = scroll; }
657   const T& getScroll() const
658   { return _scroll; }
659
660   virtual void eval(T& value, const simgear::expression::Binding* b) const
661   { value = apply_mods(getOperand()->getValue(b)); }
662
663   using SGUnaryExpression<T>::getOperand;
664
665 private:
666   T apply_mods(T property) const
667   {
668     if( _step <= SGLimits<T>::min() ) return property;
669
670     // apply stepping of input value
671     T modprop = floor(property/_step)*_step;
672
673     // calculate scroll amount (for odometer like movement)
674     T remainder = property <= SGLimits<T>::min() ? -fmod(property,_step) : (_step - fmod(property,_step));
675     if( remainder > SGLimits<T>::min() && remainder < _scroll )
676       modprop += (_scroll - remainder) / _scroll * _step;
677
678     return modprop;
679   }
680
681   T _step;
682   T _scroll;
683 };
684
685 template<typename T>
686 class SGEnableExpression : public SGUnaryExpression<T> {
687 public:
688   SGEnableExpression(SGExpression<T>* expr = 0,
689                      SGCondition* enable = 0,
690                      const T& disabledValue = T(0))
691     : SGUnaryExpression<T>(expr),
692       _enable(enable),
693       _disabledValue(disabledValue)
694   { }
695
696   const T& getDisabledValue() const
697   { return _disabledValue; }
698   void setDisabledValue(const T& disabledValue)
699   { _disabledValue = disabledValue; }
700
701   virtual void eval(T& value, const simgear::expression::Binding* b) const
702   {
703     if (_enable->test())
704       value = getOperand()->getValue(b);
705     else
706       value = _disabledValue;
707   }
708
709   virtual SGExpression<T>* simplify()
710   {
711     if (!_enable)
712       return getOperand()->simplify();
713     return SGUnaryExpression<T>::simplify();
714   }
715
716   using SGUnaryExpression<T>::getOperand;
717 private:
718   SGSharedPtr<SGCondition> _enable;
719   T _disabledValue;
720 };
721
722 template<typename T>
723 class SGAtan2Expression : public SGBinaryExpression<T> {
724 public:
725   SGAtan2Expression(SGExpression<T>* expr0, SGExpression<T>* expr1)
726     : SGBinaryExpression<T>(expr0, expr1)
727   { }
728   virtual void eval(T& value, const simgear::expression::Binding* b) const
729   { value = atan2(getOperand(0)->getDoubleValue(b), getOperand(1)->getDoubleValue(b)); }
730   using SGBinaryExpression<T>::getOperand;
731 };
732
733 template<typename T>
734 class SGDivExpression : public SGBinaryExpression<T> {
735 public:
736   SGDivExpression(SGExpression<T>* expr0, SGExpression<T>* expr1)
737     : SGBinaryExpression<T>(expr0, expr1)
738   { }
739   virtual void eval(T& value, const simgear::expression::Binding* b) const
740   { value = getOperand(0)->getValue(b) / getOperand(1)->getValue(b); }
741   using SGBinaryExpression<T>::getOperand;
742 };
743
744 template<typename T>
745 class SGModExpression : public SGBinaryExpression<T> {
746 public:
747   SGModExpression(SGExpression<T>* expr0, SGExpression<T>* expr1)
748     : SGBinaryExpression<T>(expr0, expr1)
749   { }
750   virtual void eval(T& value, const simgear::expression::Binding* b) const
751   { value = mod(getOperand(0)->getValue(b), getOperand(1)->getValue(b)); }
752   using SGBinaryExpression<T>::getOperand;
753 private:
754   int mod(const int& v0, const int& v1) const
755   { return v0 % v1; }
756   float mod(const float& v0, const float& v1) const
757   { return fmod(v0, v1); }
758   double mod(const double& v0, const double& v1) const
759   { return fmod(v0, v1); }
760 };
761
762 template<typename T>
763 class SGPowExpression : public SGBinaryExpression<T> {
764 public:
765   SGPowExpression(SGExpression<T>* expr0, SGExpression<T>* expr1)
766     : SGBinaryExpression<T>(expr0, expr1)
767   { }
768   virtual void eval(T& value, const simgear::expression::Binding* b) const
769   { value = pow(getOperand(0)->getDoubleValue(b), getOperand(1)->getDoubleValue(b)); }
770   using SGBinaryExpression<T>::getOperand;
771 };
772
773 template<typename T>
774 class SGSumExpression : public SGNaryExpression<T> {
775 public:
776   SGSumExpression()
777   { }
778   SGSumExpression(SGExpression<T>* expr0, SGExpression<T>* expr1)
779     : SGNaryExpression<T>(expr0, expr1)
780   { }
781   virtual void eval(T& value, const simgear::expression::Binding* b) const
782   {
783     value = T(0);
784     unsigned sz = SGNaryExpression<T>::getNumOperands();
785     for (unsigned i = 0; i < sz; ++i)
786       value += getOperand(i)->getValue(b);
787   }
788   using SGNaryExpression<T>::getValue;
789   using SGNaryExpression<T>::getOperand;
790 };
791
792 template<typename T>
793 class SGDifferenceExpression : public SGNaryExpression<T> {
794 public:
795   SGDifferenceExpression()
796   { }
797   SGDifferenceExpression(SGExpression<T>* expr0, SGExpression<T>* expr1)
798     : SGNaryExpression<T>(expr0, expr1)
799   { }
800   virtual void eval(T& value, const simgear::expression::Binding* b) const
801   {
802     value = getOperand(0)->getValue(b);
803     unsigned sz = SGNaryExpression<T>::getNumOperands();
804     for (unsigned i = 1; i < sz; ++i)
805       value -= getOperand(i)->getValue(b);
806   }
807   using SGNaryExpression<T>::getValue;
808   using SGNaryExpression<T>::getOperand;
809 };
810
811 template<typename T>
812 class SGProductExpression : public SGNaryExpression<T> {
813 public:
814   SGProductExpression()
815   { }
816   SGProductExpression(SGExpression<T>* expr0, SGExpression<T>* expr1)
817     : SGNaryExpression<T>(expr0, expr1)
818   { }
819   virtual void eval(T& value, const simgear::expression::Binding* b) const
820   {
821     value = T(1);
822     unsigned sz = SGNaryExpression<T>::getNumOperands();
823     for (unsigned i = 0; i < sz; ++i)
824       value *= getOperand(i)->getValue(b);
825   }
826   using SGNaryExpression<T>::getValue;
827   using SGNaryExpression<T>::getOperand;
828 };
829
830 template<typename T>
831 class SGMinExpression : public SGNaryExpression<T> {
832 public:
833   SGMinExpression()
834   { }
835   SGMinExpression(SGExpression<T>* expr0, SGExpression<T>* expr1)
836     : SGNaryExpression<T>(expr0, expr1)
837   { }
838   virtual void eval(T& value, const simgear::expression::Binding* b) const
839   {
840     unsigned sz = SGNaryExpression<T>::getNumOperands();
841     if (sz < 1)
842       return;
843     
844     value = getOperand(0)->getValue(b);
845     for (unsigned i = 1; i < sz; ++i)
846       value = SGMisc<T>::min(value, getOperand(i)->getValue(b));
847   }
848   using SGNaryExpression<T>::getOperand;
849 };
850
851 template<typename T>
852 class SGMaxExpression : public SGNaryExpression<T> {
853 public:
854   SGMaxExpression()
855   { }
856   SGMaxExpression(SGExpression<T>* expr0, SGExpression<T>* expr1)
857     : SGNaryExpression<T>(expr0, expr1)
858   { }
859   virtual void eval(T& value, const simgear::expression::Binding* b) const
860   {
861     unsigned sz = SGNaryExpression<T>::getNumOperands();
862     if (sz < 1)
863       return;
864     
865     value = getOperand(0)->getValue(b);
866     for (unsigned i = 1; i < sz; ++i)
867       value = SGMisc<T>::max(value, getOperand(i)->getValue(b));
868   }
869   using SGNaryExpression<T>::getOperand;
870 };
871
872 typedef SGExpression<int> SGExpressioni;
873 typedef SGExpression<float> SGExpressionf;
874 typedef SGExpression<double> SGExpressiond;
875 typedef SGExpression<bool> SGExpressionb;
876
877 /**
878  * Global function to make an expression out of properties.
879
880   <clip>
881     <clipMin>0</clipMin>
882     <clipMax>79</clipMax>
883     <abs>
884       <sum>
885         <rad2deg>
886           <property>sim/model/whatever-rad</property>
887         </rad2deg>
888         <property>sim/model/someother-deg</property>
889         <value>-90</value>
890       </sum>
891     </abs>
892   <clip>
893
894 will evaluate to an expression:
895
896 SGMisc<T>::clip(abs(deg2rad*sim/model/whatever-rad + sim/model/someother-deg - 90), clipMin, clipMax);
897
898  */
899 SGExpression<int>*
900 SGReadIntExpression(SGPropertyNode *inputRoot,
901                     const SGPropertyNode *configNode);
902
903 SGExpression<float>*
904 SGReadFloatExpression(SGPropertyNode *inputRoot,
905                       const SGPropertyNode *configNode);
906
907 SGExpression<double>*
908 SGReadDoubleExpression(SGPropertyNode *inputRoot,
909                        const SGPropertyNode *configNode);
910
911 SGExpression<bool>*
912 SGReadBoolExpression(SGPropertyNode *inputRoot,
913                      const SGPropertyNode *configNode);
914
915 namespace simgear
916 {
917   namespace expression
918   {
919   struct ParseError : public sg_exception
920   {
921       ParseError(const string& message = std::string())
922           : sg_exception(message) {}
923   };
924     
925   // Support for binding variables around an expression.
926   class Binding
927   {
928   public:
929       virtual ~Binding() {}
930       const virtual Value* getBindings() const = 0;
931       virtual Value* getBindings() = 0;
932   };
933
934   class VariableLengthBinding : public Binding
935   {
936   public:
937       const Value* getBindings() const
938       {
939           if (_bindings.empty())
940               return 0;
941           else
942               return &_bindings[0];
943       }
944       Value* getBindings()
945       {
946           if (_bindings.empty())
947               return 0;
948           else
949               return &_bindings[0];
950       }
951       std::vector<Value> _bindings;
952   };
953
954   template<int Size> class FixedLengthBinding : public Binding
955   {
956   public:
957       Value* getBindings()
958       {
959           return &_bindings[0];
960       }
961       const Value* getBindings() const
962       {
963           return &_bindings[0];
964       }
965       Value _bindings[Size];
966   };
967
968   struct VariableBinding
969   {
970       VariableBinding() : type(expression::DOUBLE), location(-1) {}
971
972       VariableBinding(const std::string& name_, expression::Type type_,
973                       int location_)
974           : name(name_), type(type_), location(location_)
975       {
976       }
977       std::string name;
978       expression::Type type;
979       int location;
980   };
981
982   class BindingLayout
983   {
984   public:
985       int addBinding(const std::string& name, expression::Type type);
986       bool findBinding(const string& name, VariableBinding& result) const;
987       std::vector<VariableBinding> bindings;
988   };
989
990   class Parser {
991   public:
992       typedef Expression* (*exp_parser)(const SGPropertyNode* exp,
993                                         Parser* parser);
994       void addParser(const std::string& name, exp_parser parser)
995       {
996           getParserMap().insert(std::make_pair(name, parser));
997       }
998       Expression* read(const SGPropertyNode* exp)
999       {
1000           ParserMap& map = getParserMap();
1001           ParserMap::iterator itr = map.find(exp->getName());
1002           if (itr == map.end())
1003               throw ParseError(string("unknown expression ") + exp->getName());
1004           exp_parser parser = itr->second;
1005           return (*parser)(exp, this);
1006       }
1007       // XXX vector of SGSharedPtr?
1008       bool readChildren(const SGPropertyNode* exp,
1009                         std::vector<Expression*>& result);
1010       /**
1011        * Function that parses a property tree, producing an expression.
1012        */
1013       typedef std::map<const std::string, exp_parser> ParserMap;
1014       virtual ParserMap& getParserMap() = 0;
1015       /**
1016        * After an expression is parsed, the binding layout may contain
1017        * references that need to be bound during evaluation.
1018        */
1019       BindingLayout& getBindingLayout() { return _bindingLayout; }
1020   protected:
1021       BindingLayout _bindingLayout;
1022   };
1023
1024   class ExpressionParser : public Parser
1025   {
1026   public:
1027       ParserMap& getParserMap()
1028       {
1029           return ParserMapSingleton::instance()->_parserTable;
1030       }
1031       static void addExpParser(const std::string&, exp_parser);
1032   protected:
1033       struct ParserMapSingleton : public simgear::Singleton<ParserMapSingleton>
1034       {
1035           ParserMap _parserTable;
1036       };
1037   };
1038
1039   /**
1040    * Constructor for registering parser functions.
1041    */
1042   struct ExpParserRegistrar
1043   {
1044       ExpParserRegistrar(const std::string& token, Parser::exp_parser parser)
1045       {
1046           ExpressionParser::addExpParser(token, parser);
1047       }
1048   };
1049
1050   }
1051
1052   /**
1053    * Access a variable definition. Use a location from a BindingLayout.
1054    */
1055   template<typename T>
1056   class VariableExpression : public ::SGExpression<T> {
1057   public:
1058     VariableExpression(int location) : _location(location) {}
1059     virtual ~VariableExpression() {}
1060     virtual void eval(T& value, const simgear::expression::Binding* b) const
1061     {
1062       const expression::Value* values = b->getBindings();
1063       value = *reinterpret_cast<const T *>(&values[_location].val);
1064     }
1065   protected:
1066     int _location;
1067
1068   };
1069
1070   /**
1071    * An n-ary expression where the types of the argument aren't the
1072    * same as the return type.
1073    */
1074   template<typename T, typename OpType>
1075   class GeneralNaryExpression : public ::SGExpression<T> {
1076   public:
1077     typedef OpType operand_type;
1078     unsigned getNumOperands() const
1079     { return _expressions.size(); }
1080     const ::SGExpression<OpType>* getOperand(unsigned i) const
1081     { return _expressions[i]; }
1082     ::SGExpression<OpType>* getOperand(unsigned i)
1083     { return _expressions[i]; }
1084     unsigned addOperand(::SGExpression<OpType>* expression)
1085     {
1086       if (!expression)
1087         return ~unsigned(0);
1088       _expressions.push_back(expression);
1089       return _expressions.size() - 1;
1090     }
1091     
1092     template<typename Iter>
1093     void addOperands(Iter begin, Iter end)
1094     {
1095       for (Iter iter = begin; iter != end; ++iter)
1096         {
1097           addOperand(static_cast< ::SGExpression<OpType>*>(*iter));
1098         }
1099     }
1100     
1101     virtual bool isConst() const
1102     {
1103       for (unsigned i = 0; i < _expressions.size(); ++i)
1104         if (!_expressions[i]->isConst())
1105           return false;
1106       return true;
1107     }
1108     virtual ::SGExpression<T>* simplify()
1109     {
1110       for (unsigned i = 0; i < _expressions.size(); ++i)
1111         _expressions[i] = _expressions[i]->simplify();
1112       return SGExpression<T>::simplify();
1113     }
1114
1115     simgear::expression::Type getOperandType() const
1116     {
1117       return simgear::expression::TypeTraits<OpType>::typeTag;
1118     }
1119     
1120   protected:
1121     GeneralNaryExpression()
1122     { }
1123     GeneralNaryExpression(::SGExpression<OpType>* expr0,
1124                           ::SGExpression<OpType>* expr1)
1125     { addOperand(expr0); addOperand(expr1); }
1126
1127     std::vector<SGSharedPtr<SGExpression<OpType> > > _expressions;
1128   };
1129
1130   /**
1131    * A predicate that wraps, for example the STL template predicate
1132    * expressions like std::equal_to.
1133    */
1134   template<typename OpType, template<typename PredOp> class Pred>
1135   class PredicateExpression : public GeneralNaryExpression<bool, OpType> {
1136   public:
1137     PredicateExpression()
1138     {
1139     }
1140     PredicateExpression(::SGExpression<OpType>* expr0,
1141                         ::SGExpression<OpType>* expr1)
1142       : GeneralNaryExpression<bool, OpType>(expr0, expr1)
1143     {
1144     }
1145     virtual void eval(bool& value, const simgear::expression::Binding* b) const
1146     {
1147       unsigned sz = this->getNumOperands();
1148       if (sz != 2)
1149         return;
1150       value = _pred(this->getOperand(0)->getValue(b),
1151                     this->getOperand(1)->getValue(b));
1152     }
1153   protected:
1154     Pred<OpType> _pred;
1155   };
1156
1157   template<template<typename OT> class Pred, typename OpType>
1158   PredicateExpression<OpType, Pred>*
1159   makePredicate(SGExpression<OpType>* op1, SGExpression<OpType>* op2)
1160   {
1161     return new PredicateExpression<OpType, Pred>(op1, op2);
1162   }
1163   
1164   template<typename OpType>
1165   class EqualToExpression : public PredicateExpression<OpType, std::equal_to>
1166   {
1167   public:
1168     EqualToExpression() {}
1169     EqualToExpression(::SGExpression<OpType>* expr0,
1170                       ::SGExpression<OpType>* expr1)
1171       : PredicateExpression<OpType, std::equal_to>(expr0, expr1)
1172     {
1173     }
1174   };
1175
1176   template<typename OpType>
1177   class LessExpression : public PredicateExpression<OpType, std::less>
1178   {
1179   public:
1180     LessExpression() {}
1181     LessExpression(::SGExpression<OpType>* expr0, ::SGExpression<OpType>* expr1)
1182       : PredicateExpression<OpType, std::less>(expr0, expr1)
1183     {
1184     }
1185   };
1186
1187   template<typename OpType>
1188   class LessEqualExpression
1189     : public PredicateExpression<OpType, std::less_equal>
1190   {
1191   public:
1192     LessEqualExpression() {}
1193     LessEqualExpression(::SGExpression<OpType>* expr0,
1194                         ::SGExpression<OpType>* expr1)
1195       : PredicateExpression<OpType, std::less_equal>(expr0, expr1)
1196     {
1197     }
1198   };
1199
1200   class NotExpression : public ::SGUnaryExpression<bool>
1201   {
1202   public:
1203     NotExpression(::SGExpression<bool>* expr = 0)
1204       : ::SGUnaryExpression<bool>(expr)
1205     {
1206     }
1207     void eval(bool& value, const expression::Binding* b) const
1208     {
1209       value = !getOperand()->getValue(b);
1210     }
1211   };
1212
1213   class OrExpression : public ::SGNaryExpression<bool>
1214   {
1215   public:
1216     void eval(bool& value, const expression::Binding* b) const
1217     {
1218       value = false;
1219       for (int i = 0; i < (int)getNumOperands(); ++i) {
1220         value = value || getOperand(i)->getValue(b);
1221         if (value)
1222           return;
1223       }
1224     }
1225   };
1226
1227   class AndExpression : public ::SGNaryExpression<bool>
1228   {
1229   public:
1230     void eval(bool& value, const expression::Binding* b) const
1231     {
1232       value = true;
1233       for (int i = 0; i < (int)getNumOperands(); ++i) {
1234         value = value && getOperand(i)->getValue(b);
1235         if (!value)
1236           return;
1237       }
1238     }
1239   };
1240
1241   /**
1242    * Convert an operand from OpType to T.
1243    */
1244   template<typename T, typename OpType>
1245   class ConvertExpression : public GeneralNaryExpression<T, OpType>
1246   {
1247   public:
1248     ConvertExpression() {}
1249     ConvertExpression(::SGExpression<OpType>* expr0)
1250     {
1251       this->addOperand(expr0);
1252     }
1253     virtual void eval(T& value, const simgear::expression::Binding* b) const
1254     {
1255       typename ConvertExpression::operand_type result;
1256       this->_expressions.at(0)->eval(result, b);
1257       value = result;
1258     }
1259   };
1260 }
1261 #endif // _SG_EXPRESSION_HXX