aboutsummaryrefslogtreecommitdiff
path: root/source/Ires.cpp
blob: f60fcb7599939b81ea3504f4ddd580f652cf0261 (plain)
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
#include "Ires.hpp"

#include "AppConfig.hpp"
#include "EditorCore.hpp"
#include "EditorUtils.hpp"
#include "Macros.hpp"
#include "Material.hpp"
#include "RapidJsonHelper.hpp"
#include "ScopeGuard.hpp"
#include "Shader.hpp"
#include "Sprite.hpp"
#include "Texture.hpp"
#include "Utils.hpp"

#include <imgui.h>
#include <misc/cpp/imgui_stdlib.h>
#include <rapidjson/document.h>
#include <rapidjson/filereadstream.h>
#include <rapidjson/filewritestream.h>
#include <rapidjson/prettywriter.h>
#include <rapidjson/writer.h>
#include <algorithm>
#include <cassert>

namespace fs = std::filesystem;
using namespace std::literals;

IresObject::IresObject(Kind kind)
	: mKind{ kind } {
}

std::string_view IresObject::ToString(Kind kind) {
	switch (kind) {
		case KD_Texture: return BRUSSEL_TAG_PREFIX_Ires "Texture"sv;
		case KD_Shader: return BRUSSEL_TAG_PREFIX_Ires "Shader"sv;
		case KD_Material: return BRUSSEL_TAG_PREFIX_Ires "Material"sv;
		case KD_SpriteFiles: return BRUSSEL_TAG_PREFIX_Ires "SpriteFiles"sv;
		case KD_Spritesheet: return BRUSSEL_TAG_PREFIX_Ires "Spritesheet"sv;
		case KD_COUNT: break;
	}
	return std::string_view();
}

IresObject::Kind IresObject::FromString(std::string_view name) {
	if (name == BRUSSEL_TAG_PREFIX_Ires "Texture"sv) return KD_Texture;
	if (name == BRUSSEL_TAG_PREFIX_Ires "Shader"sv) return KD_Shader;
	if (name == BRUSSEL_TAG_PREFIX_Ires "Material"sv) return KD_Material;
	if (name == BRUSSEL_TAG_PREFIX_Ires "SpriteFiles"sv) return KD_SpriteFiles;
	if (name == BRUSSEL_TAG_PREFIX_Ires "Spritesheet"sv) return KD_Spritesheet;
	return KD_COUNT;
}

std::unique_ptr<IresObject> IresObject::Create(Kind kind) {
	switch (kind) {
		case KD_Texture: return std::make_unique<IresTexture>();
		case KD_Shader: return std::make_unique<IresShader>();
		case KD_Material: return std::make_unique<IresMaterial>();
		case KD_SpriteFiles: return std::make_unique<IresSpriteFiles>();
		case KD_Spritesheet: return std::make_unique<IresSpritesheet>();
		case KD_COUNT: break;
	}
	return nullptr;
}

bool IresObject::IsAnnoymous() const {
	return mName.empty();
}

void IresObject::SetName(std::string name) {
	if (mMan) {
		mMan->Rename(this, std::move(name));
	} else {
		mName = std::move(name);
	}
}

void IresObject::ShowNullName(EditorInstance& editor, Kind kind) {
	ImGui::Text("<null>");
}

void IresObject::ShowName() const {
	if (IsAnnoymous()) {
		ImGui::Text("<annoymous %p>", (void*)this);
	} else {
		ImGui::Text("%s", mName.c_str());
	}
}

void IresObject::ShowFullName() const {
	if (IsAnnoymous()) {
		ImGui::Text("<annoymous %p> (%lx-%lx)", (void*)this, mUid.upper, mUid.lower);
	} else {
		ImGui::Text("%s (%lx-%lx)", mName.c_str(), mUid.upper, mUid.lower);
	}
}

void IresObject::ShowNullReference(EditorInstance& editor, Kind kind) {
	ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyle().Colors[ImGuiCol_ButtonHovered]);
	ImGui::Text("<null>");
	ImGui::PopStyleColor();
	ImGui::AddUnderLine(ImGui::GetStyle().Colors[ImGuiCol_Button]);
}

void IresObject::ShowReference(EditorInstance& editor) {
	ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyle().Colors[ImGuiCol_ButtonHovered]);
	if (IsAnnoymous()) {
		ImGui::Text("<annoymous %p>", (void*)this);
	} else {
		ImGui::Text("%s", mName.c_str());
	}
	ImGui::PopStyleColor();
	if (ImGui::IsItemHovered()) {
		if (ImGui::IsMouseClicked(ImGuiMouseButton_Left)) {
			editor.GetInspector().SelectTarget(EditorInspector::ITT_Ires, this);
		}
		ImGui::AddUnderLine(ImGui::GetStyle().Colors[ImGuiCol_ButtonHovered]);
	} else {
		ImGui::AddUnderLine(ImGui::GetStyle().Colors[ImGuiCol_Button]);
	}
}

void IresObject::ShowEditor(EditorInstance& editor) {
	ImGui::Text("%s", ToString(mKind).data());

	bool isAnnoymous = mName.empty();
	if (isAnnoymous) {
		ImGui::Text("Name: <annoymous: %p>", (void*)this);
	} else {
		ImGui::Text("Name: %s", mName.c_str());
	}

	if (mUid.IsNull()) {
		ImGui::TextUnformatted("Uid: <none>");
	} else {
		ImGui::Text("Uid: %lx-%lx", mUid.upper, mUid.lower);
	}
}

void IresObject::WriteFull(IresWritingContext& ctx, IresObject* ires, rapidjson::Value& value, rapidjson::Document& root) {
	rapidjson::Value rvIres(rapidjson::kObjectType);
	ires->Write(ctx, rvIres, root);

	value.AddMember("Type", rapidjson::StringRef(ToString(ires->GetKind())), root.GetAllocator());
	value.AddMember("Uid", ires->mUid.Write(root), root.GetAllocator());
	value.AddMember("Value", rvIres, root.GetAllocator());
}

std::unique_ptr<IresObject> IresObject::ReadFull(IresLoadingContext& ctx, const rapidjson::Value& value) {
	auto ires = ReadBasic(value);
	if (!ires) {
		return nullptr;
	}

	if (!ReadPartial(ctx, ires.get(), value)) {
		return nullptr;
	}

	return ires;
}

std::unique_ptr<IresObject> IresObject::ReadBasic(const rapidjson::Value& value) {
	auto rvType = rapidjson::GetProperty(value, rapidjson::kStringType, "Type"sv);
	if (!rvType) return nullptr;
	auto kind = FromString(rapidjson::AsStringView(*rvType));
	auto ires = Create(kind);
	if (!ires) return nullptr;

	auto rvUid = rapidjson::GetProperty(value, rapidjson::kArrayType, "Uid"sv);
	if (!rvUid) return nullptr;
	ires->mUid.Read(*rvUid);

	return ires;
}

bool IresObject::ReadPartial(IresLoadingContext& ctx, IresObject* ires, const rapidjson::Value& value) {
	auto rvValue = rapidjson::GetProperty(value, "Value"sv);
	if (!rvValue) return false;
	ires->Read(ctx, *rvValue);
	return true;
}

void IresObject::Write(IresWritingContext& ctx, rapidjson::Value& value, rapidjson::Document& root) const {
}

void IresObject::Read(IresLoadingContext& ctx, const rapidjson::Value& value) {
}

void IresManager::DiscoverFilesDesignatedLocation() {
	auto path = AppConfig::assetDirPath / "Ires";
	DiscoverFiles(path);
}

void IresManager::DiscoverFiles(const fs::path& dir) {
	struct LoadCandidate {
		fs::path path;
		rapidjson::Document data;
		RcPtr<IresObject> ires;
	};

	class IresLoadTimeContext final : public IresLoadingContext {
	public:
		// NOTE: pointer stability required
		robin_hood::unordered_node_map<Uid, LoadCandidate> candidates;
		std::vector<std::vector<LoadCandidate*>> candidatesByKind;

		IresLoadTimeContext() {
			candidatesByKind.resize(IresObject::KD_COUNT);
		}

		std::vector<LoadCandidate*>& GetByKind(IresObject::Kind kind) {
			int i = static_cast<int>(kind);
			return candidatesByKind[i];
		}

		virtual IresObject* FindIres(const Uid& uid) const override {
			auto iter = candidates.find(uid);
			if (iter != candidates.end()) {
				auto& cand = iter->second;
				return cand.ires.Get();
			} else {
				return nullptr;
			}
		}
	} ctx;

	for (auto& item : fs::directory_iterator(dir)) {
		if (!item.is_regular_file()) {
			continue;
		}
		if (item.path().extension() != ".json") {
			continue;
		}

		auto file = Utils::OpenCstdioFile(item.path(), Utils::Read);
		if (!file) {
			fprintf(stderr, "Ires file [" PLATFORM_PATH_STR "] Failed to open file.", item.path().c_str());
			continue;
		}
		DEFER { fclose(file); };

		char readerBuffer[65536];
		rapidjson::FileReadStream stream(file, readerBuffer, sizeof(readerBuffer));

		rapidjson::Document root;
		root.ParseStream(stream);

		auto ires = IresObject::ReadBasic(root);
		if (!ires) {
			fprintf(stderr, "Ires file: [" PLATFORM_PATH_STR "] Failed to parse header.", item.path().c_str());
			continue;
		}

		// Load name from filename
		ires->mName = item.path().filename().replace_extension().string();
		auto& iresName = ires->mName;

		// Load uid should be handled by IresObject::ReadBasic
		assert(!ires->mUid.IsNull());
		auto iresUid = ires->GetUid();

		auto iresKind = ires->GetKind();

		auto&& [iter, DISCARD] = ctx.candidates.try_emplace(
			iresUid,
			LoadCandidate{
				.path = item.path(),
				.data = std::move(root),
				.ires = RcPtr(ires.release()),
			});
		auto& cand = iter->second;

		ctx.GetByKind(iresKind).push_back(&cand);
	}

	// Load Ires in order by type, there are dependencies between them
	// TODO full arbitary dependency between Ires
	for (int i = 0; i < IresObject::KD_COUNT; ++i) {
		auto kind = static_cast<IresObject::Kind>(i);
		auto& list = ctx.GetByKind(kind);
		for (auto cand : list) {
			auto& ires = cand->ires;

			if (!IresObject::ReadPartial(ctx, ires.Get(), cand->data)) {
				fprintf(stderr, "Ires file: [" PLATFORM_PATH_STR "] Failed to parse object data.", cand->path.c_str());
				continue;
			}

			ires->mMan = this;
			mObjByUid.try_emplace(ires->GetUid(), ires);
		}
	}
}

std::pair<IresObject*, bool> IresManager::Add(IresObject* ires) {
	auto& name = ires->mName;
	if (name.empty()) {
		int n = std::rand();
		// NOTE: does not include null-terminator
		int size = snprintf(nullptr, 0, "Unnamed %s #%d", IresObject::ToString(ires->GetKind()).data(), n);
		name.resize(size); // std::string::resize handles storage for null-terminator alreaedy
		snprintf(name.data(), size, "Unnamed %s #%d", IresObject::ToString(ires->GetKind()).data(), n);
	}

	auto& uid = ires->mUid;
	if (uid.IsNull()) {
		uid = Uid::Create();
	}

	auto [iter, inserted] = mObjByUid.try_emplace(uid, ires);
	if (inserted) {
		ires->mMan = this;
		// TODO handle full path
		return { ires, true };
	} else {
		return { iter->second.Get(), false };
	}
}

IresObject* IresManager::Load(const fs::path& filePath) {
	auto file = Utils::OpenCstdioFile(filePath, Utils::Read);
	if (!file) return nullptr;
	DEFER { fclose(file); };

	char readerBuffer[65536];
	rapidjson::FileReadStream stream(file, readerBuffer, sizeof(readerBuffer));

	rapidjson::Document root;
	root.ParseStream(stream);

	auto ires = IresObject::ReadFull(*this, root);
	if (!ires) {
		return nullptr;
	}

	// Load uid should be handled by IresObject::ReadFull
	assert(!ires->mUid.IsNull());
	// Load name from filename
	ires->mName = filePath.filename().replace_extension().string();
	Add(ires.get());

	return ires.release();
}

static fs::path GetDesignatedPath(IresObject* ires) {
	return AppConfig::assetDirPath / "Ires" / fs::path(ires->GetName()).replace_extension(".json");
}

void IresManager::Delete(IresObject* ires) {
	// TODO
}

bool IresManager::Rename(IresObject* ires, std::string newName) {
	auto oldPath = GetDesignatedPath(ires);
	ires->mName = std::move(newName);
	auto newPath = GetDesignatedPath(ires);
	if (fs::exists(oldPath)) {
		fs::rename(oldPath, newPath);
	}

	// TODO validate no name duplication
#if 0
	if (mObjByPath.contains(newName)) {
		return false;
	}

	// Keep the material from being deleted, in case the old entry in map is the only one existing
	RcPtr rc(ires);

	// Remove old entry (must do before replacing Material::mName, because the std::string_view in the map is a reference to it)
	mObjByPath.erase(ires->GetName());

	// Add new entry
	ires->mName = std::move(newName);
	// TODO handle full path
	mObjByPath.try_emplace(ires->GetName(), ires);
#endif
	return true;
}

void IresManager::Reload(IresObject* ires) {
	auto file = Utils::OpenCstdioFile(GetDesignatedPath(ires), Utils::Read);
	if (!file) return;
	DEFER { fclose(file); };

	char readerBuffer[65536];
	rapidjson::FileReadStream stream(file, readerBuffer, sizeof(readerBuffer));

	rapidjson::Document root;
	root.ParseStream(stream);

	IresObject::ReadPartial(*this, ires, root);
}

void IresManager::Save(IresObject* ires) {
	Save(ires, GetDesignatedPath(ires));
}

void IresManager::Save(IresObject* ires, const fs::path& filePath) {
	rapidjson::Document root(rapidjson::kObjectType);

	IresObject::WriteFull(*this, ires, root, root);

	auto file = Utils::OpenCstdioFile(filePath, Utils::WriteTruncate);
	if (!file) return;
	DEFER { fclose(file); };

	char writerBuffer[65536];
	rapidjson::FileWriteStream stream(file, writerBuffer, sizeof(writerBuffer));
	rapidjson::PrettyWriter<rapidjson::FileWriteStream> writer(stream);
	writer.SetFormatOptions(rapidjson::PrettyFormatOptions::kFormatSingleLineArray);
	root.Accept(writer);
}

IresObject* IresManager::FindIres(const Uid& uid) const {
	auto iter = mObjByUid.find(uid);
	if (iter != mObjByUid.end()) {
		return iter->second.Get();
	} else {
		return nullptr;
	}
}