asset_manager.cpp 11.6 KB
Newer Older
1
2
#include <mirrage/asset/asset_manager.hpp>

3
4
#include <mirrage/asset/error.hpp>

5
#include <mirrage/utils/log.hpp>
6
#include <mirrage/utils/template_utils.hpp>
7
8
9
10

#include <physfs.h>

#include <cstdio>
11
#include <cstring>
12

Florian Oetke's avatar
Florian Oetke committed
13
#ifdef _WIN32
14
15
#include <direct.h>
#include <windows.h>
16
#else
17
18
#include <sys/stat.h>
#include <unistd.h>
19
20
21
#endif


22
using namespace mirrage::util;
23
using namespace std::string_literals;
24
25
26

namespace {

27
28
	std::string append_file(const std::string& folder, const std::string file)
	{
29
		if(ends_with(folder, "/") || starts_with(file, "/"))
30
			return folder + file;
31
		else
32
			return folder + "/" + file;
33
	}
34
35
	void create_dir(const std::string& dir)
	{
Florian Oetke's avatar
Florian Oetke committed
36
#ifdef _WIN32
37
38
39
40
41
42
		CreateDirectory(dir.c_str(), NULL);
#else
		mkdir(dir.c_str(), 0777);
#endif
	}

43
44
	auto last_of(const std::string& str, char c)
	{
45
		auto idx = str.find_last_of(c);
46
		return idx != std::string::npos ? mirrage::util::just(idx + 1) : mirrage::util::nothing;
47
48
	}

49
50
	auto split_path(const std::string& path)
	{
51
		auto filename_delim_end = last_of(path, '/').get_or(last_of(path, '\\').get_or(0));
52

53
		return std::make_tuple(path.substr(0, filename_delim_end - 1),
54
55
56
57
		                       path.substr(filename_delim_end, std::string::npos));
	}


58
59
	std::vector<std::string> list_files(const std::string& dir,
	                                    const std::string& prefix,
60
61
	                                    const std::string& suffix) noexcept
	{
62
63
		std::vector<std::string> res;

64
		char** rc = PHYSFS_enumerateFiles(dir.c_str());
65

66
		for(char** i = rc; *i != nullptr; i++) {
67
68
			std::string str(*i);

69
70
			if((prefix.length() == 0 || str.find(prefix) == 0)
			   && (suffix.length() == 0 || str.find(suffix) == str.length() - suffix.length()))
71
72
73
74
75
76
77
				res.emplace_back(std::move(str));
		}

		PHYSFS_freeList(rc);

		return res;
	}
78
79
	std::vector<std::string> list_wildcard_files(const std::string& wildcard_path)
	{
80
		auto   spr  = split_path(wildcard_path);
81
82
83
		auto&& path = std::get<0>(spr);
		auto&& file = std::get<1>(spr);

84
		auto wildcard = last_of(file, '*').get_or(file.length());
85
86
		LOG_IF(plog::warning, wildcard != file.find_first_of('*') + 1)
		        << "More than one wildcard ist currently not supported. Found in: " << wildcard_path;
87

88
89
		auto prefix = file.substr(0, wildcard - 1);
		auto suffix = wildcard < file.length() ? file.substr(0, wildcard - 1) : std::string();
90
91
92
93
94
95
96
97
98

		auto files = list_files(path, prefix, suffix);
		for(auto& file : files) {
			file = path + "/" + file;
		}

		return files;
	}

99
100
	bool exists_file(const std::string path)
	{
101
		if(!PHYSFS_exists(path.c_str()))
102
103
104
			return false;

		auto stat = PHYSFS_Stat{};
105
		if(!PHYSFS_stat(path.c_str(), &stat))
106
107
108
			return false;

		return stat.filetype == PHYSFS_FILETYPE_REGULAR;
109
	}
110
111
	bool exists_dir(const std::string path)
	{
112
		if(!PHYSFS_exists(path.c_str()))
113
114
115
			return false;

		auto stat = PHYSFS_Stat{};
116
		if(!PHYSFS_stat(path.c_str(), &stat))
117
118
119
			return false;

		return stat.filetype == PHYSFS_FILETYPE_DIRECTORY;
120
121
	}

122
	template <typename Callback>
123
124
	void print_dir_recursiv(const std::string& dir, uint8_t depth, Callback&& callback)
	{
125
		std::string p;
126
127
		for(uint8_t i = 0; i < depth; i++)
			p += "  ";
128

129
		callback(p + dir);
130
131
		depth++;
		for(auto&& f : list_files(dir, "", "")) {
132
			if(depth >= 5)
133
				callback(p + "  " + f);
134
			else
135
136
137
138
				print_dir_recursiv(f, depth, callback);
		}
	}

139
140
	void init_physicsfs(const std::string& exe_name)
	{
141
142
143
		if(!PHYSFS_isInit() && !PHYSFS_init(exe_name.empty() ? nullptr : exe_name.c_str())) {
			throw std::system_error(static_cast<mirrage::asset::Asset_error>(PHYSFS_getLastErrorCode()),
			                        "Unable to initalize PhysicsFS.");
144
145
146
		}
	}

147
	constexpr auto default_source = {std::make_tuple("assets", false), std::make_tuple("assets.zip", true)};
148
} // namespace
149

150
namespace mirrage::asset {
151

152
153
	std::string pwd()
	{
154
155
		char cCurrentPath[FILENAME_MAX];

156
157
158
#ifdef WINDOWS
		_getcwd(cCurrentPath, sizeof(cCurrentPath));
#else
159
160
161
		if(getcwd(cCurrentPath, sizeof(cCurrentPath)) == nullptr) {
			MIRRAGE_FAIL("getcwd with max length " << FILENAME_MAX << " failed with error code " << errno);
		}
162
#endif
163
164
165

		return cCurrentPath;
	}
166
167
	std::string write_dir(const std::string& exe_name,
	                      const std::string& org_name,
168
169
	                      const std::string& app_name)
	{
170
		init_physicsfs(exe_name);
171

172
173
174
		if(exists_dir("write_dir")) {
			return "write_dir";
		}
175

176
		return PHYSFS_getPrefDir(org_name.c_str(), app_name.c_str());
177
	}
178

179

180
181
	Asset_manager::Asset_manager(const std::string& exe_name,
	                             const std::string& org_name,
182
183
	                             const std::string& app_name)
	{
184
		init_physicsfs(exe_name);
185

186
		auto write_dir = ::mirrage::asset::write_dir(exe_name, org_name, app_name);
187

188
189
190
191
192
		if(!PHYSFS_mount(PHYSFS_getBaseDir(), nullptr, 1)
		   || !PHYSFS_mount(append_file(PHYSFS_getBaseDir(), "..").c_str(), nullptr, 1)
		   || !PHYSFS_mount(pwd().c_str(), nullptr, 1))
			throw std::system_error(static_cast<Asset_error>(PHYSFS_getLastErrorCode()),
			                        "Unable to setup default search path.");
193

194
195
		create_dir(write_dir);

196
		LOG(plog::debug) << "Write dir: " << write_dir;
197

198
		if(!PHYSFS_mount(write_dir.c_str(), nullptr, 0))
199
200
			throw std::system_error(static_cast<Asset_error>(PHYSFS_getLastErrorCode()),
			                        "Unable to construct search path.");
201

202
		if(!PHYSFS_setWriteDir(write_dir.c_str()))
203
204
			throw std::system_error(static_cast<Asset_error>(PHYSFS_getLastErrorCode()),
			                        "Unable to set write-dir: "s + write_dir);
205
206
207


		auto add_source = [](const char* path) {
208
209
210
			if(!PHYSFS_mount(path, nullptr, 1))
				throw std::system_error(static_cast<Asset_error>(PHYSFS_getLastErrorCode()),
				                        "Error adding custom archive: "s + path);
211
212
		};

213
		if(!exists_file("archives.lst")) {
214
215
216
			bool lost = true;
			for(auto& s : default_source) {
				const char* path;
217
				bool        file;
218
219
220
221
222
223
224
225
226
227

				std::tie(path, file) = s;

				if(file ? exists_file(path) : exists_dir(path)) {
					add_source(path);
					lost = false;
				}
			}

			if(lost) {
228
229
				LOG(plog::fatal) << "No archives.lst found. printing search-path...\n";
				print_dir_recursiv("/", 0, [](auto&& path) { LOG(plog::fatal) << path; });
230

231
232
				throw std::system_error(static_cast<Asset_error>(PHYSFS_getLastErrorCode()),
				                        "No archives.lst found.");
233
			} else {
234
				LOG(plog::info) << "No archives.lst found. Using defaults.";
235
236
			}
		} else {
237
238
			auto in = _open("cfg:archives.lst"_aid, "archives.lst");

239
			// load other archives
240
241
242
			for(auto&& l : in.lines()) {
				if(l.find_last_of('*') != std::string::npos) {
					for(auto& file : list_wildcard_files(l)) {
243
						LOG(plog::info) << "Added FS directory: " << file;
244
						add_source(file.c_str());
245
					}
246
					continue;
247
				}
248
249
				add_source(l.c_str());
			}
250
251
252
253
254
		}

		_reload_dispatchers();
	}

255
256
	Asset_manager::~Asset_manager()
	{
257
258
		_containers.clear();
		if(!PHYSFS_deinit()) {
259
260
			MIRRAGE_FAIL(
			        "Unable to shutdown PhysicsFS: " << PHYSFS_getErrorByCode((PHYSFS_getLastErrorCode())));
261
		}
262
263
	}

264
265
	void Asset_manager::reload()
	{
266
		_reload_dispatchers();
267

268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
		// The container lock must not be held during reload, because the reload of an asset calls
		//   third-party code that might call into the asset_manager.
		// So we first collect all relevant containers and then iterate over that list.
		auto containers = std::vector<detail::Asset_container_base*>();
		{
			auto lock = std::scoped_lock{_containers_mutex};
			containers.reserve(_containers.size());

			for(auto& container : _containers) {
				containers.emplace_back(container.second.get());
			}
		}

		for(auto& c : containers) {
			c->reload();
283
284
		}
	}
285
286
	void Asset_manager::shrink_to_fit() noexcept
	{
287
		auto lock = std::scoped_lock{_containers_mutex};
288

289
290
291
		for(auto& container : _containers) {
			container.second->shrink_to_fit();
		}
292
293
	}

294
295
	auto Asset_manager::exists(const AID& id) const noexcept -> bool
	{
296
297
		return resolve(id).process(false, [](auto&& path) { return exists_file(path); });
	}
298
299
	auto Asset_manager::try_delete(const AID& id) -> bool
	{
300
		return resolve(id).process(true, [](auto&& path) { return PHYSFS_delete(path.c_str()) == 0; });
301
	}
302

303
304
	auto Asset_manager::open(const AID& id) -> util::maybe<istream>
	{
305
306
307
308
309
		auto path = resolve(id);

		if(path.is_some() && exists_file(path.get_or_throw()))
			return _open(id, path.get_or_throw());
		else
310
			return util::nothing;
311
	}
312
313
	auto Asset_manager::open_rw(const AID& id) -> ostream
	{
314
315
316
317
318
319
		auto path = resolve(id);
		if(path.is_nothing()) {
			path = resolve(AID{id.type(), ""}).process(id.str(), [&](auto&& prefix) {
				return append_file(prefix, id.str());
			});
		};
320

321
322
323
324
		if(exists_file(path.get_or_throw()))
			PHYSFS_delete(path.get_or_throw().c_str());

		return _open_rw(id, path.get_or_throw());
325
326
	}

327
328
	auto Asset_manager::list(Asset_type type) -> std::vector<AID>
	{
329
330
		auto lock = std::shared_lock{_dispatchers_mutex};

331
332
		std::vector<AID> res;

333
		for(auto& d : _dispatchers) {
334
			if(d.first.type() == type && d.first.name().size() > 0)
335
336
337
				res.emplace_back(d.first);
		}

338
		_base_dir(type).process([&](const std::string& dir) {
339
340
341
342
343
344
345
346
347
			for(auto&& f : list_files(dir, "", ""))
				res.emplace_back(type, f);
		});

		sort(res.begin(), res.end());
		res.erase(std::unique(res.begin(), res.end()), res.end());

		return res;
	}
348
349
	auto Asset_manager::last_modified(const AID& id) const noexcept -> util::maybe<std::int64_t>
	{
350
		using namespace std::literals;
351

352
		return resolve(id).process([&](auto& path) { return _last_modified(path); });
353
354
	}

355
	auto Asset_manager::resolve(const AID& id, bool only_preexisting) const noexcept
356
357
	        -> util::maybe<std::string>
	{
358
		auto lock = std::shared_lock{_dispatchers_mutex};
359

360
		auto res = _dispatchers.find(id);
361

362
		if(res != _dispatchers.end() && (exists_file(res->second) || !only_preexisting))
363
			return res->second;
364

365
366
		else if(exists_file(id.name()))
			return id.name();
367
368
369
370
371
372
373


		auto baseDir = _base_dir(id.type());

		if(baseDir.is_some()) {
			auto path = append_file(baseDir.get_or_throw(), id.name());
			if(exists_file(path))
374
				return std::move(path);
375
376
377
378
379
380
381
382
383

			else if(!only_preexisting) {
				PHYSFS_mkdir(baseDir.get_or_throw().c_str());
				return std::move(path);
			}
		}

		if(!only_preexisting) {
			return id.name();
384
385
		}

386
		return util::nothing;
387
	}
388
389
	auto Asset_manager::resolve_reverse(std::string_view path) -> util::maybe<AID>
	{
390
		auto lock = std::shared_lock{_dispatchers_mutex};
391

392
393
394
		for(auto& e : _dispatchers) {
			if(e.second == path)
				return e.first;
395
396
		}

397
		return util::nothing;
398
399
	}

400
	void Asset_manager::_post_write() {}
401

402
403
	auto Asset_manager::_base_dir(Asset_type type) const -> util::maybe<std::string>
	{
404
		auto lock = std::shared_lock{_dispatchers_mutex};
405

406
		auto dir = _dispatchers.find(AID{type, ""}); // search for prefix-entry
407

408
		if(dir == _dispatchers.end())
409
410
			return util::nothing;

411
412
		std::string bdir = dir->second;
		return bdir;
413
414
	}

415
416
	void Asset_manager::_reload_dispatchers()
	{
417
		auto lock = std::unique_lock{_dispatchers_mutex};
418

419
		_dispatchers.clear();
420

421
		for(auto&& df : list_files("", "assets", ".map")) {
422
			LOG(plog::info) << "Added asset mapping: " << df;
423
424
425
426
427
428
			auto in = _open({}, df);
			for(auto&& l : in.lines()) {
				auto        kvp  = util::split(l, "=");
				std::string path = util::trim_copy(kvp.second);
				if(!path.empty()) {
					_dispatchers.emplace(AID{kvp.first}, std::move(path));
429
430
431
432
433
				}
			}
		}
	}

434
435
	auto Asset_manager::_last_modified(const std::string& path) const -> int64_t
	{
436
		auto stat = PHYSFS_Stat{};
437
438
		if(!PHYSFS_stat(path.c_str(), &stat))
			throw std::system_error(static_cast<Asset_error>(PHYSFS_getLastErrorCode()));
439

440
		return stat.modtime;
441
	}
442
443
	auto Asset_manager::_open(const asset::AID& id, const std::string& path) -> istream
	{
444
		return {id, *this, path};
445
	}
446
447
	auto Asset_manager::_open_rw(const asset::AID& id, const std::string& path) -> ostream
	{
448
		return {id, *this, path};
449
450
	}

451
} // namespace mirrage::asset