]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/profile.cpp
Allow custom objects for tracks
[r2c2.git] / source / libr2c2 / profile.cpp
1 /* $Id$
2
3 This file is part of R²C²
4 Copyright © 2010 Mikkosoft Productions, Mikko Rasa
5 Distributed under the GPL
6 */
7
8 #include <cmath>
9 #include "profile.h"
10
11 using namespace std;
12 using namespace Msp;
13
14 namespace R2C2 {
15
16 void Profile::append_vertex(const Point &p, bool smooth)
17 {
18         if(vertices.size()>1 && !vertices.back().smooth)
19                 vertices.push_back(vertices.back());
20
21         Vertex v;
22         v.pos = p;
23         v.smooth = (!vertices.empty() && smooth);
24
25         if(!vertices.empty())
26         {
27                 float dx = p.x-vertices.back().pos.x;
28                 float dy = p.y-vertices.back().pos.y;
29                 float len = sqrt(dx*dx+dy*dy);
30                 v.normal.x = dy/len;
31                 v.normal.y = -dx/len;
32
33                 if(vertices.back().smooth)
34                 {
35                         Point &n = vertices.back().normal;
36                         n.x += v.normal.x;
37                         n.y += v.normal.y;
38                         len = sqrt(n.x*n.x+n.y*n.y);
39                         n.x /= len;
40                         n.y /= len;
41                 }
42                 else
43                         vertices.back().normal = v.normal;
44         }
45
46         vertices.push_back(v);
47
48         if(vertices.size()==1)
49         {
50                 min_coords = p;
51                 max_coords = p;
52         }
53         else
54         {
55                 min_coords.x = min(min_coords.x, p.x);
56                 min_coords.y = min(min_coords.y, p.y);
57                 max_coords.x = max(max_coords.x, p.x);
58                 max_coords.y = max(max_coords.y, p.y);
59         }
60 }
61
62 const Profile::Vertex &Profile::get_vertex(unsigned i) const
63 {
64         if(i>=vertices.size())
65                 throw InvalidParameterValue("Index out of range");
66         return vertices[i];
67 }
68
69
70 Profile::Loader::Loader(Profile &p):
71         DataFile::ObjectLoader<Profile>(p)
72 {
73         add("point", &Loader::point);
74         add("smooth_point", &Loader::smooth_point);
75 }
76
77 void Profile::Loader::point(float x, float y)
78 {
79         obj.append_vertex(Point(x/1000, y/1000), false);
80 }
81
82 void Profile::Loader::smooth_point(float x, float y)
83 {
84         obj.append_vertex(Point(x/1000, y/1000), true);
85 }
86
87 } // namespace R2C2