Debian Codegraph @

CorsixTH/Lua/persistance.lua

raw
1 --[[ Copyright (c) 2010 Peter "Corsix" Cawley
2
3 Permission is hereby granted, free of charge, to any person obtaining a copy of
4 this software and associated documentation files (the "Software"), to deal in
5 the Software without restriction, including without limitation the rights to
6 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
7 of the Software, and to permit persons to whom the Software is furnished to do
8 so, subject to the following conditions:
9
10 The above copyright notice and this permission notice shall be included in all
11 copies or substantial portions of the Software.
12
13 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 SOFTWARE. --]]
20
21 local persist = require("persist")
22 local saved_permanents = {}
23
24 strict_declare_global "permanent"
25 strict_declare_global "unpermanent"
26
27 local th_getfenv
28 local th_getupvalue -- luacheck: ignore 231
29 if _G._VERSION == "Lua 5.1" then
30 th_getfenv = debug.getfenv
31 th_getupvalue = debug.getupvalue
32 else
33 th_getfenv = function(f)
34 local _, val = nil, nil
35 if type(f) == "function" then
36 _, val = debug.getupvalue(f, 1)
37 elseif type(f) == "userdata" then
38 val = debug.getuservalue(f)
39 else
40 print('Unhandled argument to th_getfenv')
41 end
42 return val
43 end
44
45 th_getupvalue = function(f, n)
46 return debug.getupvalue(f, n + 1)
47 end
48 end
49
50 function permanent(name, ...)
51 if select('#', ...) == 0 then
52 return function (...) return permanent(name, ...) end
53 end
54 local value = ...
55 assert(value ~= nil)
56 assert(saved_permanents[name] == nil)
57 saved_permanents[name] = value
58 return value
59 end
60
61 function unpermanent(name)
62 assert(saved_permanents[name] ~= nil)
63 saved_permanents[name] = nil
64 end
65
66 local --[[persistable:persistance_global_fetch]] function global_fetch(...)
67 local val = _G
68 for _, k in ipairs({...}) do
69 val = val[k]
70 end
71 return val
72 end
73
74 local function MakePermanentObjectsTable(inverted)
75 local return_val = setmetatable({}, {})
76 local permanent = return_val
77 if inverted then
78 getmetatable(permanent).__newindex = function(t, k, v)
79 rawset(t, v, k)
80 end
81 end
82
83 -- Global functions
84 for k, v in pairs(_G) do
85 if type(v) == "function" then
86 permanent[v] = k
87 end
88 end
89
90 -- Lua class methods
91 for name, class in pairs(_G) do repeat
92 if type(class) ~= "table" then
93 break -- continue
94 end
95 local class_mt = getmetatable(class)
96 if not class_mt or class_mt.__class_name ~= name then
97 break -- continue
98 end
99 permanent[class] = name .. ".1"
100 permanent[class_mt] = name .. ".2"
101 for k, v in pairs(class) do
102 if type(v) == "function" then
103 permanent[v] = name .. "." .. k
104 end
105 end
106 for k, v in pairs(class._metatable) do
107 if type(v) == "function" then
108 permanent[v] = name .. "._metatable." .. k
109 end
110 end
111 until true end
112
113 -- C/class/library methods
114 for name, lib in pairs(package.loaded) do
115 if not name:find(".", 1, true) then
116 permanent[lib] = name
117 end
118 if type(lib) == "table" then
119 for k, v in pairs(lib) do
120 local type_of_lib = type(v)
121 if type_of_lib == "function" or type_of_lib == "table" or type_of_lib == "userdata" then
122 permanent[v] = name .. "." .. k
123 if name == "TH" and type_of_lib == "table" then
124 -- C class metatables
125 local callenv = th_getfenv(getmetatable(v).__call)
126 permanent[callenv] = name .. "." .. k .. ".<mt>"
127 end
128 end
129 end
130 else
131 print("Warning: Expected table but got " .. type(lib) .. ". A library probably failed to load.")
132 end
133 end
134
135 -- Bits of the app
136 permanent[TheApp] = "TheApp"
137 for _, key in ipairs({"config", "modes", "video", "strings", "audio", "gfx", "fs", "moviePlayer"}) do
138 permanent[TheApp[key]] = inverted and "TheApp." .. key or {global_fetch, "TheApp", key}
139 end
140 for _, collection in ipairs({"walls", "objects", "rooms", "humanoid_actions", "diseases"}) do
141 for k, v in pairs(TheApp[collection]) do
142 if type(k) == "string" then
143 permanent[v] = inverted and "TheApp." .. collection .. "." .. k or {global_fetch, "TheApp", collection, k}
144 end
145 end
146 end
147 -- If loading a game from the main menu, there will be no menu bar, so make one
148 local menu_bar = TheApp.ui and TheApp.ui.menu_bar
149 if not menu_bar then
150 -- The menu bar wants a UI, but it is happy with just something naming an App
151 menu_bar = UIMenuBar({app = TheApp})
152 end
153 permanent[menu_bar] = "TheApp.ui.menu_bar"
154
155 -- Graphics bits are persisted as instructions to reload them or reuse if already loaded
156 if inverted then
157 -- as the object was persisted as a table, we need to add some magic to
158 -- the __index metamethod to interpret this table as a function call
159 getmetatable(return_val).__index = function(_, k)
160 if type(k) == "table" then
161 return k[1](unpack(k, 2))
162 end
163 end
164 else
165 -- load_info is a table containing a method and parameters to load obj
166 pause_gc_and_use_weak_keys(function(p)
167 for obj, load_info in pairs(TheApp.gfx.load_info) do
168 p[obj] = load_info
169 end
170 end, permanent)
171 end
172
173 -- Things requested to be permanent by other bits of code
174 for name, value in pairs(saved_permanents) do
175 permanent[value] = name
176 end
177
178 return return_val
179 end
180
181 local function NameOf(obj) -- Debug aid
182 local explored = {[_G] = true}
183 local to_explore = {[_G] = "_G"}
184
185 while true do
186 local exploring, name = next(to_explore)
187 if exploring == nil then
188 break
189 end
190 to_explore[exploring] = nil
191 if exploring == obj then
192 return name
193 end
194
195 if type(exploring) == "table" then
196 for key, val in pairs(exploring) do
197 if not explored[val] then
198 to_explore[val] = name .. "." ..tostring(key)
199 explored[val] = true
200 end
201 end
202 elseif type(exploring) == "function" then
203 local i = 0
204 while true do
205 i = i + 1
206 local dbg_name, val = debug.getupvalue(exploring, i)
207 if not dbg_name then
208 break
209 end
210 if val ~= nil and not explored[val] then
211 to_explore[val] = name .. ".<upvalue-" .. i .. tostring(name) .. ">"
212 explored[val] = true
213 end
214 end
215 end
216 local mt = debug.getmetatable(exploring)
217 if mt and not explored[mt] then
218 to_explore[mt] = name .. ".<metatable>"
219 explored[mt] = true
220 end
221 mt = th_getfenv(exploring)
222 if mt and not explored[mt] then
223 to_explore[mt] = name .. ".<env>"
224 explored[mt] = true
225 end
226 end
227
228 return "<no name>"
229 end
230
231 strict_declare_global "SaveGame"
232 strict_declare_global "SaveGameFile"
233 strict_declare_global "LoadGame"
234 strict_declare_global "LoadGameFile"
235
236 function SaveGame()
237 local state = {
238 ui = TheApp.ui,
239 world = TheApp.world,
240 map = TheApp.map,
241 random = math.randomdump(),
242 }
243 state.map:prepareForSave()
244 --local status, res = xpcall(function()
245 local result, err, obj = persist.dump(state, MakePermanentObjectsTable(false))
246 state.map:afterSave()
247 if not result then
248 print(obj, NameOf(obj)) -- for debugging
249 error(err)
250 else
251 return result
252 end
253 --end, persist.errcatch)
254 end
255
256 --! Save a game to disk.
257 --!param filename (string) Path of the file to write.
258 function SaveGameFile(filename)
259 local data = SaveGame()
260 local f = TheApp:writeToFileOrTmp(filename, "wb")
261 f:write(data)
262 f:close()
263 end
264
265 --! Compatibility function to work out the game's graphics set
266 --!param map The savegame map data
267 --!param world The savegame world data
268 local function gfxSetHeuristic(map, world)
269 -- First eliminate all but the first campaign level (same in demo and full)
270 local toxicity = tostring(_S.level_names[1]:upper())
271 local level_name = tostring(map.level_name)
272 if level_name ~= toxicity then
273 return "full"
274 end
275 -- Now check a disease only in the demo (baldness)
276 for _, disease in ipairs(world.available_diseases) do
277 if disease.id == "baldness" then
278 return "demo"
279 end
280 end
281 return "full"
282 end
283
284 --! Puts loaded file into the game
285 --!param data The file
286 function LoadGame(data)
287 --local status, res = xpcall(function()
288 local objtable = MakePermanentObjectsTable(true)
289 local state = assert(persist.load(data, objtable))
290 -- Graphics set types were defined in savegame version 166+.
291 if not state.world.gfx_set then
292 state.world.gfx_set = gfxSetHeuristic(state.map, state.world)
293 end
294 -- Check the game we're loading is compatible with program
295 if not TheApp:checkCompatibility(state.world.savegame_version, state.world.gfx_set) then return end
296 state.ui:resync(TheApp.ui)
297 TheApp.ui = state.ui
298 TheApp.world = state.world
299 TheApp.map = state.map
300 math.randomseed(state.random)
301
302 local cursor = TheApp.ui.cursor
303 TheApp.ui.cursor = nil
304 TheApp.ui:setCursor(cursor)
305 -- The menu bar is a permanent object, so its ui field needs updating to
306 -- the depersisted ui value.
307 TheApp.ui.menu_bar.ui = TheApp.ui
308 TheApp.ui.menu_bar:onChangeLanguage()
309 --end, persist.errcatch)
310 TheApp.world.map:registerTemperatureDisplayMethod()
311 -- TODO: sound effects on/off are saved too, but should be a global value?
312 TheApp.audio:playSoundEffects(TheApp.config.play_sounds)
313 TheApp:afterLoad()
314 TheApp.world:resetAnimations()
315 TheApp.ui:onChangeResolution()
316 -- Check if the blueish tone should be applied.
317 -- Note: Blue filter control should be handled from world or ui, however when
318 -- loading a game we should let persistence do it.
319 TheApp.world:updateUserActionsAllowed()
320 TheApp.world:updateScreenBlueFilter()
321 end
322
323 function LoadGameFile(filename)
324 local f = assert(io.open(filename, "rb"))
325 local data = f:read("*a")
326 f:close()
327 LoadGame(data)
328 end