]> git.tdb.fi Git - libs/gl.git/blob - source/box.cpp
Add classes for building some geometric shapes
[libs/gl.git] / source / box.cpp
1 /* $Id$
2
3 This file is part of libmspgl
4 Copyright © 2011  Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #include <cmath>
9 #include "box.h"
10 #include "primitivebuilder.h"
11
12 using namespace std;
13
14 namespace Msp {
15 namespace GL {
16
17 BoxBuilder::BoxBuilder(float w, float h, float d):
18         origin(-w/2, -h/2, -d/2),
19         span(w, h, d)
20 { }
21
22 BoxBuilder::BoxBuilder(const Vector3 &o, const Vector3 &s):
23         origin(o),
24         span(s)
25 { }
26
27 void BoxBuilder::build(PrimitiveBuilder &builder) const
28 {
29         builder.normal(1, 0, 0);
30         build_face(builder, Vector3(origin.x+span.x, origin.y, origin.z), Vector3(0, span.y, 0), Vector3(0, 0, span.z));
31         builder.normal(0, 1, 0);
32         build_face(builder, Vector3(origin.x+span.x, origin.y+span.y, origin.z), Vector3(-span.x, 0, 0), Vector3(0, 0, span.z));
33         builder.normal(-1, 0, 0);
34         build_face(builder, Vector3(origin.x, origin.y+span.y, origin.z), Vector3(0, -span.y, 0), Vector3(0, 0, span.z));
35         builder.normal(0, -1, 0);
36         build_face(builder, origin, Vector3(span.x, 0, 0), Vector3(0, 0, span.z));
37         builder.normal(0, 0, 1);
38         build_face(builder, Vector3(origin.x, origin.y, origin.z+span.z), Vector3(span.x, 0, 0), Vector3(0, span.y, 0));
39         builder.normal(0, 0, -1);
40         build_face(builder, Vector3(origin.x+span.x, origin.y, origin.z), Vector3(-span.x, 0, 0), Vector3(0, span.y, 0));
41 }
42
43 void BoxBuilder::build_face(PrimitiveBuilder &builder, const Vector3 &o, const Vector3 &s1, const Vector3 &s2) const
44 {
45         if(tangent_attr>=0)
46         {
47                 builder.attrib(tangent_attr, s1.x, s1.y, s1.z);
48                 builder.attrib(binormal_attr, s2.x, s2.y, s2.z);
49         }
50         float u_size = 1;
51         float v_size = 1;
52         if(tex_fit!=STRETCH)
53         {
54                 float l1 = sqrt(s1.x*s1.x+s1.y*s1.y+s1.z*s1.z);
55                 float l2 = sqrt(s2.x*s2.x+s2.y*s2.y+s2.z*s2.z);
56                 if((l1<l2)==(tex_fit==CUT))
57                         u_size = l1/l2;
58                 else
59                         v_size = l2/l1;
60         }
61         builder.begin(TRIANGLE_STRIP);
62         builder.texcoord(0, v_size);
63         builder.vertex(o.x+s2.x, o.y+s2.y, o.z+s2.z);
64         builder.texcoord(0, 0);
65         builder.vertex(o.x, o.y, o.z);
66         builder.texcoord(u_size, v_size);
67         builder.vertex(o.x+s1.x+s2.x, o.y+s1.y+s2.y, o.z+s1.z+s2.z);
68         builder.texcoord(u_size, 0);
69         builder.vertex(o.x+s1.x, o.y+s1.y, o.z+s1.z);
70         builder.end();
71 }
72
73 } // namespace GL
74 } // namespace Msp