[英]Piecewise linear integer curve interpolation in C#/Unity3D
是否有一種簡單有效的方法在C#中實現分段線性整數到整數曲線插值(對於Unity3D,如果重要的話)?
詳細信息如下:
在C ++中,我將執行以下操作:
#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;
}
我可以看到如何在C#中執行類似的工作,但沒有任何簡潔或有效的方法。 任何幫助將不勝感激。
編輯:我不需要更加准確,並且對分段線性插值非常滿意,因此更好的插值質量不是我的問題。
我正在尋找的是一種高效,簡潔的方法。 高效,我的意思是:依靠數據點自然排序的事實,以便能夠使用二進制搜索找到正確的段
我將使用以下插值三次方:
x=a0+a1*t+a2*t*t+a3*t*t*t
y=b0+b1*t+b2*t*t+b3*t*t*t
其中a0..a3
的計算方式如下:
d1=0.5*(p2.x-p0.x);
d2=0.5*(p3.x-p1.x);
a0=p1.x;
a1=d1;
a2=(3.0*(p2.x-p1.x))-(2.0*d1)-d2;
a3=d1+d2+(2.0*(-p2.x+p1.x));
b0 .. b3
的計算方法相同,但是當然使用y
坐標
p0..p3
是三次插值曲線的控制點
t = < 0.0 , 1.0 >
是從p1
到p2
曲線參數
這樣可以確保位置和一階導數是連續的(c1)。 如果要在整數數學上執行此操作,則只需相應地縮放ai,bi
ant t
。 您也可以按照需要添加任意多個尺寸
現在,您需要一些參數來遍歷插值點,例如u = <0 , N-1>
p(0..N-1)
是您的控制點列表
u = 0
表示起點p(0)
u = N-1
表示終點p(N-1)
P0..P3
是用於插補的控制點
因此,您需要計算t
並選擇用於插值的點
double t=u-floor(u); // fractional part between control points
int i=floor(u); // integer part points to starting control point used
if (i<1) { P0=p( 0),P1=p( 0),P2=p( 1),P3=p( 2); } // handle start edge case
else if (i==N-1) { P0=p(N-2),P1=p(N-1),P2=p(N-1),P3=p(N-1); } // handle end edge case
else if (i>=N-2) { P0=p(N-3),P1=p(N-2),P2=p(N-1),P3=p(N-1); } // handle end edge case
else { P0=p(i-1),P1=p(i ),P2=p(i+1),P3=p(i+2); }
(x,y) = interpolation (P0,P1,P2,P3,t);
如果要在整數數學上執行此操作,則只需相應地縮放u,t
。 如果N<3
則使用線性插值...或重復終點,直到N>=3
[edit1]線性插值方法
struct pnt { int x,y; };
pnt interpolate (pnt *p,int N,int x)
{
int i,j;
pnt p;
for (j=1,i=N-1;j<i;j<<=1); j>>=1; if (!j) j=1; // this just determine max mask for binary search ... can do it on p[] size change
for (i=0;j;j>>=1) // binary search by x coordinate output is i as point index with p[i].x<=x
{
i|=j;
if (i>=N) { i-=j; continue; }
if (p[i].x==x) break;
if (p[i].x> x) i-=j;
}
p.x=x;
p.y=p[i].y+((p[i+1].y-p[i].y)*(x-p[i].x)/(p[i+1].x-p[i].x))
return p;
}
添加邊緣情況處理,例如x
超出點邊界或點列表太小
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.