1 // Written by Andrew J. Ross, started December 2003
3 // Copyright (C) 2003 Andrew J. Ross - andy@plausible.org
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Library General Public
7 // License as published by the Free Software Foundation; either
8 // version 2 of the License, or (at your option) any later version.
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Library General Public License for more details.
15 // You should have received a copy of the GNU Library General Public
16 // License along with this library; if not, write to the
17 // Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 // Boston, MA 02111-1307, USA.
20 #include "interpolator.hxx"
22 void SGInterpolator::addNew(SGPropertyNode* prop, int nPoints)
24 // Set the property type to a double, if it isn't already, and
25 // make sure we aren't already managing this node.
26 prop->setDoubleValue(prop->getDoubleValue());
29 Interp* iterp = new Interp();
31 iterp->nPoints = nPoints;
32 iterp->curve = new double[2*nPoints];
34 // Dirty trick: leave the new value sitting in _list to avoid
35 // having to return a pointer to a private type.
40 void SGInterpolator::interpolate(SGPropertyNode* prop, int nPoints,
41 double* values, double* deltas)
43 addNew(prop, nPoints);
44 for(int i=0; i<nPoints; i++) {
45 _list->dt(i) = deltas[i];
46 _list->val(i) = values[i];
50 void SGInterpolator::interpolate(SGPropertyNode* prop, double val, double dt)
58 // Delete all the list elements where "expr" is true.
60 // Silly preprocessor hack to avoid writing the linked list code in
61 // two places. You would think that an STL set would be the way to
62 // go, but I had terrible trouble getting it to work with the
63 // dynamically allocated "curve" member. Frankly, this is easier to
64 // write, and the code is smaller to boot...
66 #define DELETE_WHERE(EXPR)\
67 Interp *p = _list, **last = &_list; \
72 p = (*last) ? (*last)->next : 0; \
77 void SGInterpolator::cancel(SGPropertyNode* prop)
79 DELETE_WHERE(p->target == prop)
82 void SGInterpolator::update(double dt)
84 DELETE_WHERE(interp(p, dt))
87 // This is the where the only "real" work happens. Walk through the
88 // data points until we find one with some time left, slurp it up and
89 // repeat until we run out of dt.
90 bool SGInterpolator::interp(Interp* rec, double dt)
92 double val = rec->target->getDoubleValue();
94 for(i=0; i < rec->nPoints; i++) {
95 if(rec->dt(i) > 0 && dt < rec->dt(i)) {
96 val += (dt / rec->dt(i)) * (rec->val(i) - val);
103 rec->target->setDoubleValue(val);
105 // Return true if this one is done
106 return i == rec->nPoints;