1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
|
/*
* The Mana Client
* Copyright (C) 2004-2009 The Mana World Development Team
* Copyright (C) 2009-2012 The Mana Developers
*
* This file is part of The Mana Client.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "resources/resourcemanager.h"
#include "client.h"
#include "log.h"
#include "resources/dye.h"
#include "resources/image.h"
#include "resources/imageset.h"
#include "resources/music.h"
#include "resources/soundeffect.h"
#include "resources/spritedef.h"
#include "utils/filesystem.h"
#include <SDL_image.h>
#include <cassert>
#include <sstream>
#include <memory>
#include <sys/time.h>
ResourceManager *ResourceManager::instance = nullptr;
ResourceManager::ResourceManager()
{
logger->log("Initializing resource manager...");
}
ResourceManager::~ResourceManager()
{
auto cleanupResources = [&](auto match)
{
// Include any orphaned resources into the main list for cleanup
mResources.insert(mOrphanedResources.begin(), mOrphanedResources.end());
mOrphanedResources.clear();
for (auto iter = mResources.begin(); iter != mResources.end(); )
{
if (match(iter->second))
{
cleanUp(iter->second);
iter = mResources.erase(iter);
}
else
{
++iter;
}
}
};
// SpriteDef references ImageSet
cleanupResources([](Resource *res) { return dynamic_cast<SpriteDef *>(res); });
// ImageSet references Image
cleanupResources([](Resource *res) { return dynamic_cast<ImageSet *>(res); });
// Release remaining resources
cleanupResources([](Resource *res) { return true; });
assert(mOrphanedResources.empty());
}
void ResourceManager::cleanUp(Resource *res)
{
if (res->mRefCount > 0)
{
logger->log("ResourceManager::~ResourceManager() cleaning up %d "
"reference%s to %s",
res->mRefCount,
(res->mRefCount == 1) ? "" : "s",
res->mIdPath.c_str());
}
delete res;
}
void ResourceManager::cleanOrphans()
{
// Delete orphaned resources after 30 seconds.
time_t oldest = time(nullptr);
const time_t threshold = oldest - 30;
if (mOrphanedResources.empty() || mOldestOrphan >= threshold)
return;
auto iter = mOrphanedResources.begin();
while (iter != mOrphanedResources.end())
{
Resource *res = iter->second;
const time_t t = res->mTimeStamp;
if (t >= threshold)
{
if (t < oldest)
oldest = t;
++iter;
}
else
{
logger->log("ResourceManager::release(%s)", res->mIdPath.c_str());
iter = mOrphanedResources.erase(iter);
delete res; // delete only after removal from list, to avoid issues in recursion
}
}
mOldestOrphan = oldest;
}
bool ResourceManager::addToSearchPath(const std::string &path, bool append)
{
logger->log("Adding to PhysicsFS: %s", path.c_str());
if (!FS::addToSearchPath(path, append))
{
logger->log("Error: %s", FS::getLastError());
return false;
}
return true;
}
void ResourceManager::searchAndAddArchives(const std::string &path,
const std::string &ext,
bool append)
{
const char *dirSep = FS::getDirSeparator();
for (auto fileName : FS::enumerateFiles(path))
{
const size_t len = strlen(fileName);
if (len > ext.length() && ext != (fileName + (len - ext.length())))
{
std::string file = path + fileName;
if (auto realDir = FS::getRealDir(file))
{
std::string archive = std::string(*realDir) + dirSep + file;
addToSearchPath(archive, append);
}
}
}
}
std::string ResourceManager::getPath(const std::string &file)
{
// Get the real directory of the file
auto realDir = FS::getRealDir(file);
std::string path;
if (realDir)
{
path = std::string(*realDir) + "/" + file;
}
else
{
// if not found in search path return the default path
path = Client::getPackageDirectory() + "/" + file;
}
return path;
}
Resource *ResourceManager::get(const std::string &idPath,
const std::function<Resource *()> &generator)
{
// Check if the id exists, and return the value if it does.
auto resIter = mResources.find(idPath);
if (resIter != mResources.end())
{
return resIter->second;
}
resIter = mOrphanedResources.find(idPath);
if (resIter != mOrphanedResources.end())
{
Resource *res = resIter->second;
mResources.insert(*resIter);
mOrphanedResources.erase(resIter);
return res;
}
Resource *resource = generator();
if (resource)
{
resource->mIdPath = idPath;
mResources[idPath] = resource;
cleanOrphans();
}
return resource;
}
ResourceRef<Music> ResourceManager::getMusic(const std::string &path)
{
return static_cast<Music*>(get(path, [&] () -> Resource * {
if (SDL_RWops *rw = FS::openBufferedRWops(path))
return Music::load(rw);
return nullptr;
}));
}
ResourceRef<SoundEffect> ResourceManager::getSoundEffect(const std::string &path)
{
return static_cast<SoundEffect*>(get(path, [&] () -> Resource * {
if (SDL_RWops *rw = FS::openBufferedRWops(path))
return SoundEffect::load(rw);
return nullptr;
}));
}
ResourceRef<Image> ResourceManager::getImage(const std::string &idPath)
{
return static_cast<Image*>(get(idPath, [&] () -> Resource * {
std::string path = idPath;
std::string::size_type p = path.find('|');
std::unique_ptr<Dye> d;
if (p != std::string::npos)
{
d = std::make_unique<Dye>(path.substr(p + 1));
path = path.substr(0, p);
}
SDL_RWops *rw = FS::openRWops(path);
if (!rw)
return nullptr;
Resource *res = d ? Image::load(rw, *d)
: Image::load(rw);
return res;
}));
}
ResourceRef<ImageSet> ResourceManager::getImageSet(const std::string &imagePath,
int w, int h)
{
std::stringstream ss;
ss << imagePath << "[" << w << "x" << h << "]";
return static_cast<ImageSet*>(get(ss.str(), [&] () -> Resource * {
auto img = getImage(imagePath);
if (!img)
return nullptr;
return new ImageSet(img, w, h);
}));
}
ResourceRef<SpriteDef> ResourceManager::getSprite(const std::string &path, int variant)
{
std::stringstream ss;
ss << path << "[" << variant << "]";
return static_cast<SpriteDef*>(get(ss.str(), [&] () -> Resource * {
return SpriteDef::load(path, variant);
}));
}
void ResourceManager::release(Resource *res)
{
auto resIter = mResources.find(res->mIdPath);
// The resource has to exist
assert(resIter != mResources.end() && resIter->second == res);
const time_t timestamp = time(nullptr);
res->mTimeStamp = timestamp;
if (mOrphanedResources.empty())
mOldestOrphan = timestamp;
mOrphanedResources.insert(*resIter);
mResources.erase(resIter);
}
void ResourceManager::remove(Resource *res)
{
mResources.erase(res->mIdPath);
}
ResourceManager *ResourceManager::getInstance()
{
// Create a new instance if necessary.
if (!instance)
instance = new ResourceManager;
return instance;
}
void ResourceManager::deleteInstance()
{
delete instance;
instance = nullptr;
}
|