]> git.tdb.fi Git - libs/gltk.git/blob - source/partcache.cpp
Add consistency checks to PartCache
[libs/gltk.git] / source / partcache.cpp
1 #include "part.h"
2 #include "partcache.h"
3
4 using namespace std;
5
6 namespace Msp {
7 namespace GLtk {
8
9 CachedPart::CachedPart():
10         part(0),
11         texture(0),
12         mesh(0)
13 { }
14
15 CachedPart::~CachedPart()
16 {
17         delete mesh;
18 }
19
20
21 PartCache::PartCache():
22         rebuilding(false)
23 { }
24
25 void PartCache::begin_rebuild()
26 {
27         if(rebuilding)
28                 throw logic_error("nested rebuild");
29         rebuilding = true;
30
31         next = parts.begin();
32         current = parts.end();
33 }
34
35 void PartCache::insert_special(const Part &part)
36 {
37         if(part.get_name().empty())
38                 throw invalid_argument("PartCache::insert_special");
39         if(!rebuilding)
40                 throw logic_error("!rebuilding");
41
42         for(current=next; current!=parts.end(); ++current)
43                 if(current->part==&part)
44                 {
45                         parts.erase(next, current);
46                         break;
47                 }
48
49         if(current==parts.end())
50                 current = parts.insert(next, CachedPart());
51         else
52                 *current = CachedPart();
53         current->part = ∂
54
55         next = current;
56         ++next;
57 }
58
59 GL::Mesh &PartCache::create_mesh(const Part &part, const GL::Texture2D &tex)
60 {
61         if(!rebuilding)
62                 throw logic_error("!rebuilding");
63
64         if(current!=parts.end() && current->texture==&tex)
65                 return *current->mesh;
66
67         for(current=next; current!=parts.end(); ++current)
68                 if(current->texture==&tex)
69                 {
70                         parts.erase(next, current);
71                         break;
72                 }
73
74         if(current==parts.end())
75         {
76                 current = parts.insert(next, CachedPart());
77                 current->texture = &tex;
78                 current->mesh = new GL::Mesh((GL::TEXCOORD2, GL::COLOR4_UBYTE, GL::VERTEX2));
79         }
80         else
81                 current->mesh->clear();
82         current->part = ∂
83
84         next = current;
85         ++next;
86
87         return *current->mesh;
88 }
89
90 void PartCache::end_rebuild()
91 {
92         rebuilding = false;
93         parts.erase(next, parts.end());
94 }
95
96 } // namespace GLtk
97 } // namespace Msp