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