游戏客户端架构 / 系统课时
序列化场景数据
序列化场景数据
本课将把内存中的场景对象保存为 JSON,并在重新读取后恢复对象属性与父子关系。重点不是简单输出字段,而是划清可持久化数据、运行时状态和对象引用之间的边界。
学习目标
- 设计包含对象、组件属性和层级关系的场景格式。
- 使用稳定 ID 保存并恢复父子引用。
- 通过版本字段和校验规则控制场景数据演进。
序列化边界与数据形态
场景在内存中通常是对象树,但文件更适合保存为扁平对象数组:每个对象拥有唯一 id,并用 parentId 指向父对象。这样既便于查找和版本迁移,也避免直接保存内存地址。

应保存名称、变换、组件参数和资源标识等稳定数据;对象指针、文件句柄、渲染缓存和 GPU 资源不能直接序列化。对于纹理或音频,只保存资源 ID 或相对路径,加载场景时再交给资源管理器解析。
保存与恢复场景
下面的完整示例创建两个对象,写入 scene.json,随后重新读取文件,并通过 parentId 找回 Player 的父对象。示例同样依赖 nlohmann/json.hpp。
cpp
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <vector>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
struct Transform {
float x{};
float y{};
};
struct Entity {
std::string id;
std::string name;
std::string parentId;
Transform transform;
};
void to_json(json& value, const Transform& transform) {
value = {{"x", transform.x}, {"y", transform.y}};
}
void from_json(const json& value, Transform& transform) {
value.at("x").get_to(transform.x);
value.at("y").get_to(transform.y);
}
void to_json(json& value, const Entity& entity) {
value = {
{"id", entity.id},
{"name", entity.name},
{"parentId", entity.parentId},
{"transform", entity.transform}
};
}
void from_json(const json& value, Entity& entity) {
value.at("id").get_to(entity.id);
value.at("name").get_to(entity.name);
value.at("parentId").get_to(entity.parentId);
value.at("transform").get_to(entity.transform);
}
json serializeScene(const std::vector<Entity>& entities) {
return {{"version", 1}, {"objects", entities}};
}
std::vector<Entity> deserializeScene(const json& document) {
if (document.at("version").get<int>() != 1) {
throw std::runtime_error("unsupported scene version");
}
return document.at("objects").get<std::vector<Entity>>();
}
int main() {
try {
const std::vector<Entity> scene = {
{"root", "Root", "", {0, 0}},
{"player", "Player", "root", {10, 4}}
};
const json document = serializeScene(scene);
std::ofstream output("scene.json");
output << document.dump(2);
output.close();
std::ifstream input("scene.json");
json loadedDocument;
input >> loadedDocument;
auto loaded = deserializeScene(loadedDocument);
// 第一遍建立稳定 ID 索引,第二遍才能安全解析对象引用。
std::unordered_map<std::string, Entity*> byId;
for (auto& entity : loaded) {
byId.emplace(entity.id, &entity);
}
const Entity& player = *byId.at("player");
const Entity& parent = *byId.at(player.parentId);
std::cout << "Saved scene: " << loaded.size() << " objects\n";
std::cout << "Player parent: " << parent.name << '\n';
std::cout << "Player position=(" << player.transform.x
<< ", " << player.transform.y << ")\n";
return 0;
} catch (const std::exception& error) {
std::cerr << "Scene error: " << error.what() << '\n';
return 1;
}
}编译并运行:
bash
g++ -std=c++17 main.cpp -o scene_serializer
./scene_serializer预期输出:
text
Saved scene: 2 objects
Player parent: Root
Player position=(10, 4)运行后会生成 scene.json。再次启动程序时,数据先恢复为对象数组,再通过稳定 ID 索引重建父子引用;这比保存裸指针可靠,因为内存地址每次运行都可能不同。
版本与引用处理
version 用于识别文件格式。新增字段时可以提供默认值;重命名或拆分字段时应编写迁移逻辑;遇到不支持的版本则应明确拒绝加载,不能静默误读。
恢复层级时应先创建全部对象,再统一解析 parentId。正式实现还要检查重复 ID、缺失父对象和循环引用。若一个对象引用纹理、脚本或预制体,应保存资源 ID,并在场景对象创建完成后交给资源管理器解析。
本课总结
- 场景文件应保存稳定数据与资源标识,不保存指针、句柄和运行时缓存。
- 使用唯一
id与parentId可以在反序列化后可靠重建对象层级。 - 版本检查、重复 ID 检查和引用完整性校验是场景格式长期可维护的关键。
下一课预告
下一课将继续完善资源管理流程,讨论资源依赖、加载顺序以及场景切换时如何避免重复加载和悬空引用。
按自己的节奏,确认真正理解。