]> git.tdb.fi Git - libs/gltk.git/blob - source/part.cpp
Allow an empty graphic to be specified in part definitions
[libs/gltk.git] / source / part.cpp
1 #include <msp/gl/meshbuilder.h>
2 #include "geometry.h"
3 #include "part.h"
4 #include "partcache.h"
5 #include "resources.h"
6
7 using namespace std;
8
9 namespace Msp {
10 namespace GLtk {
11
12 Part::Part(const string &n):
13         name(n)
14 {
15         fill(graphic, graphic+N_STATES_, static_cast<Graphic *>(0));
16 }
17
18 const Graphic *Part::get_graphic(State state) const
19 {
20         if(state>N_STATES_)
21                 throw invalid_argument("Part::get_graphic");
22
23         return graphic[state];
24 }
25
26 void Part::build(const Geometry &parent, State state, PartCache &cache) const
27 {
28         if(!graphic[state] || !graphic[state]->get_texture())
29                 return;
30
31         Geometry rgeom = geom;
32         align.apply(rgeom, parent, margin);
33         GL::MeshBuilder bld(cache.create_mesh(*this, *graphic[state]->get_texture()));
34         bld.matrix() *= GL::Matrix::translation(rgeom.x, rgeom.y, 0);
35         graphic[state]->build(rgeom.w, rgeom.h, bld);
36 }
37
38
39 Part::Loader::Loader(Part &p, Resources &r):
40         DataFile::CollectionObjectLoader<Part>(p, &r)
41 {
42         add("graphic", &Loader::graphic);
43         add("align",   &Loader::align);
44         add("fill",    &Loader::fill);
45         add("margin",  &Loader::margin);
46         add("size",    &Loader::size);
47 }
48
49 Part::Loader::~Loader()
50 {
51         for(unsigned i=0; i<N_STATES_; ++i)
52                 if(obj.graphic[i])
53                 {
54                         const Graphic &grph = *obj.graphic[i];
55                         const Sides &shadow = grph.get_shadow();
56                         obj.geom.w = max(obj.geom.w, grph.get_width()-shadow.left-shadow.right);
57                         obj.geom.h = max(obj.geom.h, grph.get_height()-shadow.bottom-shadow.top);
58                 }
59 }
60
61 void Part::Loader::graphic_normal(const string &n)
62 {
63         graphic(NORMAL, n);
64 }
65
66 void Part::Loader::graphic(State s, const string &n)
67 {
68         Graphic *grph = (n.empty() ? 0 : &get_collection().get<Graphic>(n));
69         for(int i=0; i<N_STATES_; ++i)
70                 if((i&s)==s)
71                         obj.graphic[i] = grph;
72 }
73
74 void Part::Loader::align(float x, float y)
75 {
76         obj.align.x = x;
77         obj.align.y = y;
78 }
79
80 void Part::Loader::fill(float w, float h)
81 {
82         obj.align.w = w;
83         obj.align.h = h;
84 }
85
86 void Part::Loader::margin()
87 {
88         load_sub(obj.margin);
89 }
90
91 void Part::Loader::size(unsigned w, unsigned h)
92 {
93         obj.geom.w = w;
94         obj.geom.h = h;
95 }
96
97 } // namespace GLtk
98 } // namespace Msp