添加 Components 和 Scene 序列化支持

- Component: 添加 Serialize/Deserialize 虚函数
- TransformComponent: 实现 Transform 数据的序列化/反序列化
- GameObject: 实现对象序列化/反序列化
- Scene: 实现 Save/Load 方法,支持场景文件保存和加载
- 测试: 添加 Save_And_Load 和 Save_ContainsGameObjectData 测试
This commit is contained in:
2026-03-22 03:42:40 +08:00
parent a9d5a68dd6
commit 70571d11df
10 changed files with 189 additions and 15 deletions

View File

@@ -1,5 +1,6 @@
#include "Scene/Scene.h"
#include "Components/GameObject.h"
#include <sstream>
namespace XCEngine {
namespace Components {
@@ -141,11 +142,53 @@ void Scene::LateUpdate(float deltaTime) {
}
void Scene::Load(const std::string& filePath) {
std::ifstream file(filePath);
if (!file.is_open()) {
return;
}
m_gameObjects.clear();
m_rootGameObjects.clear();
m_gameObjectIDs.clear();
std::string line;
while (std::getline(file, line)) {
if (line.empty() || line[0] == '#') continue;
std::istringstream iss(line);
std::string token;
std::getline(iss, token, '=');
if (token == "scene") {
std::getline(iss, m_name, ';');
} else if (token == "gameobject") {
auto go = std::make_unique<GameObject>();
go->Deserialize(iss);
go->m_scene = this;
GameObject* ptr = go.get();
GameObject::GetGlobalRegistry()[ptr->m_id] = ptr;
m_gameObjectIDs.insert(ptr->m_id);
m_rootGameObjects.push_back(ptr->m_id);
m_gameObjects.emplace(ptr->m_id, std::move(go));
}
}
}
void Scene::Save(const std::string& filePath) {
std::ofstream file(filePath);
if (!file.is_open()) {
return;
}
file << "# XCEngine Scene File\n";
file << "scene=" << m_name << ";\n";
file << "active=" << (m_active ? "1" : "0") << ";\n\n";
for (auto* go : GetRootGameObjects()) {
file << "gameobject=";
go->Serialize(file);
file << "\n";
}
}
} // namespace Components