Omnicleanup: header cleanup, add ModApiUtil shared between game and mainmenu
[oweals/minetest.git] / src / rollback.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "rollback.h"
21 #include <fstream>
22 #include <list>
23 #include <sstream>
24 #include "log.h"
25 #include "mapnode.h"
26 #include "gamedef.h"
27 #include "nodedef.h"
28 #include "util/serialize.h"
29 #include "util/string.h"
30 #include "util/numeric.h"
31 #include "inventorymanager.h" // deserializing InventoryLocations
32
33 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
34
35 #define POINTS_PER_NODE (16.0)
36
37 // Get nearness factor for subject's action for this action
38 // Return value: 0 = impossible, >0 = factor
39 static float getSuspectNearness(bool is_guess, v3s16 suspect_p, int suspect_t,
40                 v3s16 action_p, int action_t)
41 {
42         // Suspect cannot cause things in the past
43         if(action_t < suspect_t)
44                 return 0; // 0 = cannot be
45         // Start from 100
46         int f = 100;
47         // Distance (1 node = -x points)
48         f -= POINTS_PER_NODE * intToFloat(suspect_p, 1).getDistanceFrom(intToFloat(action_p, 1));
49         // Time (1 second = -x points)
50         f -= 1 * (action_t - suspect_t);
51         // If is a guess, halve the points
52         if(is_guess)
53                 f *= 0.5;
54         // Limit to 0
55         if(f < 0)
56                 f = 0;
57         return f;
58 }
59
60 class RollbackManager: public IRollbackManager
61 {
62 public:
63         // IRollbackManager interface
64
65         void reportAction(const RollbackAction &action_)
66         {
67                 // Ignore if not important
68                 if(!action_.isImportant(m_gamedef))
69                         return;
70                 RollbackAction action = action_;
71                 action.unix_time = time(0);
72                 // Figure out actor
73                 action.actor = m_current_actor;
74                 action.actor_is_guess = m_current_actor_is_guess;
75                 // If actor is not known, find out suspect or cancel
76                 if(action.actor.empty()){
77                         v3s16 p;
78                         if(!action.getPosition(&p))
79                                 return;
80                         action.actor = getSuspect(p, 83, 1);
81                         if(action.actor.empty())
82                                 return;
83                         action.actor_is_guess = true;
84                 }
85                 infostream<<"RollbackManager::reportAction():"
86                                 <<" time="<<action.unix_time
87                                 <<" actor=\""<<action.actor<<"\""
88                                 <<(action.actor_is_guess?" (guess)":"")
89                                 <<" action="<<action.toString()
90                                 <<std::endl;
91                 addAction(action);
92         }
93         std::string getActor()
94         {
95                 return m_current_actor;
96         }
97         bool isActorGuess()
98         {
99                 return m_current_actor_is_guess;
100         }
101         void setActor(const std::string &actor, bool is_guess)
102         {
103                 m_current_actor = actor;
104                 m_current_actor_is_guess = is_guess;
105         }
106         std::string getSuspect(v3s16 p, float nearness_shortcut, float min_nearness)
107         {
108                 if(m_current_actor != "")
109                         return m_current_actor;
110                 int cur_time = time(0);
111                 int first_time = cur_time - (100-min_nearness);
112                 RollbackAction likely_suspect;
113                 float likely_suspect_nearness = 0;
114                 for(std::list<RollbackAction>::const_reverse_iterator
115                                 i = m_action_latest_buffer.rbegin();
116                                 i != m_action_latest_buffer.rend(); i++)
117                 {
118                         if(i->unix_time < first_time)
119                                 break;
120                         if(i->actor == "")
121                                 continue;
122                         // Find position of suspect or continue
123                         v3s16 suspect_p;
124                         if(!i->getPosition(&suspect_p))
125                                 continue;
126                         float f = getSuspectNearness(i->actor_is_guess, suspect_p,
127                                         i->unix_time, p, cur_time);
128                         if(f >= min_nearness && f > likely_suspect_nearness){
129                                 likely_suspect_nearness = f;
130                                 likely_suspect = *i;
131                                 if(likely_suspect_nearness >= nearness_shortcut)
132                                         break;
133                         }
134                 }
135                 // No likely suspect was found
136                 if(likely_suspect_nearness == 0)
137                         return "";
138                 // Likely suspect was found
139                 return likely_suspect.actor;
140         }
141         void flush()
142         {
143                 infostream<<"RollbackManager::flush()"<<std::endl;
144                 std::ofstream of(m_filepath.c_str(), std::ios::app);
145                 if(!of.good()){
146                         errorstream<<"RollbackManager::flush(): Could not open file "
147                                         <<"for appending: \""<<m_filepath<<"\""<<std::endl;
148                         return;
149                 }
150                 for(std::list<RollbackAction>::const_iterator
151                                 i = m_action_todisk_buffer.begin();
152                                 i != m_action_todisk_buffer.end(); i++)
153                 {
154                         // Do not save stuff that does not have an actor
155                         if(i->actor == "")
156                                 continue;
157                         of<<i->unix_time;
158                         of<<" ";
159                         of<<serializeJsonString(i->actor);
160                         of<<" ";
161                         of<<i->toString();
162                         if(i->actor_is_guess){
163                                 of<<" ";
164                                 of<<"actor_is_guess";
165                         }
166                         of<<std::endl;
167                 }
168                 m_action_todisk_buffer.clear();
169         }
170         
171         // Other
172
173         RollbackManager(const std::string &filepath, IGameDef *gamedef):
174                 m_filepath(filepath),
175                 m_gamedef(gamedef),
176                 m_current_actor_is_guess(false)
177         {
178                 infostream<<"RollbackManager::RollbackManager("<<filepath<<")"
179                                 <<std::endl;
180         }
181         ~RollbackManager()
182         {
183                 infostream<<"RollbackManager::~RollbackManager()"<<std::endl;
184                 flush();
185         }
186
187         void addAction(const RollbackAction &action)
188         {
189                 m_action_todisk_buffer.push_back(action);
190                 m_action_latest_buffer.push_back(action);
191
192                 // Flush to disk sometimes
193                 if(m_action_todisk_buffer.size() >= 100)
194                         flush();
195         }
196         
197         bool readFile(std::list<RollbackAction> &dst)
198         {
199                 // Load whole file to memory
200                 std::ifstream f(m_filepath.c_str(), std::ios::in);
201                 if(!f.good()){
202                         errorstream<<"RollbackManager::readFile(): Could not open "
203                                         <<"file for reading: \""<<m_filepath<<"\""<<std::endl;
204                         return false;
205                 }
206                 for(;;){
207                         if(f.eof() || !f.good())
208                                 break;
209                         std::string line;
210                         std::getline(f, line);
211                         line = trim(line);
212                         if(line == "")
213                                 continue;
214                         std::istringstream is(line);
215                         
216                         try{
217                                 std::string action_time_raw;
218                                 std::getline(is, action_time_raw, ' ');
219                                 std::string action_actor;
220                                 try{
221                                         action_actor = deSerializeJsonString(is);
222                                 }catch(SerializationError &e){
223                                         errorstream<<"RollbackManager: Error deserializing actor: "
224                                                         <<e.what()<<std::endl;
225                                         throw e;
226                                 }
227                                 RollbackAction action;
228                                 action.unix_time = stoi(action_time_raw);
229                                 action.actor = action_actor;
230                                 int c = is.get();
231                                 if(c != ' '){
232                                         is.putback(c);
233                                         throw SerializationError("readFile(): second ' ' not found");
234                                 }
235                                 action.fromStream(is);
236                                 /*infostream<<"RollbackManager::readFile(): Action from disk: "
237                                                 <<action.toString()<<std::endl;*/
238                                 dst.push_back(action);
239                         }
240                         catch(SerializationError &e){
241                                 errorstream<<"RollbackManager: Error on line: "<<line<<std::endl;
242                                 errorstream<<"RollbackManager: ^ error: "<<e.what()<<std::endl;
243                         }
244                 }
245                 return true;
246         }
247
248         std::list<RollbackAction> getEntriesSince(int first_time)
249         {
250                 infostream<<"RollbackManager::getEntriesSince("<<first_time<<")"<<std::endl;
251                 // Collect enough data to this buffer
252                 std::list<RollbackAction> action_buffer;
253                 // Use the latest buffer if it is long enough
254                 if(!m_action_latest_buffer.empty() &&
255                                 m_action_latest_buffer.begin()->unix_time <= first_time){
256                         action_buffer = m_action_latest_buffer;
257                 }
258                 else
259                 {
260                         // Save all remaining stuff
261                         flush();
262                         // Load whole file to memory
263                         bool good = readFile(action_buffer);
264                         if(!good){
265                                 errorstream<<"RollbackManager::getEntriesSince(): Failed to"
266                                                 <<" open file; using data in memory."<<std::endl;
267                                 action_buffer = m_action_latest_buffer;
268                         }
269                 }
270                 return action_buffer;
271         }
272         
273         std::string getLastNodeActor(v3s16 p, int range, int seconds,
274                         v3s16 *act_p, int *act_seconds)
275         {
276                 infostream<<"RollbackManager::getLastNodeActor("<<PP(p)
277                                 <<", "<<seconds<<")"<<std::endl;
278                 // Figure out time
279                 int cur_time = time(0);
280                 int first_time = cur_time - seconds;
281
282                 std::list<RollbackAction> action_buffer = getEntriesSince(first_time);
283                 
284                 std::list<RollbackAction> result;
285
286                 for(std::list<RollbackAction>::const_reverse_iterator
287                                 i = action_buffer.rbegin();
288                                 i != action_buffer.rend(); i++)
289                 {
290                         if(i->unix_time < first_time)
291                                 break;
292
293                         // Find position of action or continue
294                         v3s16 action_p;
295                         if(!i->getPosition(&action_p))
296                                 continue;
297
298                         if(range == 0){
299                                 if(action_p != p)
300                                         continue;
301                         } else {
302                                 if(abs(action_p.X - p.X) > range ||
303                                                 abs(action_p.Y - p.Y) > range ||
304                                                 abs(action_p.Z - p.Z) > range)
305                                         continue;
306                         }
307                         
308                         if(act_p)
309                                 *act_p = action_p;
310                         if(act_seconds)
311                                 *act_seconds = cur_time - i->unix_time;
312                         return i->actor;
313                 }
314                 return "";
315         }
316
317         std::list<RollbackAction> getRevertActions(const std::string &actor_filter,
318                         int seconds)
319         {
320                 infostream<<"RollbackManager::getRevertActions("<<actor_filter
321                                 <<", "<<seconds<<")"<<std::endl;
322                 // Figure out time
323                 int cur_time = time(0);
324                 int first_time = cur_time - seconds;
325                 
326                 std::list<RollbackAction> action_buffer = getEntriesSince(first_time);
327                 
328                 std::list<RollbackAction> result;
329
330                 for(std::list<RollbackAction>::const_reverse_iterator
331                                 i = action_buffer.rbegin();
332                                 i != action_buffer.rend(); i++)
333                 {
334                         if(i->unix_time < first_time)
335                                 break;
336                         if(i->actor != actor_filter)
337                                 continue;
338                         const RollbackAction &action = *i;
339                         /*infostream<<"RollbackManager::revertAction(): Should revert"
340                                         <<" time="<<action.unix_time
341                                         <<" actor=\""<<action.actor<<"\""
342                                         <<" action="<<action.toString()
343                                         <<std::endl;*/
344                         result.push_back(action);
345                 }
346
347                 return result;
348         }
349
350 private:
351         std::string m_filepath;
352         IGameDef *m_gamedef;
353         std::string m_current_actor;
354         bool m_current_actor_is_guess;
355         std::list<RollbackAction> m_action_todisk_buffer;
356         std::list<RollbackAction> m_action_latest_buffer;
357 };
358
359 IRollbackManager *createRollbackManager(const std::string &filepath, IGameDef *gamedef)
360 {
361         return new RollbackManager(filepath, gamedef);
362 }
363
364