Skip to content

Instantly share code, notes, and snippets.

@soraphis
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soraphis/61ee9185416ee23d0d40 to your computer and use it in GitHub Desktop.
Save soraphis/61ee9185416ee23d0d40 to your computer and use it in GitHub Desktop.
algorithm to calculate b splines
package testproject.test;
import java.awt.Graphics;
public class Bspline {
double[][] P;
double[] T;
int _k = 3;
public Bspline() {
P = new double[3][2];
P[0][0] = 100; P[0][1] = 100;
P[1][0] = 47; P[1][1] = 68;
P[2][0] = 123; P[2][1] = 284;
update();
}
private void update() {
if(P.length < 2)
return;
//_k = Math.min(4, P.length);
T = new double[_k+P.length+1];
double d = 1.0/(1+T.length - 2*_k);
int i;
for(i = _k ; i < T.length-_k; i++){
T[i] = (i+1-_k)*d;
}for(; i < T.length; i++){
T[i] = 1;
}
}
private double basisFunc(int i, int k, double t){
if(k == 0){
if(T[i] <= t && t < T[i+1])
return 1;
return 0;
}
double a = (T[i+k]-T[i]) == 0 ? 0 : (t-T[i])/(T[i+k]-T[i]);
double b = (T[i+k+1]-T[i+1]) == 0 ? 0 : (T[i+k+1]-t)/(T[i+k+1]-T[i+1]);
if(Double.isNaN(a) || Double.isNaN(b) || Double.isInfinite(a) || Double.isInfinite(b))
System.err.println("should not happen");
return a*basisFunc(i, k-1, t) + b * basisFunc(i+1, k-1, t);
}
private double[] DeBoor(double t){
double[] V = new double[2];
for(int i = 0; i < P.length; i++){
double scale = basisFunc(i, _k, t);
V[0] += P[i][0] * scale;
V[1] += P[i][1] * scale;
}
return V;
}
public void calculatePath(Graphics g){
if(P.length < 2){
return; // zu wenige punkte um ein pfad zu zeichnen
}
double[] v = new double[2];
/*
double delta = (T[P.length+1]-T[_k])/32.0;
for(double t = T[_k]; t < T[P.length+1]; t += delta ){
/*/
double delta = 1/32.0;
for(double t = 0; t < 1; t += delta ){
//*/
double[] p = DeBoor(t);
// System.out.println(p[0]+"|"+p[1]);
if(v != null){ g.drawLine((int)v[0], (int)v[1], (int)p[0], (int)p[1]); }
v = p;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment