CSC3224_Computer_Games_Development / GameEngine / Engine_IO / EngineFileSystem.cpp
EngineFileSystem.cpp
Raw
#include "EngineFileSystem.h"

EngineFileSystem::EngineFileSystem() {}
EngineFileSystem::~EngineFileSystem() {}
// Read File
void EngineFileSystem::LoadingAssetsFromFile(EntityManagement& entityManagement, EnginePhysicsSystem& enginePhysicsSystem, ResourceManagement& resourceManagement, std::string filePath)
{
	auto root = ReadFileToJson(filePath);

	if (root.size() > 0)
	{ 
// Load Textures
		for (auto jsonValue : root["Textures"])
		{
			auto path = jsonValue.get("Path", "Unknown").asString();
			auto name = jsonValue.get("Identifier", path).asString();
			resourceManagement.loadTexture(name, path);
		}
// Load Audio
		for (auto jsonValue : root["Sounds"])
		{
			auto path = jsonValue.get("Path", "Unknown").asString();
			auto name = jsonValue.get("Identifier", path).asString();
			resourceManagement.loadSound(name, path);
		}
// Load Entities
		for (auto jsonValue : root["Entities"])
		{
			Entity::messageBuildFromJson(entityManagement, enginePhysicsSystem, jsonValue);
		}
	}
}
// Write to File
void EngineFileSystem::WriteEntitiesToFile(EntityManagement& entityManagement, std::string filePath, bool fileReadable)
{
	Json::Value value;
	auto maxNrOfEntities = entityManagement.getMaxEntityID();

	for (uint32_t i = 0; i < maxNrOfEntities; ++i)
	{
// Check for valid Entities
		auto Events = entityManagement.getMessageSystemEventType(i);
		if (Events)
		{
			Json::Value entityJson;
			for (auto checkEventType : *Events)
			{
				if (checkEventType->getType() == MessageSystemEventType::SPRITE_RECTANGLE_TYPE)
				{
// Look for Sprites
					entityJson["Sprite"] = checkEventType->convertToJson();
				}
				else
				{
// Look for Events					
					entityJson["Events"].append(checkEventType->convertToJson());
				}
			}
			value.append(entityJson);
		}
	}
// Open file
	std::ofstream outFile;
// Overwrite existing file
	outFile.open(filePath, std::ios::trunc);
// Write to string
	std::string string;
	if (fileReadable)
	{
		Json::StyledWriter styledWriter;
		string = styledWriter.write(value);
	}
	else
	{
		Json::FastWriter fastWriter;
		string = fastWriter.write(value);
	}
// Write to file
	outFile << string;
// Close file
	outFile.close();
}

Json::Value EngineFileSystem::ReadFileToJson(std::string jsonFilePath)
{
	std::ifstream inputStream(jsonFilePath);
	std::string keys((std::istreambuf_iterator<char>(inputStream)), (std::istreambuf_iterator<char>()));
// 
	Json::Value value;
	Json::Reader reader;
// Check for file
	if (!reader.parse(keys, value))
	{
		std::cout << "Failed to load file to Json" << std::endl;
	}
	return value;
}