]> git.tdb.fi Git - libs/gl.git/blob - source/capsule.cpp
Refactor AnimationPlayer ticking
[libs/gl.git] / source / capsule.cpp
1 #define _USE_MATH_DEFINES
2 #include <cmath>
3 #include "capsule.h"
4 #include "primitivebuilder.h"
5
6 using namespace std;
7
8 namespace Msp {
9 namespace GL {
10
11 CapsuleBuilder::CapsuleBuilder(float r, float l, unsigned s, unsigned n):
12         radius(r),
13         length(l),
14         segments(s),
15         rings(n)
16 {
17         if(segments<3)
18                 segments = 3;
19         rings |= 1;
20         if(rings<3)
21                 rings = 3;
22 }
23
24 void CapsuleBuilder::build(PrimitiveBuilder &builder) const
25 {
26         float u_scale = 1.0/segments;
27         float v_scale = 1/(length+radius*M_PI);
28         adjust_texture_scale(u_scale, v_scale, radius*M_PI*2, length+radius*M_PI);
29
30         builder.normal(0, 0, -1);
31         builder.texcoord(0.5, 0);
32         builder.vertex(0, 0, -length/2-radius);
33         for(unsigned i=1; i<rings; ++i)
34         {
35                 float cz = length*(i>rings/2 ? 0.5 : -0.5);
36                 float v = ((i>rings/2 ? i-1 : i)*radius*M_PI/(rings-1)+(i>rings/2 ? length : 0))*v_scale;
37                 float ra = (i>rings/2 ? i-1 : i)*M_PI/(rings-1);
38                 float rc = cos(ra);
39                 float rs = sin(ra);
40                 for(unsigned j=0; j<=segments; ++j)
41                 {
42                         float sa = j*M_PI*2/segments;
43                         float sc = cos(sa);
44                         float ss = sin(sa);
45                         builder.normal(rs*sc, rs*ss, -rc);
46                         if(generate_tbn)
47                         {
48                                 builder.tangent(-ss, sc, 0);
49                                 builder.binormal(rc*sc, rc*ss, rs);
50                         }
51                         builder.texcoord(j*u_scale, v);
52                         builder.vertex(rs*sc*radius, rs*ss*radius, cz-rc*radius);
53                 }
54         }
55         builder.normal(0, 0, 1);
56         builder.texcoord(0.5, (length+radius*M_PI)*v_scale);
57         builder.vertex(0, 0, length/2+radius);
58
59         for(unsigned i=0; i<segments; ++i)
60         {
61                 builder.begin(TRIANGLE_STRIP);
62                 builder.element(0);
63                 for(unsigned j=0; j+1<rings; ++j)
64                 {
65                         builder.element(1+j*(segments+1)+i+1);
66                         builder.element(1+j*(segments+1)+i);
67                 }
68                 builder.element((segments+1)*(rings-1)+1);
69                 builder.end();
70         }
71 }
72
73 } // namespace GL
74 } // namespace Msp