## vrheights

### view src/bezmath.c @ 14:25cab9e20c9c

mesh vbos
author John Tsiombikas Thu, 09 Oct 2014 01:29:28 +0300
line source
1 #include <math.h>
2 #include "bezmath.h"
4 static float bernstein(int i, float x);
7 struct vec3 v3_add(struct vec3 a, struct vec3 b)
8 {
9 a.x += b.x;
10 a.y += b.y;
11 a.z += b.z;
12 return a;
13 }
15 struct vec3 v3_sub(struct vec3 a, struct vec3 b)
16 {
17 a.x -= b.x;
18 a.y -= b.y;
19 a.z -= b.z;
20 return a;
21 }
23 struct vec3 v3_cross(struct vec3 a, struct vec3 b)
24 {
25 struct vec3 res;
26 res.x = a.y * b.z - a.z * b.y;
27 res.y = a.z * b.x - a.x * b.z;
28 res.z = a.x * b.y - a.y * b.x;
29 return res;
30 }
32 struct vec3 v3_normalize(struct vec3 v)
33 {
34 float len = sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
35 v.x /= len;
36 v.y /= len;
37 v.z /= len;
38 return v;
39 }
41 struct vec3 bezier_patch(struct vec3 *cp, float u, float v)
42 {
43 int i, j;
44 struct vec3 res = {0, 0, 0};
46 for(j=0; j<4; j++) {
47 for(i=0; i<4; i++) {
48 float bu = bernstein(i, u);
49 float bv = bernstein(j, v);
51 res.x += cp->x * bu * bv;
52 res.y += cp->y * bu * bv;
53 res.z += cp->z * bu * bv;
55 cp++;
56 }
57 }
58 return res;
59 }
61 #define DT 0.001
63 struct vec3 bezier_patch_norm(struct vec3 *cp, float u, float v)
64 {
65 struct vec3 tang, bitan, norm;
67 tang = v3_sub(bezier_patch(cp, u + DT, v), bezier_patch(cp, u - DT, v));
68 bitan = v3_sub(bezier_patch(cp, u, v + DT), bezier_patch(cp, u, v - DT));
69 norm = v3_cross(tang, bitan);
71 return v3_normalize(norm);
72 }
76 static float bernstein(int i, float x)
77 {
78 float invx = 1.0 - x;
80 switch(i) {
81 case 0:
82 return invx * invx * invx;
83 case 1:
84 return 3 * x * invx * invx;
85 case 2:
86 return 3 * x * x * invx;
87 case 3:
88 return x * x * x;
89 default:
90 break;
91 }
92 return 0;
93 }