Is there a simple, efficient way to implement a piecewise linear integer-to-integer curve interpolation in C# (for Unity3D, if it matters) ?
Details are as follows:
- The piecewise linear curve representation has to be built over time. The first interpolation request comes before we have all data points
- The curve is strictly monotonous
- The first point is always (0, 0)
- The data points' first coordinates are also strictly monotonous w.r.t arrival time, i.e. the points are naturally ordered by their first coordinate.
- The data points are not in ranges that would cause cause overflow problems for 4-byte integers
- The output does not have to be 100% accurate, so rounding errors are not an issue.
In C++, I would do something like this:
#include <algorithm>
#include <vector>
#include <cassert>
using namespace std;
typedef pair<int, int> tDataPoint;
typedef vector<tDataPoint> tPLC;
void appendData(tPLC& curve, const tDataPoint& point) {
assert(curve.empty() || curve.back().first < point.first);
curve.push_back(point);
}
int interpolate(const tPLC& curve, int cursor) {
assert(!curve.empty());
int result = 0;
// below zero, the value is a constant 0
if (cursor > 0) {
// find the first data point above the cursor
const auto upper = upper_bound(begin(curve), end(curve), cursor);
// above the last data point, the value is a constant 0
if (upper == end(curve)) {
result = curve.back().second;
} else {
// get the point below or equal to the cursor
const auto lower = upper - 1;
// lerp between
float linear = float((cursor - lower.first) * (upper.second - lower.second)) / (upper.first - lower.first);
result = lower.second + int(linear);
}
}
return result;
}
I can see how I could do something that work sort of like this in C#, but nothing as concise or efficient. Any help will be appreciated.
EDIT:
I do not need to be more accurate, and am perfectly happy with piecewise linear interpolation, so better interpolation quality is not my problem here.
What I am looking for is an efficient, concise way of doing this. By efficient, I mean things like: relying on the fact that the data points are naturally ordered to be able to use binary search to find the proper segment