Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : * This file is part of 0 A.D.
3 : *
4 : * 0 A.D. is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 2 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * 0 A.D. is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 : */
17 :
18 : #include "precompiled.h"
19 :
20 : #include "SavedGame.h"
21 :
22 : #include "graphics/GameView.h"
23 : #include "lib/allocators/shared_ptr.h"
24 : #include "lib/code_annotation.h"
25 : #include "lib/debug.h"
26 : #include "lib/file/archive/archive.h"
27 : #include "lib/file/archive/archive_zip.h"
28 : #include "lib/file/file_system.h"
29 : #include "lib/file/io/io.h"
30 : #include "lib/file/io/write_buffer.h"
31 : #include "lib/file/vfs/vfs.h"
32 : #include "lib/file/vfs/vfs_path.h"
33 : #include "lib/file/vfs/vfs_util.h"
34 : #include "lib/path.h"
35 : #include "lib/sysdep/filesystem.h"
36 : #include "maths/Vector3D.h"
37 : #include "ps/CLogger.h"
38 : #include "ps/CStr.h"
39 : #include "ps/Filesystem.h"
40 : #include "ps/Game.h"
41 : #include "ps/Mod.h"
42 : #include "ps/Profiler2.h"
43 : #include "ps/Pyrogenesis.h"
44 : #include "scriptinterface/JSON.h"
45 : #include "scriptinterface/Object.h"
46 : #include "scriptinterface/Conversions.h"
47 : #include "scriptinterface/Request.h"
48 : #include "scriptinterface/StructuredClone.h"
49 : #include "simulation2/Simulation2.h"
50 :
51 : #include <cstdint>
52 : #include <ctime>
53 : #include <filesystem>
54 : #include <js/RootingAPI.h>
55 : #include <js/TypeDecls.h>
56 : #include <memory>
57 : #include <sstream>
58 : #include <system_error>
59 : #include <utility>
60 :
61 : namespace Script { class Interface; }
62 :
63 : // TODO: we ought to check version numbers when loading files
64 :
65 0 : Status SavedGames::SavePrefix(const CStrW& prefix, const CStrW& description, CSimulation2& simulation, const Script::StructuredClone& guiMetadataClone)
66 : {
67 : // Determine the filename to save under
68 0 : const VfsPath basenameFormat(L"saves/" + prefix + L"-%04d");
69 0 : const VfsPath filenameFormat = basenameFormat.ChangeExtension(L".0adsave");
70 0 : VfsPath filename;
71 :
72 : // Don't make this a static global like NextNumberedFilename expects, because
73 : // that wouldn't work when 'prefix' changes, and because it's not thread-safe
74 0 : size_t nextSaveNumber = 0;
75 0 : vfs::NextNumberedFilename(g_VFS, filenameFormat, nextSaveNumber, filename);
76 :
77 0 : return Save(filename.Filename().string(), description, simulation, guiMetadataClone);
78 0 : }
79 :
80 0 : Status SavedGames::Save(const CStrW& name, const CStrW& description, CSimulation2& simulation, const Script::StructuredClone& guiMetadataClone)
81 : {
82 0 : Script::Request rq(simulation.GetScriptInterface());
83 :
84 : // Determine the filename to save under
85 0 : const VfsPath basenameFormat(L"saves/" + name);
86 0 : const VfsPath filename = basenameFormat.ChangeExtension(L".0adsave");
87 :
88 : // ArchiveWriter_Zip can only write to OsPaths, not VfsPaths,
89 : // but we'd like to handle saved games via VFS.
90 : // To avoid potential confusion from writing with non-VFS then
91 : // reading the same file with VFS, we'll just write to a temporary
92 : // non-VFS path and then load and save again via VFS,
93 : // which is kind of a hack.
94 :
95 0 : OsPath tempSaveFileRealPath;
96 0 : WARN_RETURN_STATUS_IF_ERR(g_VFS->GetDirectoryRealPath("cache/", tempSaveFileRealPath));
97 0 : tempSaveFileRealPath = tempSaveFileRealPath / "temp.0adsave";
98 :
99 0 : time_t now = time(NULL);
100 :
101 : // Construct the serialized state to be saved
102 :
103 0 : std::stringstream simStateStream;
104 0 : if (!simulation.SerializeState(simStateStream))
105 0 : WARN_RETURN(ERR::FAIL);
106 :
107 0 : JS::RootedValue initAttributes(rq.cx, simulation.GetInitAttributes());
108 0 : JS::RootedValue mods(rq.cx);
109 0 : Script::ToJSVal(rq, &mods, g_Mods.GetEnabledModsData());
110 :
111 0 : JS::RootedValue metadata(rq.cx);
112 :
113 0 : Script::CreateObject(
114 : rq,
115 : &metadata,
116 : "engine_version", PS_VERSION,
117 : "engine_serialization_version", PS_SERIALIZATION_VERSION,
118 0 : "time", static_cast<double>(now),
119 0 : "playerID", g_Game->GetPlayerID(),
120 : "mods", mods,
121 : "initAttributes", initAttributes);
122 :
123 0 : JS::RootedValue guiMetadata(rq.cx);
124 0 : Script::ReadStructuredClone(rq, guiMetadataClone, &guiMetadata);
125 :
126 : // get some camera data
127 0 : const CVector3D cameraPosition = g_Game->GetView()->GetCameraPosition();
128 0 : const CVector3D cameraRotation = g_Game->GetView()->GetCameraRotation();
129 :
130 0 : JS::RootedValue cameraMetadata(rq.cx);
131 :
132 0 : Script::CreateObject(
133 : rq,
134 : &cameraMetadata,
135 : "PosX", cameraPosition.X,
136 : "PosY", cameraPosition.Y,
137 : "PosZ", cameraPosition.Z,
138 : "RotX", cameraRotation.X,
139 : "RotY", cameraRotation.Y,
140 0 : "Zoom", g_Game->GetView()->GetCameraZoom());
141 :
142 0 : Script::SetProperty(rq, guiMetadata, "camera", cameraMetadata);
143 :
144 0 : Script::SetProperty(rq, metadata, "gui", guiMetadata);
145 0 : Script::SetProperty(rq, metadata, "description", description);
146 :
147 0 : std::string metadataString = Script::StringifyJSON(rq, &metadata, true);
148 :
149 : // Write the saved game as zip file containing the various components
150 0 : PIArchiveWriter archiveWriter = CreateArchiveWriter_Zip(tempSaveFileRealPath, false);
151 0 : if (!archiveWriter)
152 0 : WARN_RETURN(ERR::FAIL);
153 :
154 0 : WARN_RETURN_STATUS_IF_ERR(archiveWriter->AddMemory(reinterpret_cast<const std::uint8_t*>(
155 : metadataString.c_str()), metadataString.length(), now, "metadata.json"));
156 0 : WARN_RETURN_STATUS_IF_ERR(archiveWriter->AddMemory(reinterpret_cast<const std::uint8_t*>(
157 : simStateStream.str().c_str()), simStateStream.str().length(), now, "simulation.dat"));
158 0 : archiveWriter.reset(); // close the file
159 :
160 0 : WriteBuffer buffer;
161 0 : CFileInfo tempSaveFile;
162 0 : WARN_RETURN_STATUS_IF_ERR(GetFileInfo(tempSaveFileRealPath, &tempSaveFile));
163 0 : buffer.Reserve(tempSaveFile.Size());
164 0 : WARN_RETURN_STATUS_IF_ERR(io::Load(tempSaveFileRealPath, buffer.Data().get(), buffer.Size()));
165 0 : WARN_RETURN_STATUS_IF_ERR(g_VFS->CreateFile(filename, {buffer.Data().get(), buffer.Size()}));
166 :
167 0 : OsPath realPath;
168 0 : WARN_RETURN_STATUS_IF_ERR(g_VFS->GetRealPath(filename, realPath));
169 0 : LOGMESSAGERENDER("Saved game to '{}'", realPath.string8());
170 0 : debug_printf("Saved game to '%s'\n", realPath.string8().c_str());
171 :
172 0 : return INFO::OK;
173 0 : }
174 :
175 : /**
176 : * Helper class for retrieving data from saved game archives
177 : */
178 0 : class CGameLoader
179 : {
180 : NONCOPYABLE(CGameLoader);
181 : public:
182 :
183 : /**
184 : * @param scriptInterface the Script::Interface used for loading metadata.
185 : * @param[out] savedState serialized simulation state stored as string of bytes,
186 : * loaded from simulation.dat inside the archive.
187 : *
188 : * Note: We use a different approach for returning the string and the metadata JS::Value.
189 : * We use a pointer for the string to avoid copies (efficiency). We don't use this approach
190 : * for the metadata because it would be error prone with rooting and the stack-based rooting
191 : * types and confusing (a chain of pointers pointing to other pointers).
192 : */
193 0 : CGameLoader(const Script::Interface& scriptInterface, std::string* savedState) :
194 0 : m_ScriptInterface(scriptInterface),
195 0 : m_SavedState(savedState)
196 : {
197 0 : Script::Request rq(scriptInterface);
198 0 : m_Metadata.init(rq.cx);
199 0 : }
200 :
201 0 : static void ReadEntryCallback(const VfsPath& pathname, const CFileInfo& fileInfo, PIArchiveFile archiveFile, uintptr_t cbData)
202 : {
203 0 : ((CGameLoader*)cbData)->ReadEntry(pathname, fileInfo, archiveFile);
204 0 : }
205 :
206 0 : void ReadEntry(const VfsPath& pathname, const CFileInfo& fileInfo, PIArchiveFile archiveFile)
207 : {
208 0 : if (pathname == L"metadata.json")
209 : {
210 0 : std::string buffer;
211 0 : buffer.resize(fileInfo.Size());
212 0 : WARN_IF_ERR(archiveFile->Load("",
213 : {reinterpret_cast<std::uint8_t*>(buffer.data()), buffer.size()}));
214 0 : Script::ParseJSON(Script::Request(m_ScriptInterface), buffer, &m_Metadata);
215 0 : }
216 0 : else if (pathname == L"simulation.dat" && m_SavedState)
217 : {
218 0 : m_SavedState->resize(fileInfo.Size());
219 0 : WARN_IF_ERR(archiveFile->Load("",
220 : {reinterpret_cast<std::uint8_t*>(m_SavedState->data()), m_SavedState->size()}));
221 : }
222 0 : }
223 :
224 0 : JS::Value GetMetadata()
225 : {
226 0 : return m_Metadata.get();
227 : }
228 :
229 : private:
230 :
231 : const Script::Interface& m_ScriptInterface;
232 : JS::PersistentRooted<JS::Value> m_Metadata;
233 : std::string* m_SavedState;
234 : };
235 :
236 0 : std::optional<SavedGames::LoadResult> SavedGames::Load(const Script::Interface& scriptInterface,
237 : const std::wstring& name)
238 : {
239 : // Determine the filename to load
240 0 : const VfsPath basename(L"saves/" + name);
241 0 : const VfsPath filename = basename.ChangeExtension(L".0adsave");
242 :
243 : // Don't crash just because file isn't found, this can happen if the file is deleted from the OS
244 0 : if (!VfsFileExists(filename))
245 0 : return std::nullopt;
246 :
247 0 : OsPath realPath;
248 0 : {
249 0 : const Status status{g_VFS->GetRealPath(filename, realPath)};
250 0 : if (status < 0)
251 : {
252 0 : DEBUG_WARN_ERR(status);
253 0 : return std::nullopt;
254 : }
255 : }
256 :
257 0 : PIArchiveReader archiveReader = CreateArchiveReader_Zip(realPath);
258 0 : if (!archiveReader)
259 : {
260 0 : DEBUG_WARN_ERR(ERR::FAIL);
261 0 : return std::nullopt;
262 : }
263 :
264 0 : std::string savedState;
265 0 : CGameLoader loader(scriptInterface, &savedState);
266 0 : {
267 0 : const Status status{archiveReader->ReadEntries(CGameLoader::ReadEntryCallback,
268 : reinterpret_cast<uintptr_t>(&loader))};
269 0 : if (status < 0)
270 : {
271 0 : DEBUG_WARN_ERR(status);
272 0 : return std::nullopt;
273 : }
274 : }
275 0 : const Script::Request rq{scriptInterface};
276 0 : JS::RootedValue metadata{rq.cx, loader.GetMetadata()};
277 :
278 : // `std::make_optional` can't be used since `LoadResult` doesn't have a constructor.
279 0 : return {{metadata, std::move(savedState)}};
280 0 : }
281 :
282 0 : JS::Value SavedGames::GetSavedGames(const Script::Interface& scriptInterface)
283 : {
284 0 : PROFILE2("GetSavedGames");
285 0 : Script::Request rq(scriptInterface);
286 :
287 0 : JS::RootedValueVector games{rq.cx};
288 :
289 0 : Status err;
290 :
291 0 : VfsPaths pathnames;
292 0 : err = vfs::GetPathnames(g_VFS, "saves/", L"*.0adsave", pathnames);
293 0 : WARN_IF_ERR(err);
294 :
295 0 : for (const VfsPath& pathname : pathnames)
296 : {
297 0 : OsPath realPath;
298 0 : err = g_VFS->GetRealPath(pathname, realPath);
299 0 : if (err < 0)
300 : {
301 0 : DEBUG_WARN_ERR(err);
302 0 : continue; // skip this file
303 0 : }
304 :
305 0 : PIArchiveReader archiveReader = CreateArchiveReader_Zip(realPath);
306 0 : if (!archiveReader)
307 : {
308 : // Triggered by e.g. the file being open in another program
309 0 : LOGWARNING("Failed to read saved game '{}'", realPath.string8());
310 0 : continue; // skip this file
311 0 : }
312 :
313 0 : CGameLoader loader(scriptInterface, NULL);
314 0 : err = archiveReader->ReadEntries(CGameLoader::ReadEntryCallback, (uintptr_t)&loader);
315 0 : if (err < 0)
316 : {
317 0 : DEBUG_WARN_ERR(err);
318 0 : continue; // skip this file
319 0 : }
320 0 : JS::RootedValue metadata(rq.cx, loader.GetMetadata());
321 :
322 0 : JS::RootedValue game(rq.cx);
323 0 : Script::CreateObject(
324 : rq,
325 : &game,
326 0 : "id", pathname.Basename(),
327 : "metadata", metadata);
328 :
329 0 : if (!games.append(game))
330 0 : throw std::runtime_error{"Append failed"};
331 0 : }
332 :
333 0 : return JS::ObjectValue(*JS::NewArrayObject(rq.cx, games));
334 0 : }
335 :
336 0 : bool SavedGames::DeleteSavedGame(const std::wstring& name)
337 : {
338 0 : const VfsPath basename(L"saves/" + name);
339 0 : const VfsPath filename = basename.ChangeExtension(L".0adsave");
340 0 : OsPath realpath;
341 :
342 : // Make sure it exists in VFS and find its path
343 0 : if (!VfsFileExists(filename) || g_VFS->GetOriginalPath(filename, realpath) != INFO::OK)
344 0 : return false; // Error
345 :
346 : // Remove from VFS
347 0 : if (g_VFS->RemoveFile(filename) != INFO::OK)
348 : return false; // Error
349 :
350 : // Delete actual file
351 0 : std::error_code ec{};
352 0 : std::filesystem::remove(realpath.string(), ec);
353 0 : if (ec)
354 : return false; // Error
355 :
356 : // Successfully deleted file
357 : return true;
358 0 : }
|